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"
55 #define BLKDISCARD _IO(0x12,119)
58 static int btrfs_scan_done = 0;
60 static int rand_seed_initlized = 0;
61 static unsigned short rand_seed[3];
63 struct btrfs_config bconf;
66 * Discard the given range in one go
68 static int discard_range(int fd, u64 start, u64 len)
70 u64 range[2] = { start, len };
72 if (ioctl(fd, BLKDISCARD, &range) < 0)
78 * Discard blocks in the given range in 1G chunks, the process is interruptible
80 static int discard_blocks(int fd, u64 start, u64 len)
84 u64 chunk_size = min_t(u64, len, SZ_1G);
87 ret = discard_range(fd, start, chunk_size);
97 int test_uuid_unique(char *fs_uuid)
100 blkid_dev_iterate iter = NULL;
101 blkid_dev dev = NULL;
102 blkid_cache cache = NULL;
104 if (blkid_get_cache(&cache, NULL) < 0) {
105 printf("ERROR: lblkid cache get failed\n");
108 blkid_probe_all(cache);
109 iter = blkid_dev_iterate_begin(cache);
110 blkid_dev_set_search(iter, "UUID", fs_uuid);
112 while (blkid_dev_next(iter, &dev) == 0) {
113 dev = blkid_verify(cache, dev);
120 blkid_dev_iterate_end(iter);
121 blkid_put_cache(cache);
127 * Insert a root item for temporary tree root
129 * Only used in make_btrfs_v2().
131 #define VERSION_TO_STRING3(a,b,c) #a "." #b "." #c, KERNEL_VERSION(a,b,c)
132 #define VERSION_TO_STRING2(a,b) #a "." #b, KERNEL_VERSION(a,b,0)
135 * Feature stability status and versions: compat <= safe <= default
137 static const struct btrfs_fs_feature {
140 const char *sysfs_name;
142 * Compatibility with kernel of given version. Filesystem can be
145 const char *compat_str;
148 * Considered safe for use, but is not on by default, even if the
149 * kernel supports the feature.
151 const char *safe_str;
154 * Considered safe for use and will be turned on by default if
155 * supported by the running kernel.
157 const char *default_str;
160 } mkfs_features[] = {
161 { "mixed-bg", BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS,
163 VERSION_TO_STRING3(2,6,37),
164 VERSION_TO_STRING3(2,6,37),
166 "mixed data and metadata block groups" },
167 { "extref", BTRFS_FEATURE_INCOMPAT_EXTENDED_IREF,
169 VERSION_TO_STRING2(3,7),
170 VERSION_TO_STRING2(3,12),
171 VERSION_TO_STRING2(3,12),
172 "increased hardlink limit per file to 65536" },
173 { "raid56", BTRFS_FEATURE_INCOMPAT_RAID56,
175 VERSION_TO_STRING2(3,9),
178 "raid56 extended format" },
179 { "skinny-metadata", BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA,
181 VERSION_TO_STRING2(3,10),
182 VERSION_TO_STRING2(3,18),
183 VERSION_TO_STRING2(3,18),
184 "reduced-size metadata extent refs" },
185 { "no-holes", BTRFS_FEATURE_INCOMPAT_NO_HOLES,
187 VERSION_TO_STRING2(3,14),
188 VERSION_TO_STRING2(4,0),
190 "no explicit hole extents for files" },
191 /* Keep this one last */
192 { "list-all", BTRFS_FEATURE_LIST_ALL, NULL }
195 static int parse_one_fs_feature(const char *name, u64 *flags)
200 for (i = 0; i < ARRAY_SIZE(mkfs_features); i++) {
201 if (name[0] == '^' &&
202 !strcmp(mkfs_features[i].name, name + 1)) {
203 *flags &= ~ mkfs_features[i].flag;
205 } else if (!strcmp(mkfs_features[i].name, name)) {
206 *flags |= mkfs_features[i].flag;
214 void btrfs_parse_features_to_string(char *buf, u64 flags)
220 for (i = 0; i < ARRAY_SIZE(mkfs_features); i++) {
221 if (flags & mkfs_features[i].flag) {
224 strcat(buf, mkfs_features[i].name);
229 void btrfs_process_fs_features(u64 flags)
233 for (i = 0; i < ARRAY_SIZE(mkfs_features); i++) {
234 if (flags & mkfs_features[i].flag) {
235 printf("Turning ON incompat feature '%s': %s\n",
236 mkfs_features[i].name,
237 mkfs_features[i].desc);
242 void btrfs_list_all_fs_features(u64 mask_disallowed)
246 fprintf(stderr, "Filesystem features available:\n");
247 for (i = 0; i < ARRAY_SIZE(mkfs_features) - 1; i++) {
248 const struct btrfs_fs_feature *feat = &mkfs_features[i];
250 if (feat->flag & mask_disallowed)
252 fprintf(stderr, "%-20s- %s (0x%llx", feat->name, feat->desc,
254 if (feat->compat_ver)
255 fprintf(stderr, ", compat=%s", feat->compat_str);
257 fprintf(stderr, ", safe=%s", feat->safe_str);
258 if (feat->default_ver)
259 fprintf(stderr, ", default=%s", feat->default_str);
260 fprintf(stderr, ")\n");
265 * Return NULL if all features were parsed fine, otherwise return the name of
266 * the first unparsed.
268 char* btrfs_parse_fs_features(char *namelist, u64 *flags)
271 char *save_ptr = NULL; /* Satisfy static checkers */
273 for (this_char = strtok_r(namelist, ",", &save_ptr);
275 this_char = strtok_r(NULL, ",", &save_ptr)) {
276 if (parse_one_fs_feature(this_char, flags))
283 void print_kernel_version(FILE *stream, u32 version)
287 v[0] = version & 0xFF;
288 v[1] = (version >> 8) & 0xFF;
289 v[2] = version >> 16;
290 fprintf(stream, "%u.%u", v[2], v[1]);
292 fprintf(stream, ".%u", v[0]);
295 u32 get_running_kernel_version(void)
297 struct utsname utsbuf;
299 char *saveptr = NULL;
303 if (strcmp(utsbuf.sysname, "Linux") != 0) {
304 error("unsupported system: %s", utsbuf.sysname);
308 tmp = strchr(utsbuf.release, '-');
312 tmp = strtok_r(utsbuf.release, ".", &saveptr);
313 if (!string_is_numerical(tmp))
315 version = atoi(tmp) << 16;
316 tmp = strtok_r(NULL, ".", &saveptr);
317 if (!string_is_numerical(tmp))
319 version |= atoi(tmp) << 8;
320 tmp = strtok_r(NULL, ".", &saveptr);
322 if (!string_is_numerical(tmp))
324 version |= atoi(tmp);
330 u64 btrfs_device_size(int fd, struct stat *st)
333 if (S_ISREG(st->st_mode)) {
336 if (!S_ISBLK(st->st_mode)) {
339 if (ioctl(fd, BLKGETSIZE64, &size) >= 0) {
345 static int zero_blocks(int fd, off_t start, size_t len)
347 char *buf = malloc(len);
354 written = pwrite(fd, buf, len, start);
361 #define ZERO_DEV_BYTES SZ_2M
363 /* don't write outside the device by clamping the region to the device size */
364 static int zero_dev_clamped(int fd, off_t start, ssize_t len, u64 dev_size)
366 off_t end = max(start, start + len);
369 /* and don't overwrite the disk labels on sparc */
370 start = max(start, 1024);
371 end = max(end, 1024);
374 start = min_t(u64, start, dev_size);
375 end = min_t(u64, end, dev_size);
377 return zero_blocks(fd, start, end - start);
380 int btrfs_add_to_fsid(struct btrfs_trans_handle *trans,
381 struct btrfs_root *root, int fd, const char *path,
382 u64 device_total_bytes, u32 io_width, u32 io_align,
385 struct btrfs_super_block *disk_super;
386 struct btrfs_super_block *super = root->fs_info->super_copy;
387 struct btrfs_device *device;
388 struct btrfs_dev_item *dev_item;
394 device_total_bytes = (device_total_bytes / sectorsize) * sectorsize;
396 device = calloc(1, sizeof(*device));
401 buf = calloc(1, sectorsize);
407 disk_super = (struct btrfs_super_block *)buf;
408 dev_item = &disk_super->dev_item;
410 uuid_generate(device->uuid);
413 device->io_width = io_width;
414 device->io_align = io_align;
415 device->sector_size = sectorsize;
417 device->writeable = 1;
418 device->total_bytes = device_total_bytes;
419 device->bytes_used = 0;
420 device->total_ios = 0;
421 device->dev_root = root->fs_info->dev_root;
422 device->name = strdup(path);
428 INIT_LIST_HEAD(&device->dev_list);
429 ret = btrfs_add_device(trans, root, device);
433 fs_total_bytes = btrfs_super_total_bytes(super) + device_total_bytes;
434 btrfs_set_super_total_bytes(super, fs_total_bytes);
436 num_devs = btrfs_super_num_devices(super) + 1;
437 btrfs_set_super_num_devices(super, num_devs);
439 memcpy(disk_super, super, sizeof(*disk_super));
441 btrfs_set_super_bytenr(disk_super, BTRFS_SUPER_INFO_OFFSET);
442 btrfs_set_stack_device_id(dev_item, device->devid);
443 btrfs_set_stack_device_type(dev_item, device->type);
444 btrfs_set_stack_device_io_align(dev_item, device->io_align);
445 btrfs_set_stack_device_io_width(dev_item, device->io_width);
446 btrfs_set_stack_device_sector_size(dev_item, device->sector_size);
447 btrfs_set_stack_device_total_bytes(dev_item, device->total_bytes);
448 btrfs_set_stack_device_bytes_used(dev_item, device->bytes_used);
449 memcpy(&dev_item->uuid, device->uuid, BTRFS_UUID_SIZE);
451 ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
452 BUG_ON(ret != sectorsize);
455 list_add(&device->dev_list, &root->fs_info->fs_devices->devices);
456 device->fs_devices = root->fs_info->fs_devices;
465 static int btrfs_wipe_existing_sb(int fd)
467 const char *off = NULL;
472 blkid_probe pr = NULL;
474 pr = blkid_new_probe();
478 if (blkid_probe_set_device(pr, fd, 0, 0)) {
483 ret = blkid_probe_lookup_value(pr, "SBMAGIC_OFFSET", &off, NULL);
485 ret = blkid_probe_lookup_value(pr, "SBMAGIC", NULL, &len);
487 if (ret || len == 0 || off == NULL) {
489 * If lookup fails, the probe did not find any values, eg. for
490 * a file image or a loop device. Soft error.
496 offset = strtoll(off, NULL, 10);
497 if (len > sizeof(buf))
501 ret = pwrite(fd, buf, len, offset);
503 error("cannot wipe existing superblock: %s", strerror(errno));
505 } else if (ret != len) {
506 error("cannot wipe existing superblock: wrote %d of %zd", ret, len);
512 blkid_free_probe(pr);
516 int btrfs_prepare_device(int fd, const char *file, u64 *block_count_ret,
517 u64 max_block_count, unsigned opflags)
523 ret = fstat(fd, &st);
525 error("unable to stat %s: %s", file, strerror(errno));
529 block_count = btrfs_device_size(fd, &st);
530 if (block_count == 0) {
531 error("unable to determine size of %s", file);
535 block_count = min(block_count, max_block_count);
537 if (opflags & PREP_DEVICE_DISCARD) {
539 * We intentionally ignore errors from the discard ioctl. It
540 * is not necessary for the mkfs functionality but just an
543 if (discard_range(fd, 0, 0) == 0) {
544 if (opflags & PREP_DEVICE_VERBOSE)
545 printf("Performing full device TRIM %s (%s) ...\n",
546 file, pretty_size(block_count));
547 discard_blocks(fd, 0, block_count);
551 ret = zero_dev_clamped(fd, 0, ZERO_DEV_BYTES, block_count);
552 for (i = 0 ; !ret && i < BTRFS_SUPER_MIRROR_MAX; i++)
553 ret = zero_dev_clamped(fd, btrfs_sb_offset(i),
554 BTRFS_SUPER_INFO_SIZE, block_count);
555 if (!ret && (opflags & PREP_DEVICE_ZERO_END))
556 ret = zero_dev_clamped(fd, block_count - ZERO_DEV_BYTES,
557 ZERO_DEV_BYTES, block_count);
560 error("failed to zero device '%s': %s", file, strerror(-ret));
564 ret = btrfs_wipe_existing_sb(fd);
566 error("cannot wipe superblocks on %s", file);
570 *block_count_ret = block_count;
574 int btrfs_make_root_dir(struct btrfs_trans_handle *trans,
575 struct btrfs_root *root, u64 objectid)
578 struct btrfs_inode_item inode_item;
579 time_t now = time(NULL);
581 memset(&inode_item, 0, sizeof(inode_item));
582 btrfs_set_stack_inode_generation(&inode_item, trans->transid);
583 btrfs_set_stack_inode_size(&inode_item, 0);
584 btrfs_set_stack_inode_nlink(&inode_item, 1);
585 btrfs_set_stack_inode_nbytes(&inode_item, root->nodesize);
586 btrfs_set_stack_inode_mode(&inode_item, S_IFDIR | 0755);
587 btrfs_set_stack_timespec_sec(&inode_item.atime, now);
588 btrfs_set_stack_timespec_nsec(&inode_item.atime, 0);
589 btrfs_set_stack_timespec_sec(&inode_item.ctime, now);
590 btrfs_set_stack_timespec_nsec(&inode_item.ctime, 0);
591 btrfs_set_stack_timespec_sec(&inode_item.mtime, now);
592 btrfs_set_stack_timespec_nsec(&inode_item.mtime, 0);
593 btrfs_set_stack_timespec_sec(&inode_item.otime, now);
594 btrfs_set_stack_timespec_nsec(&inode_item.otime, 0);
596 if (root->fs_info->tree_root == root)
597 btrfs_set_super_root_dir(root->fs_info->super_copy, objectid);
599 ret = btrfs_insert_inode(trans, root, objectid, &inode_item);
603 ret = btrfs_insert_inode_ref(trans, root, "..", 2, objectid, objectid, 0);
607 btrfs_set_root_dirid(&root->root_item, objectid);
614 * checks if a path is a block device node
615 * Returns negative errno on failure, otherwise
616 * returns 1 for blockdev, 0 for not-blockdev
618 int is_block_device(const char *path)
622 if (stat(path, &statbuf) < 0)
625 return !!S_ISBLK(statbuf.st_mode);
629 * check if given path is a mount point
630 * return 1 if yes. 0 if no. -1 for error
632 int is_mount_point(const char *path)
638 f = setmntent("/proc/self/mounts", "r");
642 while ((mnt = getmntent(f)) != NULL) {
643 if (strcmp(mnt->mnt_dir, path))
652 static int is_reg_file(const char *path)
656 if (stat(path, &statbuf) < 0)
658 return S_ISREG(statbuf.st_mode);
662 * This function checks if the given input parameter is
664 * return <0 : some error in the given input
665 * return BTRFS_ARG_UNKNOWN: unknown input
666 * return BTRFS_ARG_UUID: given input is uuid
667 * return BTRFS_ARG_MNTPOINT: given input is path
668 * return BTRFS_ARG_REG: given input is regular file
669 * return BTRFS_ARG_BLKDEV: given input is block device
671 int check_arg_type(const char *input)
679 if (realpath(input, path)) {
680 if (is_block_device(path) == 1)
681 return BTRFS_ARG_BLKDEV;
683 if (is_mount_point(path) == 1)
684 return BTRFS_ARG_MNTPOINT;
686 if (is_reg_file(path))
687 return BTRFS_ARG_REG;
689 return BTRFS_ARG_UNKNOWN;
692 if (strlen(input) == (BTRFS_UUID_UNPARSED_SIZE - 1) &&
693 !uuid_parse(input, uuid))
694 return BTRFS_ARG_UUID;
696 return BTRFS_ARG_UNKNOWN;
700 * Find the mount point for a mounted device.
701 * On success, returns 0 with mountpoint in *mp.
702 * On failure, returns -errno (not mounted yields -EINVAL)
703 * Is noisy on failures, expects to be given a mounted device.
705 int get_btrfs_mount(const char *dev, char *mp, size_t mp_size)
710 ret = is_block_device(dev);
713 error("not a block device: %s", dev);
716 error("cannot check %s: %s", dev, strerror(-ret));
721 fd = open(dev, O_RDONLY);
724 error("cannot open %s: %s", dev, strerror(errno));
728 ret = check_mounted_where(fd, dev, mp, mp_size, NULL);
731 } else { /* mounted, all good */
741 * Given a pathname, return a filehandle to:
742 * the original pathname or,
743 * if the pathname is a mounted btrfs device, to its mountpoint.
745 * On error, return -1, errno should be set.
747 int open_path_or_dev_mnt(const char *path, DIR **dirstream, int verbose)
752 if (is_block_device(path)) {
753 ret = get_btrfs_mount(path, mp, sizeof(mp));
755 /* not a mounted btrfs dev */
756 error_on(verbose, "'%s' is not a mounted btrfs device",
761 ret = open_file_or_dir(mp, dirstream);
762 error_on(verbose && ret < 0, "can't access '%s': %s",
763 path, strerror(errno));
765 ret = btrfs_open_dir(path, dirstream, 1);
772 * Do the following checks before calling open_file_or_dir():
773 * 1: path is in a btrfs filesystem
774 * 2: path is a directory
776 int btrfs_open_dir(const char *path, DIR **dirstream, int verbose)
782 if (statfs(path, &stfs) != 0) {
783 error_on(verbose, "cannot access '%s': %s", path,
788 if (stfs.f_type != BTRFS_SUPER_MAGIC) {
789 error_on(verbose, "not a btrfs filesystem: %s", path);
793 if (stat(path, &st) != 0) {
794 error_on(verbose, "cannot access '%s': %s", path,
799 if (!S_ISDIR(st.st_mode)) {
800 error_on(verbose, "not a directory: %s", path);
804 ret = open_file_or_dir(path, dirstream);
806 error_on(verbose, "cannot access '%s': %s", path,
813 /* checks if a device is a loop device */
814 static int is_loop_device (const char* device) {
817 if(stat(device, &statbuf) < 0)
820 return (S_ISBLK(statbuf.st_mode) &&
821 MAJOR(statbuf.st_rdev) == LOOP_MAJOR);
825 * Takes a loop device path (e.g. /dev/loop0) and returns
826 * the associated file (e.g. /images/my_btrfs.img) using
829 static int resolve_loop_device_with_loopdev(const char* loop_dev, char* loop_file)
833 struct loop_info64 lo64;
835 fd = open(loop_dev, O_RDONLY | O_NONBLOCK);
838 ret = ioctl(fd, LOOP_GET_STATUS64, &lo64);
844 memcpy(loop_file, lo64.lo_file_name, sizeof(lo64.lo_file_name));
845 loop_file[sizeof(lo64.lo_file_name)] = 0;
853 /* Takes a loop device path (e.g. /dev/loop0) and returns
854 * the associated file (e.g. /images/my_btrfs.img) */
855 static int resolve_loop_device(const char* loop_dev, char* loop_file,
862 char real_loop_dev[PATH_MAX];
864 if (!realpath(loop_dev, real_loop_dev))
866 snprintf(p, PATH_MAX, "/sys/block/%s/loop/backing_file", strrchr(real_loop_dev, '/'));
867 if (!(f = fopen(p, "r"))) {
870 * It's possibly a partitioned loop device, which is
871 * resolvable with loopdev API.
873 return resolve_loop_device_with_loopdev(loop_dev, loop_file);
877 snprintf(fmt, 20, "%%%i[^\n]", max_len-1);
878 ret = fscanf(f, fmt, loop_file);
887 * Checks whether a and b are identical or device
888 * files associated with the same block device
890 static int is_same_blk_file(const char* a, const char* b)
892 struct stat st_buf_a, st_buf_b;
893 char real_a[PATH_MAX];
894 char real_b[PATH_MAX];
896 if (!realpath(a, real_a))
897 strncpy_null(real_a, a);
899 if (!realpath(b, real_b))
900 strncpy_null(real_b, b);
902 /* Identical path? */
903 if (strcmp(real_a, real_b) == 0)
906 if (stat(a, &st_buf_a) < 0 || stat(b, &st_buf_b) < 0) {
912 /* Same blockdevice? */
913 if (S_ISBLK(st_buf_a.st_mode) && S_ISBLK(st_buf_b.st_mode) &&
914 st_buf_a.st_rdev == st_buf_b.st_rdev) {
919 if (st_buf_a.st_dev == st_buf_b.st_dev &&
920 st_buf_a.st_ino == st_buf_b.st_ino) {
927 /* checks if a and b are identical or device
928 * files associated with the same block device or
929 * if one file is a loop device that uses the other
932 static int is_same_loop_file(const char* a, const char* b)
934 char res_a[PATH_MAX];
935 char res_b[PATH_MAX];
936 const char* final_a = NULL;
937 const char* final_b = NULL;
940 /* Resolve a if it is a loop device */
941 if((ret = is_loop_device(a)) < 0) {
946 ret = resolve_loop_device(a, res_a, sizeof(res_a));
957 /* Resolve b if it is a loop device */
958 if ((ret = is_loop_device(b)) < 0) {
963 ret = resolve_loop_device(b, res_b, sizeof(res_b));
974 return is_same_blk_file(final_a, final_b);
977 /* Checks if a file exists and is a block or regular file*/
978 static int is_existing_blk_or_reg_file(const char* filename)
982 if(stat(filename, &st_buf) < 0) {
989 return (S_ISBLK(st_buf.st_mode) || S_ISREG(st_buf.st_mode));
992 /* Checks if a file is used (directly or indirectly via a loop device)
993 * by a device in fs_devices
995 static int blk_file_in_dev_list(struct btrfs_fs_devices* fs_devices,
999 struct list_head *head;
1000 struct list_head *cur;
1001 struct btrfs_device *device;
1003 head = &fs_devices->devices;
1004 list_for_each(cur, head) {
1005 device = list_entry(cur, struct btrfs_device, dev_list);
1007 if((ret = is_same_loop_file(device->name, file)))
1015 * Resolve a pathname to a device mapper node to /dev/mapper/<name>
1016 * Returns NULL on invalid input or malloc failure; Other failures
1017 * will be handled by the caller using the input pathame.
1019 char *canonicalize_dm_name(const char *ptname)
1023 char path[PATH_MAX], name[PATH_MAX], *res = NULL;
1025 if (!ptname || !*ptname)
1028 snprintf(path, sizeof(path), "/sys/block/%s/dm/name", ptname);
1029 if (!(f = fopen(path, "r")))
1032 /* read <name>\n from sysfs */
1033 if (fgets(name, sizeof(name), f) && (sz = strlen(name)) > 1) {
1034 name[sz - 1] = '\0';
1035 snprintf(path, sizeof(path), "/dev/mapper/%s", name);
1037 if (access(path, F_OK) == 0)
1045 * Resolve a pathname to a canonical device node, e.g. /dev/sda1 or
1046 * to a device mapper pathname.
1047 * Returns NULL on invalid input or malloc failure; Other failures
1048 * will be handled by the caller using the input pathame.
1050 char *canonicalize_path(const char *path)
1052 char *canonical, *p;
1054 if (!path || !*path)
1057 canonical = realpath(path, NULL);
1059 return strdup(path);
1060 p = strrchr(canonical, '/');
1061 if (p && strncmp(p, "/dm-", 4) == 0 && isdigit(*(p + 4))) {
1062 char *dm = canonicalize_dm_name(p + 1);
1073 * returns 1 if the device was mounted, < 0 on error or 0 if everything
1074 * is safe to continue.
1076 int check_mounted(const char* file)
1081 fd = open(file, O_RDONLY);
1083 error("mount check: cannot open %s: %s", file,
1088 ret = check_mounted_where(fd, file, NULL, 0, NULL);
1094 int check_mounted_where(int fd, const char *file, char *where, int size,
1095 struct btrfs_fs_devices **fs_dev_ret)
1100 struct btrfs_fs_devices *fs_devices_mnt = NULL;
1104 /* scan the initial device */
1105 ret = btrfs_scan_one_device(fd, file, &fs_devices_mnt,
1106 &total_devs, BTRFS_SUPER_INFO_OFFSET, SBREAD_DEFAULT);
1107 is_btrfs = (ret >= 0);
1109 /* scan other devices */
1110 if (is_btrfs && total_devs > 1) {
1111 ret = btrfs_scan_devices();
1116 /* iterate over the list of currently mounted filesystems */
1117 if ((f = setmntent ("/proc/self/mounts", "r")) == NULL)
1120 while ((mnt = getmntent (f)) != NULL) {
1122 if(strcmp(mnt->mnt_type, "btrfs") != 0)
1125 ret = blk_file_in_dev_list(fs_devices_mnt, mnt->mnt_fsname);
1127 /* ignore entries in the mount table that are not
1128 associated with a file*/
1129 if((ret = is_existing_blk_or_reg_file(mnt->mnt_fsname)) < 0)
1130 goto out_mntloop_err;
1134 ret = is_same_loop_file(file, mnt->mnt_fsname);
1138 goto out_mntloop_err;
1143 /* Did we find an entry in mnt table? */
1144 if (mnt && size && where) {
1145 strncpy(where, mnt->mnt_dir, size);
1149 *fs_dev_ret = fs_devices_mnt;
1151 ret = (mnt != NULL);
1159 struct pending_dir {
1160 struct list_head list;
1161 char name[PATH_MAX];
1164 int btrfs_register_one_device(const char *fname)
1166 struct btrfs_ioctl_vol_args args;
1170 fd = open("/dev/btrfs-control", O_RDWR);
1173 "failed to open /dev/btrfs-control, skipping device registration: %s",
1177 memset(&args, 0, sizeof(args));
1178 strncpy_null(args.name, fname);
1179 ret = ioctl(fd, BTRFS_IOC_SCAN_DEV, &args);
1181 error("device scan failed on '%s': %s", fname,
1190 * Register all devices in the fs_uuid list created in the user
1191 * space. Ensure btrfs_scan_devices() is called before this func.
1193 int btrfs_register_all_devices(void)
1197 struct btrfs_fs_devices *fs_devices;
1198 struct btrfs_device *device;
1199 struct list_head *all_uuids;
1201 all_uuids = btrfs_scanned_uuids();
1203 list_for_each_entry(fs_devices, all_uuids, list) {
1204 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1206 err = btrfs_register_one_device(device->name);
1216 int btrfs_device_already_in_root(struct btrfs_root *root, int fd,
1219 struct btrfs_super_block *disk_super;
1223 buf = malloc(BTRFS_SUPER_INFO_SIZE);
1228 ret = pread(fd, buf, BTRFS_SUPER_INFO_SIZE, super_offset);
1229 if (ret != BTRFS_SUPER_INFO_SIZE)
1233 disk_super = (struct btrfs_super_block *)buf;
1235 * Accept devices from the same filesystem, allow partially created
1238 if (btrfs_super_magic(disk_super) != BTRFS_MAGIC &&
1239 btrfs_super_magic(disk_super) != BTRFS_MAGIC_PARTIAL)
1242 if (!memcmp(disk_super->fsid, root->fs_info->super_copy->fsid,
1252 * Note: this function uses a static per-thread buffer. Do not call this
1253 * function more than 10 times within one argument list!
1255 const char *pretty_size_mode(u64 size, unsigned mode)
1257 static __thread int ps_index = 0;
1258 static __thread char ps_array[10][32];
1261 ret = ps_array[ps_index];
1264 (void)pretty_size_snprintf(size, ret, 32, mode);
1269 static const char* unit_suffix_binary[] =
1270 { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"};
1271 static const char* unit_suffix_decimal[] =
1272 { "B", "kB", "MB", "GB", "TB", "PB", "EB"};
1274 int pretty_size_snprintf(u64 size, char *str, size_t str_size, unsigned unit_mode)
1280 const char** suffix = NULL;
1287 negative = !!(unit_mode & UNITS_NEGATIVE);
1288 unit_mode &= ~UNITS_NEGATIVE;
1290 if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_RAW) {
1292 snprintf(str, str_size, "%lld", size);
1294 snprintf(str, str_size, "%llu", size);
1298 if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_BINARY) {
1301 suffix = unit_suffix_binary;
1302 } else if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_DECIMAL) {
1305 suffix = unit_suffix_decimal;
1310 fprintf(stderr, "INTERNAL ERROR: unknown unit base, mode %d\n",
1318 switch (unit_mode & UNITS_MODE_MASK) {
1319 case UNITS_TBYTES: base *= mult; num_divs++;
1320 case UNITS_GBYTES: base *= mult; num_divs++;
1321 case UNITS_MBYTES: base *= mult; num_divs++;
1322 case UNITS_KBYTES: num_divs++;
1330 s64 ssize = (s64)size;
1331 s64 last_ssize = ssize;
1333 while ((ssize < 0 ? -ssize : ssize) >= mult) {
1338 last_size = (u64)last_ssize;
1340 while (size >= mult) {
1347 * If the value is smaller than base, we didn't do any
1348 * division, in that case, base should be 1, not original
1349 * base, or the unit will be wrong
1355 if (num_divs >= ARRAY_SIZE(unit_suffix_binary)) {
1357 printf("INTERNAL ERROR: unsupported unit suffix, index %d\n",
1364 fraction = (float)(s64)last_size / base;
1366 fraction = (float)last_size / base;
1369 return snprintf(str, str_size, "%.2f%s", fraction, suffix[num_divs]);
1373 * __strncpy_null - strncpy with null termination
1374 * @dest: the target array
1375 * @src: the source string
1376 * @n: maximum bytes to copy (size of *dest)
1378 * Like strncpy, but ensures destination is null-terminated.
1380 * Copies the string pointed to by src, including the terminating null
1381 * byte ('\0'), to the buffer pointed to by dest, up to a maximum
1382 * of n bytes. Then ensure that dest is null-terminated.
1384 char *__strncpy_null(char *dest, const char *src, size_t n)
1386 strncpy(dest, src, n);
1393 * Checks to make sure that the label matches our requirements.
1395 0 if everything is safe and usable
1396 -1 if the label is too long
1398 static int check_label(const char *input)
1400 int len = strlen(input);
1402 if (len > BTRFS_LABEL_SIZE - 1) {
1403 error("label %s is too long (max %d)", input,
1404 BTRFS_LABEL_SIZE - 1);
1411 static int set_label_unmounted(const char *dev, const char *label)
1413 struct btrfs_trans_handle *trans;
1414 struct btrfs_root *root;
1417 ret = check_mounted(dev);
1419 error("checking mount status of %s failed: %d", dev, ret);
1423 error("device %s is mounted, use mount point", dev);
1427 /* Open the super_block at the default location
1428 * and as read-write.
1430 root = open_ctree(dev, 0, OPEN_CTREE_WRITES);
1431 if (!root) /* errors are printed by open_ctree() */
1434 trans = btrfs_start_transaction(root, 1);
1435 __strncpy_null(root->fs_info->super_copy->label, label, BTRFS_LABEL_SIZE - 1);
1437 btrfs_commit_transaction(trans, root);
1439 /* Now we close it since we are done. */
1444 static int set_label_mounted(const char *mount_path, const char *labelp)
1447 char label[BTRFS_LABEL_SIZE];
1449 fd = open(mount_path, O_RDONLY | O_NOATIME);
1451 error("unable to access %s: %s", mount_path, strerror(errno));
1455 memset(label, 0, sizeof(label));
1456 __strncpy_null(label, labelp, BTRFS_LABEL_SIZE - 1);
1457 if (ioctl(fd, BTRFS_IOC_SET_FSLABEL, label) < 0) {
1458 error("unable to set label of %s: %s", mount_path,
1468 int get_label_unmounted(const char *dev, char *label)
1470 struct btrfs_root *root;
1473 ret = check_mounted(dev);
1475 error("checking mount status of %s failed: %d", dev, ret);
1479 /* Open the super_block at the default location
1482 root = open_ctree(dev, 0, 0);
1486 __strncpy_null(label, root->fs_info->super_copy->label,
1487 BTRFS_LABEL_SIZE - 1);
1489 /* Now we close it since we are done. */
1495 * If a partition is mounted, try to get the filesystem label via its
1496 * mounted path rather than device. Return the corresponding error
1497 * the user specified the device path.
1499 int get_label_mounted(const char *mount_path, char *labelp)
1501 char label[BTRFS_LABEL_SIZE];
1505 fd = open(mount_path, O_RDONLY | O_NOATIME);
1507 error("unable to access %s: %s", mount_path, strerror(errno));
1511 memset(label, '\0', sizeof(label));
1512 ret = ioctl(fd, BTRFS_IOC_GET_FSLABEL, label);
1514 if (errno != ENOTTY)
1515 error("unable to get label of %s: %s", mount_path,
1522 __strncpy_null(labelp, label, BTRFS_LABEL_SIZE - 1);
1527 int get_label(const char *btrfs_dev, char *label)
1531 ret = is_existing_blk_or_reg_file(btrfs_dev);
1533 ret = get_label_mounted(btrfs_dev, label);
1535 ret = get_label_unmounted(btrfs_dev, label);
1540 int set_label(const char *btrfs_dev, const char *label)
1544 if (check_label(label))
1547 ret = is_existing_blk_or_reg_file(btrfs_dev);
1549 ret = set_label_mounted(btrfs_dev, label);
1551 ret = set_label_unmounted(btrfs_dev, label);
1557 * A not-so-good version fls64. No fascinating optimization since
1558 * no one except parse_size use it
1560 static int fls64(u64 x)
1564 for (i = 0; i <64; i++)
1565 if (x << i & (1ULL << 63))
1570 u64 parse_size(char *s)
1578 error("size value is empty");
1582 error("size value '%s' is less equal than 0", s);
1585 ret = strtoull(s, &endptr, 10);
1587 error("size value '%s' is invalid", s);
1590 if (endptr[0] && endptr[1]) {
1591 error("illegal suffix contains character '%c' in wrong position",
1596 * strtoll returns LLONG_MAX when overflow, if this happens,
1597 * need to call strtoull to get the real size
1599 if (errno == ERANGE && ret == ULLONG_MAX) {
1600 error("size value '%s' is too large for u64", s);
1604 c = tolower(endptr[0]);
1627 error("unknown size descriptor '%c'", c);
1631 /* Check whether ret * mult overflow */
1632 if (fls64(ret) + fls64(mult) - 1 > 64) {
1633 error("size value '%s' is too large for u64", s);
1640 u64 parse_qgroupid(const char *p)
1642 char *s = strchr(p, '/');
1643 const char *ptr_src_end = p + strlen(p);
1644 char *ptr_parse_end = NULL;
1653 /* Numeric format like '0/257' is the primary case */
1655 id = strtoull(p, &ptr_parse_end, 10);
1656 if (ptr_parse_end != ptr_src_end)
1660 level = strtoull(p, &ptr_parse_end, 10);
1661 if (ptr_parse_end != s)
1664 id = strtoull(s + 1, &ptr_parse_end, 10);
1665 if (ptr_parse_end != ptr_src_end)
1668 return (level << BTRFS_QGROUP_LEVEL_SHIFT) | id;
1671 /* Path format like subv at 'my_subvol' is the fallback case */
1672 ret = test_issubvolume(p);
1673 if (ret < 0 || !ret)
1675 fd = open(p, O_RDONLY);
1678 ret = lookup_path_rootid(fd, &id);
1680 error("failed to lookup root id: %s", strerror(-ret));
1687 error("invalid qgroupid or subvolume path: %s", p);
1691 int open_file_or_dir3(const char *fname, DIR **dirstream, int open_flags)
1697 ret = stat(fname, &st);
1701 if (S_ISDIR(st.st_mode)) {
1702 *dirstream = opendir(fname);
1705 fd = dirfd(*dirstream);
1706 } else if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
1707 fd = open(fname, open_flags);
1710 * we set this on purpose, in case the caller output
1711 * strerror(errno) as success
1719 closedir(*dirstream);
1726 int open_file_or_dir(const char *fname, DIR **dirstream)
1728 return open_file_or_dir3(fname, dirstream, O_RDWR);
1731 void close_file_or_dir(int fd, DIR *dirstream)
1734 closedir(dirstream);
1739 int get_device_info(int fd, u64 devid,
1740 struct btrfs_ioctl_dev_info_args *di_args)
1744 di_args->devid = devid;
1745 memset(&di_args->uuid, '\0', sizeof(di_args->uuid));
1747 ret = ioctl(fd, BTRFS_IOC_DEV_INFO, di_args);
1748 return ret < 0 ? -errno : 0;
1751 static u64 find_max_device_id(struct btrfs_ioctl_search_args *search_args,
1754 struct btrfs_dev_item *dev_item;
1755 char *buf = search_args->buf;
1757 buf += (nr_items - 1) * (sizeof(struct btrfs_ioctl_search_header)
1758 + sizeof(struct btrfs_dev_item));
1759 buf += sizeof(struct btrfs_ioctl_search_header);
1761 dev_item = (struct btrfs_dev_item *)buf;
1763 return btrfs_stack_device_id(dev_item);
1766 static int search_chunk_tree_for_fs_info(int fd,
1767 struct btrfs_ioctl_fs_info_args *fi_args)
1771 u64 start_devid = 1;
1772 struct btrfs_ioctl_search_args search_args;
1773 struct btrfs_ioctl_search_key *search_key = &search_args.key;
1775 fi_args->num_devices = 0;
1777 max_items = BTRFS_SEARCH_ARGS_BUFSIZE
1778 / (sizeof(struct btrfs_ioctl_search_header)
1779 + sizeof(struct btrfs_dev_item));
1781 search_key->tree_id = BTRFS_CHUNK_TREE_OBJECTID;
1782 search_key->min_objectid = BTRFS_DEV_ITEMS_OBJECTID;
1783 search_key->max_objectid = BTRFS_DEV_ITEMS_OBJECTID;
1784 search_key->min_type = BTRFS_DEV_ITEM_KEY;
1785 search_key->max_type = BTRFS_DEV_ITEM_KEY;
1786 search_key->min_transid = 0;
1787 search_key->max_transid = (u64)-1;
1788 search_key->nr_items = max_items;
1789 search_key->max_offset = (u64)-1;
1792 search_key->min_offset = start_devid;
1794 ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH, &search_args);
1798 fi_args->num_devices += (u64)search_key->nr_items;
1800 if (search_key->nr_items == max_items) {
1801 start_devid = find_max_device_id(&search_args,
1802 search_key->nr_items) + 1;
1806 /* get the lastest max_id to stay consistent with the num_devices */
1807 if (search_key->nr_items == 0)
1809 * last tree_search returns an empty buf, use the devid of
1810 * the last dev_item of the previous tree_search
1812 fi_args->max_id = start_devid - 1;
1814 fi_args->max_id = find_max_device_id(&search_args,
1815 search_key->nr_items);
1821 * For a given path, fill in the ioctl fs_ and info_ args.
1822 * If the path is a btrfs mountpoint, fill info for all devices.
1823 * If the path is a btrfs device, fill in only that device.
1825 * The path provided must be either on a mounted btrfs fs,
1826 * or be a mounted btrfs device.
1828 * Returns 0 on success, or a negative errno.
1830 int get_fs_info(const char *path, struct btrfs_ioctl_fs_info_args *fi_args,
1831 struct btrfs_ioctl_dev_info_args **di_ret)
1838 struct btrfs_fs_devices *fs_devices_mnt = NULL;
1839 struct btrfs_ioctl_dev_info_args *di_args;
1840 struct btrfs_ioctl_dev_info_args tmp;
1842 DIR *dirstream = NULL;
1844 memset(fi_args, 0, sizeof(*fi_args));
1846 if (is_block_device(path) == 1) {
1847 struct btrfs_super_block *disk_super;
1848 char buf[BTRFS_SUPER_INFO_SIZE];
1850 /* Ensure it's mounted, then set path to the mountpoint */
1851 fd = open(path, O_RDONLY);
1854 error("cannot open %s: %s", path, strerror(errno));
1857 ret = check_mounted_where(fd, path, mp, sizeof(mp),
1866 /* Only fill in this one device */
1867 fi_args->num_devices = 1;
1869 disk_super = (struct btrfs_super_block *)buf;
1870 ret = btrfs_read_dev_super(fd, disk_super,
1871 BTRFS_SUPER_INFO_OFFSET, 0);
1876 last_devid = btrfs_stack_device_id(&disk_super->dev_item);
1877 fi_args->max_id = last_devid;
1879 memcpy(fi_args->fsid, fs_devices_mnt->fsid, BTRFS_FSID_SIZE);
1883 /* at this point path must not be for a block device */
1884 fd = open_file_or_dir(path, &dirstream);
1890 /* fill in fi_args if not just a single device */
1891 if (fi_args->num_devices != 1) {
1892 ret = ioctl(fd, BTRFS_IOC_FS_INFO, fi_args);
1899 * The fs_args->num_devices does not include seed devices
1901 ret = search_chunk_tree_for_fs_info(fd, fi_args);
1906 * search_chunk_tree_for_fs_info() will lacks the devid 0
1907 * so manual probe for it here.
1909 ret = get_device_info(fd, 0, &tmp);
1911 fi_args->num_devices++;
1914 if (last_devid == 0)
1919 if (!fi_args->num_devices)
1922 di_args = *di_ret = malloc((fi_args->num_devices) * sizeof(*di_args));
1929 memcpy(di_args, &tmp, sizeof(tmp));
1930 for (; last_devid <= fi_args->max_id; last_devid++) {
1931 ret = get_device_info(fd, last_devid, &di_args[ndevs]);
1940 * only when the only dev we wanted to find is not there then
1941 * let any error be returned
1943 if (fi_args->num_devices != 1) {
1949 close_file_or_dir(fd, dirstream);
1953 #define isoctal(c) (((c) & ~7) == '0')
1955 static inline void translate(char *f, char *t)
1957 while (*f != '\0') {
1959 isoctal(f[1]) && isoctal(f[2]) && isoctal(f[3])) {
1960 *t++ = 64*(f[1] & 7) + 8*(f[2] & 7) + (f[3] & 7);
1970 * Checks if the swap device.
1971 * Returns 1 if swap device, < 0 on error or 0 if not swap device.
1973 static int is_swap_device(const char *file)
1984 if (stat(file, &st_buf) < 0)
1986 if (S_ISBLK(st_buf.st_mode))
1987 dev = st_buf.st_rdev;
1988 else if (S_ISREG(st_buf.st_mode)) {
1989 dev = st_buf.st_dev;
1990 ino = st_buf.st_ino;
1994 if ((f = fopen("/proc/swaps", "r")) == NULL)
1997 /* skip the first line */
1998 if (fgets(tmp, sizeof(tmp), f) == NULL)
2001 while (fgets(tmp, sizeof(tmp), f) != NULL) {
2002 if ((cp = strchr(tmp, ' ')) != NULL)
2004 if ((cp = strchr(tmp, '\t')) != NULL)
2006 translate(tmp, buf);
2007 if (stat(buf, &st_buf) != 0)
2009 if (S_ISBLK(st_buf.st_mode)) {
2010 if (dev == st_buf.st_rdev) {
2014 } else if (S_ISREG(st_buf.st_mode)) {
2015 if (dev == st_buf.st_dev && ino == st_buf.st_ino) {
2029 * Check for existing filesystem or partition table on device.
2031 * 1 for existing fs or partition
2032 * 0 for nothing found
2033 * -1 for internal error
2035 static int check_overwrite(const char *device)
2038 blkid_probe pr = NULL;
2042 if (!device || !*device)
2045 ret = -1; /* will reset on success of all setup calls */
2047 pr = blkid_new_probe_from_filename(device);
2051 size = blkid_probe_get_size(pr);
2055 /* nothing to overwrite on a 0-length device */
2061 ret = blkid_probe_enable_partitions(pr, 1);
2065 ret = blkid_do_fullprobe(pr);
2070 * Blkid returns 1 for nothing found and 0 when it finds a signature,
2071 * but we want the exact opposite, so reverse the return value here.
2073 * In addition print some useful diagnostics about what actually is
2081 if (!blkid_probe_lookup_value(pr, "TYPE", &type, NULL)) {
2083 "%s appears to contain an existing "
2084 "filesystem (%s).\n", device, type);
2085 } else if (!blkid_probe_lookup_value(pr, "PTTYPE", &type, NULL)) {
2087 "%s appears to contain a partition "
2088 "table (%s).\n", device, type);
2091 "%s appears to contain something weird "
2092 "according to blkid\n", device);
2098 blkid_free_probe(pr);
2101 "probe of %s failed, cannot detect "
2102 "existing filesystem.\n", device);
2106 static int group_profile_devs_min(u64 flag)
2108 switch (flag & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
2109 case 0: /* single */
2110 case BTRFS_BLOCK_GROUP_DUP:
2112 case BTRFS_BLOCK_GROUP_RAID0:
2113 case BTRFS_BLOCK_GROUP_RAID1:
2114 case BTRFS_BLOCK_GROUP_RAID5:
2116 case BTRFS_BLOCK_GROUP_RAID6:
2118 case BTRFS_BLOCK_GROUP_RAID10:
2125 int test_num_disk_vs_raid(u64 metadata_profile, u64 data_profile,
2126 u64 dev_cnt, int mixed, int ssd)
2129 u64 profile = metadata_profile | data_profile;
2134 allowed |= BTRFS_BLOCK_GROUP_RAID10;
2136 allowed |= BTRFS_BLOCK_GROUP_RAID6;
2138 allowed |= BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
2139 BTRFS_BLOCK_GROUP_RAID5;
2141 allowed |= BTRFS_BLOCK_GROUP_DUP;
2144 if (dev_cnt > 1 && profile & BTRFS_BLOCK_GROUP_DUP) {
2145 warning("DUP is not recommended on filesystem with multiple devices");
2147 if (metadata_profile & ~allowed) {
2149 "ERROR: unable to create FS with metadata profile %s "
2150 "(have %llu devices but %d devices are required)\n",
2151 btrfs_group_profile_str(metadata_profile), dev_cnt,
2152 group_profile_devs_min(metadata_profile));
2155 if (data_profile & ~allowed) {
2157 "ERROR: unable to create FS with data profile %s "
2158 "(have %llu devices but %d devices are required)\n",
2159 btrfs_group_profile_str(data_profile), dev_cnt,
2160 group_profile_devs_min(data_profile));
2164 if (dev_cnt == 3 && profile & BTRFS_BLOCK_GROUP_RAID6) {
2165 warning("RAID6 is not recommended on filesystem with 3 devices only");
2167 if (dev_cnt == 2 && profile & BTRFS_BLOCK_GROUP_RAID5) {
2168 warning("RAID5 is not recommended on filesystem with 2 devices only");
2170 warning_on(!mixed && (data_profile & BTRFS_BLOCK_GROUP_DUP) && ssd,
2171 "DUP may not actually lead to 2 copies on the device, see manual page");
2176 int group_profile_max_safe_loss(u64 flags)
2178 switch (flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
2179 case 0: /* single */
2180 case BTRFS_BLOCK_GROUP_DUP:
2181 case BTRFS_BLOCK_GROUP_RAID0:
2183 case BTRFS_BLOCK_GROUP_RAID1:
2184 case BTRFS_BLOCK_GROUP_RAID5:
2185 case BTRFS_BLOCK_GROUP_RAID10:
2187 case BTRFS_BLOCK_GROUP_RAID6:
2195 * Check if a device is suitable for btrfs
2197 * 1: something is wrong, an error is printed
2200 int test_dev_for_mkfs(const char *file, int force_overwrite)
2205 ret = is_swap_device(file);
2207 error("checking status of %s: %s", file, strerror(-ret));
2211 error("%s is a swap device", file);
2214 if (!force_overwrite) {
2215 if (check_overwrite(file)) {
2216 error("use the -f option to force overwrite of %s",
2221 ret = check_mounted(file);
2223 error("cannot check mount status of %s: %s", file,
2228 error("%s is mounted", file);
2231 /* check if the device is busy */
2232 fd = open(file, O_RDWR|O_EXCL);
2234 error("unable to open %s: %s", file, strerror(errno));
2237 if (fstat(fd, &st)) {
2238 error("unable to stat %s: %s", file, strerror(errno));
2242 if (!S_ISBLK(st.st_mode)) {
2243 error("%s is not a block device", file);
2251 int btrfs_scan_devices(void)
2256 struct btrfs_fs_devices *tmp_devices;
2257 blkid_dev_iterate iter = NULL;
2258 blkid_dev dev = NULL;
2259 blkid_cache cache = NULL;
2260 char path[PATH_MAX];
2262 if (btrfs_scan_done)
2265 if (blkid_get_cache(&cache, NULL) < 0) {
2266 error("blkid cache get failed");
2269 blkid_probe_all(cache);
2270 iter = blkid_dev_iterate_begin(cache);
2271 blkid_dev_set_search(iter, "TYPE", "btrfs");
2272 while (blkid_dev_next(iter, &dev) == 0) {
2273 dev = blkid_verify(cache, dev);
2276 /* if we are here its definitely a btrfs disk*/
2277 strncpy_null(path, blkid_dev_devname(dev));
2279 fd = open(path, O_RDONLY);
2281 error("cannot open %s: %s", path, strerror(errno));
2284 ret = btrfs_scan_one_device(fd, path, &tmp_devices,
2285 &num_devices, BTRFS_SUPER_INFO_OFFSET,
2288 error("cannot scan %s: %s", path, strerror(-ret));
2295 blkid_dev_iterate_end(iter);
2296 blkid_put_cache(cache);
2298 btrfs_scan_done = 1;
2303 int is_vol_small(const char *file)
2310 fd = open(file, O_RDONLY);
2313 if (fstat(fd, &st) < 0) {
2318 size = btrfs_device_size(fd, &st);
2323 if (size < BTRFS_MKFS_SMALL_VOLUME_SIZE) {
2333 * This reads a line from the stdin and only returns non-zero if the
2334 * first whitespace delimited token is a case insensitive match with yes
2337 int ask_user(const char *question)
2339 char buf[30] = {0,};
2340 char *saveptr = NULL;
2343 printf("%s [y/N]: ", question);
2345 return fgets(buf, sizeof(buf) - 1, stdin) &&
2346 (answer = strtok_r(buf, " \t\n\r", &saveptr)) &&
2347 (!strcasecmp(answer, "yes") || !strcasecmp(answer, "y"));
2351 * return 0 if a btrfs mount point is found
2352 * return 1 if a mount point is found but not btrfs
2353 * return <0 if something goes wrong
2355 int find_mount_root(const char *path, char **mount_root)
2363 int longest_matchlen = 0;
2364 char *longest_match = NULL;
2366 fd = open(path, O_RDONLY | O_NOATIME);
2371 mnttab = setmntent("/proc/self/mounts", "r");
2375 while ((ent = getmntent(mnttab))) {
2376 len = strlen(ent->mnt_dir);
2377 if (strncmp(ent->mnt_dir, path, len) == 0) {
2378 /* match found and use the latest match */
2379 if (longest_matchlen <= len) {
2380 free(longest_match);
2381 longest_matchlen = len;
2382 longest_match = strdup(ent->mnt_dir);
2383 not_btrfs = strcmp(ent->mnt_type, "btrfs");
2392 free(longest_match);
2397 *mount_root = realpath(longest_match, NULL);
2401 free(longest_match);
2405 int test_minimum_size(const char *file, u32 nodesize)
2408 struct stat statbuf;
2410 fd = open(file, O_RDONLY);
2413 if (stat(file, &statbuf) < 0) {
2417 if (btrfs_device_size(fd, &statbuf) < btrfs_min_dev_size(nodesize)) {
2427 * Test if path is a directory
2429 * 0 - path exists but it is not a directory
2430 * 1 - path exists and it is a directory
2433 int test_isdir(const char *path)
2438 ret = stat(path, &st);
2442 return !!S_ISDIR(st.st_mode);
2445 void units_set_mode(unsigned *units, unsigned mode)
2447 unsigned base = *units & UNITS_MODE_MASK;
2449 *units = base | mode;
2452 void units_set_base(unsigned *units, unsigned base)
2454 unsigned mode = *units & ~UNITS_MODE_MASK;
2456 *units = base | mode;
2459 int find_next_key(struct btrfs_path *path, struct btrfs_key *key)
2463 for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2464 if (!path->nodes[level])
2466 if (path->slots[level] + 1 >=
2467 btrfs_header_nritems(path->nodes[level]))
2470 btrfs_item_key_to_cpu(path->nodes[level], key,
2471 path->slots[level] + 1);
2473 btrfs_node_key_to_cpu(path->nodes[level], key,
2474 path->slots[level] + 1);
2480 const char* btrfs_group_type_str(u64 flag)
2482 u64 mask = BTRFS_BLOCK_GROUP_TYPE_MASK |
2483 BTRFS_SPACE_INFO_GLOBAL_RSV;
2485 switch (flag & mask) {
2486 case BTRFS_BLOCK_GROUP_DATA:
2488 case BTRFS_BLOCK_GROUP_SYSTEM:
2490 case BTRFS_BLOCK_GROUP_METADATA:
2492 case BTRFS_BLOCK_GROUP_DATA|BTRFS_BLOCK_GROUP_METADATA:
2493 return "Data+Metadata";
2494 case BTRFS_SPACE_INFO_GLOBAL_RSV:
2495 return "GlobalReserve";
2501 const char* btrfs_group_profile_str(u64 flag)
2503 switch (flag & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
2506 case BTRFS_BLOCK_GROUP_RAID0:
2508 case BTRFS_BLOCK_GROUP_RAID1:
2510 case BTRFS_BLOCK_GROUP_RAID5:
2512 case BTRFS_BLOCK_GROUP_RAID6:
2514 case BTRFS_BLOCK_GROUP_DUP:
2516 case BTRFS_BLOCK_GROUP_RAID10:
2523 u64 disk_size(const char *path)
2527 if (statfs(path, &sfs) < 0)
2530 return sfs.f_bsize * sfs.f_blocks;
2533 u64 get_partition_size(const char *dev)
2536 int fd = open(dev, O_RDONLY);
2540 if (ioctl(fd, BLKGETSIZE64, &result) < 0) {
2550 * Check if the BTRFS_IOC_TREE_SEARCH_V2 ioctl is supported on a given
2551 * filesystem, opened at fd
2553 int btrfs_tree_search2_ioctl_supported(int fd)
2555 struct btrfs_ioctl_search_args_v2 *args2;
2556 struct btrfs_ioctl_search_key *sk;
2557 int args2_size = 1024;
2558 char args2_buf[args2_size];
2561 args2 = (struct btrfs_ioctl_search_args_v2 *)args2_buf;
2565 * Search for the extent tree item in the root tree.
2567 sk->tree_id = BTRFS_ROOT_TREE_OBJECTID;
2568 sk->min_objectid = BTRFS_EXTENT_TREE_OBJECTID;
2569 sk->max_objectid = BTRFS_EXTENT_TREE_OBJECTID;
2570 sk->min_type = BTRFS_ROOT_ITEM_KEY;
2571 sk->max_type = BTRFS_ROOT_ITEM_KEY;
2573 sk->max_offset = (u64)-1;
2574 sk->min_transid = 0;
2575 sk->max_transid = (u64)-1;
2577 args2->buf_size = args2_size - sizeof(struct btrfs_ioctl_search_args_v2);
2578 ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH_V2, args2);
2579 if (ret == -EOPNOTSUPP)
2586 int btrfs_check_nodesize(u32 nodesize, u32 sectorsize, u64 features)
2588 if (nodesize < sectorsize) {
2589 error("illegal nodesize %u (smaller than %u)",
2590 nodesize, sectorsize);
2592 } else if (nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
2593 error("illegal nodesize %u (larger than %u)",
2594 nodesize, BTRFS_MAX_METADATA_BLOCKSIZE);
2596 } else if (nodesize & (sectorsize - 1)) {
2597 error("illegal nodesize %u (not aligned to %u)",
2598 nodesize, sectorsize);
2600 } else if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS &&
2601 nodesize != sectorsize) {
2602 error("illegal nodesize %u (not equal to %u for mixed block group)",
2603 nodesize, sectorsize);
2610 * Copy a path argument from SRC to DEST and check the SRC length if it's at
2611 * most PATH_MAX and fits into DEST. DESTLEN is supposed to be exact size of
2613 * The destination buffer is zero terminated.
2614 * Return < 0 for error, 0 otherwise.
2616 int arg_copy_path(char *dest, const char *src, int destlen)
2618 size_t len = strlen(src);
2620 if (len >= PATH_MAX || len >= destlen)
2621 return -ENAMETOOLONG;
2623 __strncpy_null(dest, src, destlen);
2628 unsigned int get_unit_mode_from_arg(int *argc, char *argv[], int df_mode)
2630 unsigned int unit_mode = UNITS_DEFAULT;
2634 for (arg_i = 0; arg_i < *argc; arg_i++) {
2635 if (!strcmp(argv[arg_i], "--"))
2638 if (!strcmp(argv[arg_i], "--raw")) {
2639 unit_mode = UNITS_RAW;
2643 if (!strcmp(argv[arg_i], "--human-readable")) {
2644 unit_mode = UNITS_HUMAN_BINARY;
2649 if (!strcmp(argv[arg_i], "--iec")) {
2650 units_set_mode(&unit_mode, UNITS_BINARY);
2654 if (!strcmp(argv[arg_i], "--si")) {
2655 units_set_mode(&unit_mode, UNITS_DECIMAL);
2660 if (!strcmp(argv[arg_i], "--kbytes")) {
2661 units_set_base(&unit_mode, UNITS_KBYTES);
2665 if (!strcmp(argv[arg_i], "--mbytes")) {
2666 units_set_base(&unit_mode, UNITS_MBYTES);
2670 if (!strcmp(argv[arg_i], "--gbytes")) {
2671 units_set_base(&unit_mode, UNITS_GBYTES);
2675 if (!strcmp(argv[arg_i], "--tbytes")) {
2676 units_set_base(&unit_mode, UNITS_TBYTES);
2684 if (!strcmp(argv[arg_i], "-b")) {
2685 unit_mode = UNITS_RAW;
2689 if (!strcmp(argv[arg_i], "-h")) {
2690 unit_mode = UNITS_HUMAN_BINARY;
2694 if (!strcmp(argv[arg_i], "-H")) {
2695 unit_mode = UNITS_HUMAN_DECIMAL;
2699 if (!strcmp(argv[arg_i], "-k")) {
2700 units_set_base(&unit_mode, UNITS_KBYTES);
2704 if (!strcmp(argv[arg_i], "-m")) {
2705 units_set_base(&unit_mode, UNITS_MBYTES);
2709 if (!strcmp(argv[arg_i], "-g")) {
2710 units_set_base(&unit_mode, UNITS_GBYTES);
2714 if (!strcmp(argv[arg_i], "-t")) {
2715 units_set_base(&unit_mode, UNITS_TBYTES);
2721 for (arg_i = 0, arg_end = 0; arg_i < *argc; arg_i++) {
2724 argv[arg_end] = argv[arg_i];
2733 int string_is_numerical(const char *str)
2737 if (!(*str >= '0' && *str <= '9'))
2739 while (*str >= '0' && *str <= '9')
2746 /* Subvolume helper functions */
2748 * test if name is a correct subvolume name
2749 * this function return
2750 * 0-> name is not a correct subvolume name
2751 * 1-> name is a correct subvolume name
2753 int test_issubvolname(const char *name)
2755 return name[0] != '\0' && !strchr(name, '/') &&
2756 strcmp(name, ".") && strcmp(name, "..");
2760 * Test if path is a subvolume
2762 * 0 - path exists but it is not a subvolume
2763 * 1 - path exists and it is a subvolume
2766 int test_issubvolume(const char *path)
2772 res = stat(path, &st);
2776 if (st.st_ino != BTRFS_FIRST_FREE_OBJECTID || !S_ISDIR(st.st_mode))
2779 res = statfs(path, &stfs);
2783 return (int)stfs.f_type == BTRFS_SUPER_MAGIC;
2786 const char *subvol_strip_mountpoint(const char *mnt, const char *full_path)
2788 int len = strlen(mnt);
2792 if (mnt[len - 1] != '/')
2795 return full_path + len;
2802 * 1: Error; and error info printed to the terminal. Fixme.
2803 * 2: If the fullpath is root tree instead of subvol tree
2805 int get_subvol_info(const char *fullpath, struct root_info *get_ri)
2812 const char *svpath = NULL;
2813 DIR *dirstream1 = NULL;
2814 DIR *dirstream2 = NULL;
2816 ret = test_issubvolume(fullpath);
2820 error("not a subvolume: %s", fullpath);
2824 ret = find_mount_root(fullpath, &mnt);
2828 error("%s doesn't belong to btrfs mount point", fullpath);
2832 svpath = subvol_strip_mountpoint(mnt, fullpath);
2834 fd = btrfs_open_dir(fullpath, &dirstream1, 1);
2838 ret = btrfs_list_get_path_rootid(fd, &sv_id);
2842 mntfd = btrfs_open_dir(mnt, &dirstream2, 1);
2846 memset(get_ri, 0, sizeof(*get_ri));
2847 get_ri->root_id = sv_id;
2849 if (sv_id == BTRFS_FS_TREE_OBJECTID)
2850 ret = btrfs_get_toplevel_subvol(mntfd, get_ri);
2852 ret = btrfs_get_subvol(mntfd, get_ri);
2854 error("can't find '%s': %d", svpath, ret);
2857 close_file_or_dir(mntfd, dirstream2);
2858 close_file_or_dir(fd, dirstream1);
2864 void init_rand_seed(u64 seed)
2868 /* only use the last 48 bits */
2869 for (i = 0; i < 3; i++) {
2870 rand_seed[i] = (unsigned short)(seed ^ (unsigned short)(-1));
2873 rand_seed_initlized = 1;
2876 static void __init_seed(void)
2882 if(rand_seed_initlized)
2884 /* Use urandom as primary seed source. */
2885 fd = open("/dev/urandom", O_RDONLY);
2887 ret = read(fd, rand_seed, sizeof(rand_seed));
2889 if (ret < sizeof(rand_seed))
2893 /* Use time and pid as fallback seed */
2894 warning("failed to read /dev/urandom, use time and pid as random seed");
2895 gettimeofday(&tv, 0);
2896 rand_seed[0] = getpid() ^ (tv.tv_sec & 0xFFFF);
2897 rand_seed[1] = getppid() ^ (tv.tv_usec & 0xFFFF);
2898 rand_seed[2] = (tv.tv_sec ^ tv.tv_usec) >> 16;
2900 rand_seed_initlized = 1;
2907 * Don't use nrand48, its range is [0,2^31) The highest bit will alwasy
2908 * be 0. Use jrand48 to include the highest bit.
2910 return (u32)jrand48(rand_seed);
2913 unsigned int rand_range(unsigned int upper)
2917 * Use the full 48bits to mod, which would be more uniformly
2920 return (unsigned int)(jrand48(rand_seed) % upper);
2923 void btrfs_config_init(void)