2 * Copyright (C) 2007 Oracle. All rights reserved.
3 * Copyright (C) 2008 Morey Roof. All rights reserved.
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public
7 * License v2 as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public
15 * License along with this program; if not, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 021110-1307, USA.
23 #include <sys/ioctl.h>
24 #include <sys/mount.h>
25 #include <sys/types.h>
27 #include <uuid/uuid.h>
32 #include <linux/loop.h>
33 #include <linux/major.h>
34 #include <linux/kdev_t.h>
36 #include <blkid/blkid.h>
38 #include <sys/statfs.h>
39 #include <linux/magic.h>
42 #include "kerncompat.h"
43 #include "radix-tree.h"
46 #include "transaction.h"
52 #include "mkfs/common.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
);
126 u64
btrfs_device_size(int fd
, struct stat
*st
)
129 if (S_ISREG(st
->st_mode
)) {
132 if (!S_ISBLK(st
->st_mode
)) {
135 if (ioctl(fd
, BLKGETSIZE64
, &size
) >= 0) {
141 static int zero_blocks(int fd
, off_t start
, size_t len
)
143 char *buf
= malloc(len
);
150 written
= pwrite(fd
, buf
, len
, start
);
157 #define ZERO_DEV_BYTES SZ_2M
159 /* don't write outside the device by clamping the region to the device size */
160 static int zero_dev_clamped(int fd
, off_t start
, ssize_t len
, u64 dev_size
)
162 off_t end
= max(start
, start
+ len
);
165 /* and don't overwrite the disk labels on sparc */
166 start
= max(start
, 1024);
167 end
= max(end
, 1024);
170 start
= min_t(u64
, start
, dev_size
);
171 end
= min_t(u64
, end
, dev_size
);
173 return zero_blocks(fd
, start
, end
- start
);
176 int btrfs_add_to_fsid(struct btrfs_trans_handle
*trans
,
177 struct btrfs_root
*root
, int fd
, const char *path
,
178 u64 device_total_bytes
, u32 io_width
, u32 io_align
,
181 struct btrfs_super_block
*disk_super
;
182 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
183 struct btrfs_super_block
*super
= fs_info
->super_copy
;
184 struct btrfs_device
*device
;
185 struct btrfs_dev_item
*dev_item
;
191 device_total_bytes
= (device_total_bytes
/ sectorsize
) * sectorsize
;
193 device
= calloc(1, sizeof(*device
));
198 buf
= calloc(1, sectorsize
);
204 disk_super
= (struct btrfs_super_block
*)buf
;
205 dev_item
= &disk_super
->dev_item
;
207 uuid_generate(device
->uuid
);
210 device
->io_width
= io_width
;
211 device
->io_align
= io_align
;
212 device
->sector_size
= sectorsize
;
214 device
->writeable
= 1;
215 device
->total_bytes
= device_total_bytes
;
216 device
->bytes_used
= 0;
217 device
->total_ios
= 0;
218 device
->dev_root
= fs_info
->dev_root
;
219 device
->name
= strdup(path
);
225 INIT_LIST_HEAD(&device
->dev_list
);
226 ret
= btrfs_add_device(trans
, fs_info
, device
);
230 fs_total_bytes
= btrfs_super_total_bytes(super
) + device_total_bytes
;
231 btrfs_set_super_total_bytes(super
, fs_total_bytes
);
233 num_devs
= btrfs_super_num_devices(super
) + 1;
234 btrfs_set_super_num_devices(super
, num_devs
);
236 memcpy(disk_super
, super
, sizeof(*disk_super
));
238 btrfs_set_super_bytenr(disk_super
, BTRFS_SUPER_INFO_OFFSET
);
239 btrfs_set_stack_device_id(dev_item
, device
->devid
);
240 btrfs_set_stack_device_type(dev_item
, device
->type
);
241 btrfs_set_stack_device_io_align(dev_item
, device
->io_align
);
242 btrfs_set_stack_device_io_width(dev_item
, device
->io_width
);
243 btrfs_set_stack_device_sector_size(dev_item
, device
->sector_size
);
244 btrfs_set_stack_device_total_bytes(dev_item
, device
->total_bytes
);
245 btrfs_set_stack_device_bytes_used(dev_item
, device
->bytes_used
);
246 memcpy(&dev_item
->uuid
, device
->uuid
, BTRFS_UUID_SIZE
);
248 ret
= pwrite(fd
, buf
, sectorsize
, BTRFS_SUPER_INFO_OFFSET
);
249 BUG_ON(ret
!= sectorsize
);
252 list_add(&device
->dev_list
, &fs_info
->fs_devices
->devices
);
253 device
->fs_devices
= fs_info
->fs_devices
;
262 static int btrfs_wipe_existing_sb(int fd
)
264 const char *off
= NULL
;
269 blkid_probe pr
= NULL
;
271 pr
= blkid_new_probe();
275 if (blkid_probe_set_device(pr
, fd
, 0, 0)) {
280 ret
= blkid_probe_lookup_value(pr
, "SBMAGIC_OFFSET", &off
, NULL
);
282 ret
= blkid_probe_lookup_value(pr
, "SBMAGIC", NULL
, &len
);
284 if (ret
|| len
== 0 || off
== NULL
) {
286 * If lookup fails, the probe did not find any values, eg. for
287 * a file image or a loop device. Soft error.
293 offset
= strtoll(off
, NULL
, 10);
294 if (len
> sizeof(buf
))
298 ret
= pwrite(fd
, buf
, len
, offset
);
300 error("cannot wipe existing superblock: %s", strerror(errno
));
302 } else if (ret
!= len
) {
303 error("cannot wipe existing superblock: wrote %d of %zd", ret
, len
);
309 blkid_free_probe(pr
);
313 int btrfs_prepare_device(int fd
, const char *file
, u64
*block_count_ret
,
314 u64 max_block_count
, unsigned opflags
)
320 ret
= fstat(fd
, &st
);
322 error("unable to stat %s: %s", file
, strerror(errno
));
326 block_count
= btrfs_device_size(fd
, &st
);
327 if (block_count
== 0) {
328 error("unable to determine size of %s", file
);
332 block_count
= min(block_count
, max_block_count
);
334 if (opflags
& PREP_DEVICE_DISCARD
) {
336 * We intentionally ignore errors from the discard ioctl. It
337 * is not necessary for the mkfs functionality but just an
340 if (discard_range(fd
, 0, 0) == 0) {
341 if (opflags
& PREP_DEVICE_VERBOSE
)
342 printf("Performing full device TRIM %s (%s) ...\n",
343 file
, pretty_size(block_count
));
344 discard_blocks(fd
, 0, block_count
);
348 ret
= zero_dev_clamped(fd
, 0, ZERO_DEV_BYTES
, block_count
);
349 for (i
= 0 ; !ret
&& i
< BTRFS_SUPER_MIRROR_MAX
; i
++)
350 ret
= zero_dev_clamped(fd
, btrfs_sb_offset(i
),
351 BTRFS_SUPER_INFO_SIZE
, block_count
);
352 if (!ret
&& (opflags
& PREP_DEVICE_ZERO_END
))
353 ret
= zero_dev_clamped(fd
, block_count
- ZERO_DEV_BYTES
,
354 ZERO_DEV_BYTES
, block_count
);
357 error("failed to zero device '%s': %s", file
, strerror(-ret
));
361 ret
= btrfs_wipe_existing_sb(fd
);
363 error("cannot wipe superblocks on %s", file
);
367 *block_count_ret
= block_count
;
371 int btrfs_make_root_dir(struct btrfs_trans_handle
*trans
,
372 struct btrfs_root
*root
, u64 objectid
)
375 struct btrfs_inode_item inode_item
;
376 time_t now
= time(NULL
);
378 memset(&inode_item
, 0, sizeof(inode_item
));
379 btrfs_set_stack_inode_generation(&inode_item
, trans
->transid
);
380 btrfs_set_stack_inode_size(&inode_item
, 0);
381 btrfs_set_stack_inode_nlink(&inode_item
, 1);
382 btrfs_set_stack_inode_nbytes(&inode_item
, root
->fs_info
->nodesize
);
383 btrfs_set_stack_inode_mode(&inode_item
, S_IFDIR
| 0755);
384 btrfs_set_stack_timespec_sec(&inode_item
.atime
, now
);
385 btrfs_set_stack_timespec_nsec(&inode_item
.atime
, 0);
386 btrfs_set_stack_timespec_sec(&inode_item
.ctime
, now
);
387 btrfs_set_stack_timespec_nsec(&inode_item
.ctime
, 0);
388 btrfs_set_stack_timespec_sec(&inode_item
.mtime
, now
);
389 btrfs_set_stack_timespec_nsec(&inode_item
.mtime
, 0);
390 btrfs_set_stack_timespec_sec(&inode_item
.otime
, now
);
391 btrfs_set_stack_timespec_nsec(&inode_item
.otime
, 0);
393 if (root
->fs_info
->tree_root
== root
)
394 btrfs_set_super_root_dir(root
->fs_info
->super_copy
, objectid
);
396 ret
= btrfs_insert_inode(trans
, root
, objectid
, &inode_item
);
400 ret
= btrfs_insert_inode_ref(trans
, root
, "..", 2, objectid
, objectid
, 0);
404 btrfs_set_root_dirid(&root
->root_item
, objectid
);
411 * checks if a path is a block device node
412 * Returns negative errno on failure, otherwise
413 * returns 1 for blockdev, 0 for not-blockdev
415 int is_block_device(const char *path
)
419 if (stat(path
, &statbuf
) < 0)
422 return !!S_ISBLK(statbuf
.st_mode
);
426 * check if given path is a mount point
427 * return 1 if yes. 0 if no. -1 for error
429 int is_mount_point(const char *path
)
435 f
= setmntent("/proc/self/mounts", "r");
439 while ((mnt
= getmntent(f
)) != NULL
) {
440 if (strcmp(mnt
->mnt_dir
, path
))
449 static int is_reg_file(const char *path
)
453 if (stat(path
, &statbuf
) < 0)
455 return S_ISREG(statbuf
.st_mode
);
459 * This function checks if the given input parameter is
461 * return <0 : some error in the given input
462 * return BTRFS_ARG_UNKNOWN: unknown input
463 * return BTRFS_ARG_UUID: given input is uuid
464 * return BTRFS_ARG_MNTPOINT: given input is path
465 * return BTRFS_ARG_REG: given input is regular file
466 * return BTRFS_ARG_BLKDEV: given input is block device
468 int check_arg_type(const char *input
)
476 if (realpath(input
, path
)) {
477 if (is_block_device(path
) == 1)
478 return BTRFS_ARG_BLKDEV
;
480 if (is_mount_point(path
) == 1)
481 return BTRFS_ARG_MNTPOINT
;
483 if (is_reg_file(path
))
484 return BTRFS_ARG_REG
;
486 return BTRFS_ARG_UNKNOWN
;
489 if (strlen(input
) == (BTRFS_UUID_UNPARSED_SIZE
- 1) &&
490 !uuid_parse(input
, uuid
))
491 return BTRFS_ARG_UUID
;
493 return BTRFS_ARG_UNKNOWN
;
497 * Find the mount point for a mounted device.
498 * On success, returns 0 with mountpoint in *mp.
499 * On failure, returns -errno (not mounted yields -EINVAL)
500 * Is noisy on failures, expects to be given a mounted device.
502 int get_btrfs_mount(const char *dev
, char *mp
, size_t mp_size
)
507 ret
= is_block_device(dev
);
510 error("not a block device: %s", dev
);
513 error("cannot check %s: %s", dev
, strerror(-ret
));
518 fd
= open(dev
, O_RDONLY
);
521 error("cannot open %s: %s", dev
, strerror(errno
));
525 ret
= check_mounted_where(fd
, dev
, mp
, mp_size
, NULL
);
528 } else { /* mounted, all good */
538 * Given a pathname, return a filehandle to:
539 * the original pathname or,
540 * if the pathname is a mounted btrfs device, to its mountpoint.
542 * On error, return -1, errno should be set.
544 int open_path_or_dev_mnt(const char *path
, DIR **dirstream
, int verbose
)
549 if (is_block_device(path
)) {
550 ret
= get_btrfs_mount(path
, mp
, sizeof(mp
));
552 /* not a mounted btrfs dev */
553 error_on(verbose
, "'%s' is not a mounted btrfs device",
558 ret
= open_file_or_dir(mp
, dirstream
);
559 error_on(verbose
&& ret
< 0, "can't access '%s': %s",
560 path
, strerror(errno
));
562 ret
= btrfs_open_dir(path
, dirstream
, 1);
569 * Do the following checks before calling open_file_or_dir():
570 * 1: path is in a btrfs filesystem
571 * 2: path is a directory
573 int btrfs_open_dir(const char *path
, DIR **dirstream
, int verbose
)
579 if (statfs(path
, &stfs
) != 0) {
580 error_on(verbose
, "cannot access '%s': %s", path
,
585 if (stfs
.f_type
!= BTRFS_SUPER_MAGIC
) {
586 error_on(verbose
, "not a btrfs filesystem: %s", path
);
590 if (stat(path
, &st
) != 0) {
591 error_on(verbose
, "cannot access '%s': %s", path
,
596 if (!S_ISDIR(st
.st_mode
)) {
597 error_on(verbose
, "not a directory: %s", path
);
601 ret
= open_file_or_dir(path
, dirstream
);
603 error_on(verbose
, "cannot access '%s': %s", path
,
610 /* checks if a device is a loop device */
611 static int is_loop_device (const char* device
) {
614 if(stat(device
, &statbuf
) < 0)
617 return (S_ISBLK(statbuf
.st_mode
) &&
618 MAJOR(statbuf
.st_rdev
) == LOOP_MAJOR
);
622 * Takes a loop device path (e.g. /dev/loop0) and returns
623 * the associated file (e.g. /images/my_btrfs.img) using
626 static int resolve_loop_device_with_loopdev(const char* loop_dev
, char* loop_file
)
630 struct loop_info64 lo64
;
632 fd
= open(loop_dev
, O_RDONLY
| O_NONBLOCK
);
635 ret
= ioctl(fd
, LOOP_GET_STATUS64
, &lo64
);
641 memcpy(loop_file
, lo64
.lo_file_name
, sizeof(lo64
.lo_file_name
));
642 loop_file
[sizeof(lo64
.lo_file_name
)] = 0;
650 /* Takes a loop device path (e.g. /dev/loop0) and returns
651 * the associated file (e.g. /images/my_btrfs.img) */
652 static int resolve_loop_device(const char* loop_dev
, char* loop_file
,
659 char real_loop_dev
[PATH_MAX
];
661 if (!realpath(loop_dev
, real_loop_dev
))
663 snprintf(p
, PATH_MAX
, "/sys/block/%s/loop/backing_file", strrchr(real_loop_dev
, '/'));
664 if (!(f
= fopen(p
, "r"))) {
667 * It's possibly a partitioned loop device, which is
668 * resolvable with loopdev API.
670 return resolve_loop_device_with_loopdev(loop_dev
, loop_file
);
674 snprintf(fmt
, 20, "%%%i[^\n]", max_len
-1);
675 ret
= fscanf(f
, fmt
, loop_file
);
684 * Checks whether a and b are identical or device
685 * files associated with the same block device
687 static int is_same_blk_file(const char* a
, const char* b
)
689 struct stat st_buf_a
, st_buf_b
;
690 char real_a
[PATH_MAX
];
691 char real_b
[PATH_MAX
];
693 if (!realpath(a
, real_a
))
694 strncpy_null(real_a
, a
);
696 if (!realpath(b
, real_b
))
697 strncpy_null(real_b
, b
);
699 /* Identical path? */
700 if (strcmp(real_a
, real_b
) == 0)
703 if (stat(a
, &st_buf_a
) < 0 || stat(b
, &st_buf_b
) < 0) {
709 /* Same blockdevice? */
710 if (S_ISBLK(st_buf_a
.st_mode
) && S_ISBLK(st_buf_b
.st_mode
) &&
711 st_buf_a
.st_rdev
== st_buf_b
.st_rdev
) {
716 if (st_buf_a
.st_dev
== st_buf_b
.st_dev
&&
717 st_buf_a
.st_ino
== st_buf_b
.st_ino
) {
724 /* checks if a and b are identical or device
725 * files associated with the same block device or
726 * if one file is a loop device that uses the other
729 static int is_same_loop_file(const char* a
, const char* b
)
731 char res_a
[PATH_MAX
];
732 char res_b
[PATH_MAX
];
733 const char* final_a
= NULL
;
734 const char* final_b
= NULL
;
737 /* Resolve a if it is a loop device */
738 if((ret
= is_loop_device(a
)) < 0) {
743 ret
= resolve_loop_device(a
, res_a
, sizeof(res_a
));
754 /* Resolve b if it is a loop device */
755 if ((ret
= is_loop_device(b
)) < 0) {
760 ret
= resolve_loop_device(b
, res_b
, sizeof(res_b
));
771 return is_same_blk_file(final_a
, final_b
);
774 /* Checks if a file exists and is a block or regular file*/
775 static int is_existing_blk_or_reg_file(const char* filename
)
779 if(stat(filename
, &st_buf
) < 0) {
786 return (S_ISBLK(st_buf
.st_mode
) || S_ISREG(st_buf
.st_mode
));
789 /* Checks if a file is used (directly or indirectly via a loop device)
790 * by a device in fs_devices
792 static int blk_file_in_dev_list(struct btrfs_fs_devices
* fs_devices
,
796 struct list_head
*head
;
797 struct list_head
*cur
;
798 struct btrfs_device
*device
;
800 head
= &fs_devices
->devices
;
801 list_for_each(cur
, head
) {
802 device
= list_entry(cur
, struct btrfs_device
, dev_list
);
804 if((ret
= is_same_loop_file(device
->name
, file
)))
812 * Resolve a pathname to a device mapper node to /dev/mapper/<name>
813 * Returns NULL on invalid input or malloc failure; Other failures
814 * will be handled by the caller using the input pathame.
816 char *canonicalize_dm_name(const char *ptname
)
820 char path
[PATH_MAX
], name
[PATH_MAX
], *res
= NULL
;
822 if (!ptname
|| !*ptname
)
825 snprintf(path
, sizeof(path
), "/sys/block/%s/dm/name", ptname
);
826 if (!(f
= fopen(path
, "r")))
829 /* read <name>\n from sysfs */
830 if (fgets(name
, sizeof(name
), f
) && (sz
= strlen(name
)) > 1) {
832 snprintf(path
, sizeof(path
), "/dev/mapper/%s", name
);
834 if (access(path
, F_OK
) == 0)
842 * Resolve a pathname to a canonical device node, e.g. /dev/sda1 or
843 * to a device mapper pathname.
844 * Returns NULL on invalid input or malloc failure; Other failures
845 * will be handled by the caller using the input pathame.
847 char *canonicalize_path(const char *path
)
854 canonical
= realpath(path
, NULL
);
857 p
= strrchr(canonical
, '/');
858 if (p
&& strncmp(p
, "/dm-", 4) == 0 && isdigit(*(p
+ 4))) {
859 char *dm
= canonicalize_dm_name(p
+ 1);
870 * returns 1 if the device was mounted, < 0 on error or 0 if everything
871 * is safe to continue.
873 int check_mounted(const char* file
)
878 fd
= open(file
, O_RDONLY
);
880 error("mount check: cannot open %s: %s", file
,
885 ret
= check_mounted_where(fd
, file
, NULL
, 0, NULL
);
891 int check_mounted_where(int fd
, const char *file
, char *where
, int size
,
892 struct btrfs_fs_devices
**fs_dev_ret
)
897 struct btrfs_fs_devices
*fs_devices_mnt
= NULL
;
901 /* scan the initial device */
902 ret
= btrfs_scan_one_device(fd
, file
, &fs_devices_mnt
,
903 &total_devs
, BTRFS_SUPER_INFO_OFFSET
, SBREAD_DEFAULT
);
904 is_btrfs
= (ret
>= 0);
906 /* scan other devices */
907 if (is_btrfs
&& total_devs
> 1) {
908 ret
= btrfs_scan_devices();
913 /* iterate over the list of currently mounted filesystems */
914 if ((f
= setmntent ("/proc/self/mounts", "r")) == NULL
)
917 while ((mnt
= getmntent (f
)) != NULL
) {
919 if(strcmp(mnt
->mnt_type
, "btrfs") != 0)
922 ret
= blk_file_in_dev_list(fs_devices_mnt
, mnt
->mnt_fsname
);
924 /* ignore entries in the mount table that are not
925 associated with a file*/
926 if((ret
= is_existing_blk_or_reg_file(mnt
->mnt_fsname
)) < 0)
927 goto out_mntloop_err
;
931 ret
= is_same_loop_file(file
, mnt
->mnt_fsname
);
935 goto out_mntloop_err
;
940 /* Did we find an entry in mnt table? */
941 if (mnt
&& size
&& where
) {
942 strncpy(where
, mnt
->mnt_dir
, size
);
946 *fs_dev_ret
= fs_devices_mnt
;
957 struct list_head list
;
961 int btrfs_register_one_device(const char *fname
)
963 struct btrfs_ioctl_vol_args args
;
967 fd
= open("/dev/btrfs-control", O_RDWR
);
970 "failed to open /dev/btrfs-control, skipping device registration: %s",
974 memset(&args
, 0, sizeof(args
));
975 strncpy_null(args
.name
, fname
);
976 ret
= ioctl(fd
, BTRFS_IOC_SCAN_DEV
, &args
);
978 error("device scan failed on '%s': %s", fname
,
987 * Register all devices in the fs_uuid list created in the user
988 * space. Ensure btrfs_scan_devices() is called before this func.
990 int btrfs_register_all_devices(void)
994 struct btrfs_fs_devices
*fs_devices
;
995 struct btrfs_device
*device
;
996 struct list_head
*all_uuids
;
998 all_uuids
= btrfs_scanned_uuids();
1000 list_for_each_entry(fs_devices
, all_uuids
, list
) {
1001 list_for_each_entry(device
, &fs_devices
->devices
, dev_list
) {
1003 err
= btrfs_register_one_device(device
->name
);
1013 int btrfs_device_already_in_root(struct btrfs_root
*root
, int fd
,
1016 struct btrfs_super_block
*disk_super
;
1020 buf
= malloc(BTRFS_SUPER_INFO_SIZE
);
1025 ret
= pread(fd
, buf
, BTRFS_SUPER_INFO_SIZE
, super_offset
);
1026 if (ret
!= BTRFS_SUPER_INFO_SIZE
)
1030 disk_super
= (struct btrfs_super_block
*)buf
;
1032 * Accept devices from the same filesystem, allow partially created
1035 if (btrfs_super_magic(disk_super
) != BTRFS_MAGIC
&&
1036 btrfs_super_magic(disk_super
) != BTRFS_MAGIC_PARTIAL
)
1039 if (!memcmp(disk_super
->fsid
, root
->fs_info
->super_copy
->fsid
,
1049 * Note: this function uses a static per-thread buffer. Do not call this
1050 * function more than 10 times within one argument list!
1052 const char *pretty_size_mode(u64 size
, unsigned mode
)
1054 static __thread
int ps_index
= 0;
1055 static __thread
char ps_array
[10][32];
1058 ret
= ps_array
[ps_index
];
1061 (void)pretty_size_snprintf(size
, ret
, 32, mode
);
1066 static const char* unit_suffix_binary
[] =
1067 { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"};
1068 static const char* unit_suffix_decimal
[] =
1069 { "B", "kB", "MB", "GB", "TB", "PB", "EB"};
1071 int pretty_size_snprintf(u64 size
, char *str
, size_t str_size
, unsigned unit_mode
)
1077 const char** suffix
= NULL
;
1084 negative
= !!(unit_mode
& UNITS_NEGATIVE
);
1085 unit_mode
&= ~UNITS_NEGATIVE
;
1087 if ((unit_mode
& ~UNITS_MODE_MASK
) == UNITS_RAW
) {
1089 snprintf(str
, str_size
, "%lld", size
);
1091 snprintf(str
, str_size
, "%llu", size
);
1095 if ((unit_mode
& ~UNITS_MODE_MASK
) == UNITS_BINARY
) {
1098 suffix
= unit_suffix_binary
;
1099 } else if ((unit_mode
& ~UNITS_MODE_MASK
) == UNITS_DECIMAL
) {
1102 suffix
= unit_suffix_decimal
;
1107 fprintf(stderr
, "INTERNAL ERROR: unknown unit base, mode %d\n",
1115 switch (unit_mode
& UNITS_MODE_MASK
) {
1116 case UNITS_TBYTES
: base
*= mult
; num_divs
++;
1117 case UNITS_GBYTES
: base
*= mult
; num_divs
++;
1118 case UNITS_MBYTES
: base
*= mult
; num_divs
++;
1119 case UNITS_KBYTES
: num_divs
++;
1127 s64 ssize
= (s64
)size
;
1128 s64 last_ssize
= ssize
;
1130 while ((ssize
< 0 ? -ssize
: ssize
) >= mult
) {
1135 last_size
= (u64
)last_ssize
;
1137 while (size
>= mult
) {
1144 * If the value is smaller than base, we didn't do any
1145 * division, in that case, base should be 1, not original
1146 * base, or the unit will be wrong
1152 if (num_divs
>= ARRAY_SIZE(unit_suffix_binary
)) {
1154 printf("INTERNAL ERROR: unsupported unit suffix, index %d\n",
1161 fraction
= (float)(s64
)last_size
/ base
;
1163 fraction
= (float)last_size
/ base
;
1166 return snprintf(str
, str_size
, "%.2f%s", fraction
, suffix
[num_divs
]);
1170 * __strncpy_null - strncpy with null termination
1171 * @dest: the target array
1172 * @src: the source string
1173 * @n: maximum bytes to copy (size of *dest)
1175 * Like strncpy, but ensures destination is null-terminated.
1177 * Copies the string pointed to by src, including the terminating null
1178 * byte ('\0'), to the buffer pointed to by dest, up to a maximum
1179 * of n bytes. Then ensure that dest is null-terminated.
1181 char *__strncpy_null(char *dest
, const char *src
, size_t n
)
1183 strncpy(dest
, src
, n
);
1190 * Checks to make sure that the label matches our requirements.
1192 0 if everything is safe and usable
1193 -1 if the label is too long
1195 static int check_label(const char *input
)
1197 int len
= strlen(input
);
1199 if (len
> BTRFS_LABEL_SIZE
- 1) {
1200 error("label %s is too long (max %d)", input
,
1201 BTRFS_LABEL_SIZE
- 1);
1208 static int set_label_unmounted(const char *dev
, const char *label
)
1210 struct btrfs_trans_handle
*trans
;
1211 struct btrfs_root
*root
;
1214 ret
= check_mounted(dev
);
1216 error("checking mount status of %s failed: %d", dev
, ret
);
1220 error("device %s is mounted, use mount point", dev
);
1224 /* Open the super_block at the default location
1225 * and as read-write.
1227 root
= open_ctree(dev
, 0, OPEN_CTREE_WRITES
);
1228 if (!root
) /* errors are printed by open_ctree() */
1231 trans
= btrfs_start_transaction(root
, 1);
1232 __strncpy_null(root
->fs_info
->super_copy
->label
, label
, BTRFS_LABEL_SIZE
- 1);
1234 btrfs_commit_transaction(trans
, root
);
1236 /* Now we close it since we are done. */
1241 static int set_label_mounted(const char *mount_path
, const char *labelp
)
1244 char label
[BTRFS_LABEL_SIZE
];
1246 fd
= open(mount_path
, O_RDONLY
| O_NOATIME
);
1248 error("unable to access %s: %s", mount_path
, strerror(errno
));
1252 memset(label
, 0, sizeof(label
));
1253 __strncpy_null(label
, labelp
, BTRFS_LABEL_SIZE
- 1);
1254 if (ioctl(fd
, BTRFS_IOC_SET_FSLABEL
, label
) < 0) {
1255 error("unable to set label of %s: %s", mount_path
,
1265 int get_label_unmounted(const char *dev
, char *label
)
1267 struct btrfs_root
*root
;
1270 ret
= check_mounted(dev
);
1272 error("checking mount status of %s failed: %d", dev
, ret
);
1276 /* Open the super_block at the default location
1279 root
= open_ctree(dev
, 0, 0);
1283 __strncpy_null(label
, root
->fs_info
->super_copy
->label
,
1284 BTRFS_LABEL_SIZE
- 1);
1286 /* Now we close it since we are done. */
1292 * If a partition is mounted, try to get the filesystem label via its
1293 * mounted path rather than device. Return the corresponding error
1294 * the user specified the device path.
1296 int get_label_mounted(const char *mount_path
, char *labelp
)
1298 char label
[BTRFS_LABEL_SIZE
];
1302 fd
= open(mount_path
, O_RDONLY
| O_NOATIME
);
1304 error("unable to access %s: %s", mount_path
, strerror(errno
));
1308 memset(label
, '\0', sizeof(label
));
1309 ret
= ioctl(fd
, BTRFS_IOC_GET_FSLABEL
, label
);
1311 if (errno
!= ENOTTY
)
1312 error("unable to get label of %s: %s", mount_path
,
1319 __strncpy_null(labelp
, label
, BTRFS_LABEL_SIZE
- 1);
1324 int get_label(const char *btrfs_dev
, char *label
)
1328 ret
= is_existing_blk_or_reg_file(btrfs_dev
);
1330 ret
= get_label_mounted(btrfs_dev
, label
);
1332 ret
= get_label_unmounted(btrfs_dev
, label
);
1337 int set_label(const char *btrfs_dev
, const char *label
)
1341 if (check_label(label
))
1344 ret
= is_existing_blk_or_reg_file(btrfs_dev
);
1346 ret
= set_label_mounted(btrfs_dev
, label
);
1348 ret
= set_label_unmounted(btrfs_dev
, label
);
1354 * A not-so-good version fls64. No fascinating optimization since
1355 * no one except parse_size use it
1357 static int fls64(u64 x
)
1361 for (i
= 0; i
<64; i
++)
1362 if (x
<< i
& (1ULL << 63))
1367 u64
parse_size(char *s
)
1375 error("size value is empty");
1379 error("size value '%s' is less equal than 0", s
);
1382 ret
= strtoull(s
, &endptr
, 10);
1384 error("size value '%s' is invalid", s
);
1387 if (endptr
[0] && endptr
[1]) {
1388 error("illegal suffix contains character '%c' in wrong position",
1393 * strtoll returns LLONG_MAX when overflow, if this happens,
1394 * need to call strtoull to get the real size
1396 if (errno
== ERANGE
&& ret
== ULLONG_MAX
) {
1397 error("size value '%s' is too large for u64", s
);
1401 c
= tolower(endptr
[0]);
1424 error("unknown size descriptor '%c'", c
);
1428 /* Check whether ret * mult overflow */
1429 if (fls64(ret
) + fls64(mult
) - 1 > 64) {
1430 error("size value '%s' is too large for u64", s
);
1437 u64
parse_qgroupid(const char *p
)
1439 char *s
= strchr(p
, '/');
1440 const char *ptr_src_end
= p
+ strlen(p
);
1441 char *ptr_parse_end
= NULL
;
1450 /* Numeric format like '0/257' is the primary case */
1452 id
= strtoull(p
, &ptr_parse_end
, 10);
1453 if (ptr_parse_end
!= ptr_src_end
)
1457 level
= strtoull(p
, &ptr_parse_end
, 10);
1458 if (ptr_parse_end
!= s
)
1461 id
= strtoull(s
+ 1, &ptr_parse_end
, 10);
1462 if (ptr_parse_end
!= ptr_src_end
)
1465 return (level
<< BTRFS_QGROUP_LEVEL_SHIFT
) | id
;
1468 /* Path format like subv at 'my_subvol' is the fallback case */
1469 ret
= test_issubvolume(p
);
1470 if (ret
< 0 || !ret
)
1472 fd
= open(p
, O_RDONLY
);
1475 ret
= lookup_path_rootid(fd
, &id
);
1477 error("failed to lookup root id: %s", strerror(-ret
));
1484 error("invalid qgroupid or subvolume path: %s", p
);
1488 int open_file_or_dir3(const char *fname
, DIR **dirstream
, int open_flags
)
1494 ret
= stat(fname
, &st
);
1498 if (S_ISDIR(st
.st_mode
)) {
1499 *dirstream
= opendir(fname
);
1502 fd
= dirfd(*dirstream
);
1503 } else if (S_ISREG(st
.st_mode
) || S_ISLNK(st
.st_mode
)) {
1504 fd
= open(fname
, open_flags
);
1507 * we set this on purpose, in case the caller output
1508 * strerror(errno) as success
1516 closedir(*dirstream
);
1523 int open_file_or_dir(const char *fname
, DIR **dirstream
)
1525 return open_file_or_dir3(fname
, dirstream
, O_RDWR
);
1528 void close_file_or_dir(int fd
, DIR *dirstream
)
1531 closedir(dirstream
);
1536 int get_device_info(int fd
, u64 devid
,
1537 struct btrfs_ioctl_dev_info_args
*di_args
)
1541 di_args
->devid
= devid
;
1542 memset(&di_args
->uuid
, '\0', sizeof(di_args
->uuid
));
1544 ret
= ioctl(fd
, BTRFS_IOC_DEV_INFO
, di_args
);
1545 return ret
< 0 ? -errno
: 0;
1548 static u64
find_max_device_id(struct btrfs_ioctl_search_args
*search_args
,
1551 struct btrfs_dev_item
*dev_item
;
1552 char *buf
= search_args
->buf
;
1554 buf
+= (nr_items
- 1) * (sizeof(struct btrfs_ioctl_search_header
)
1555 + sizeof(struct btrfs_dev_item
));
1556 buf
+= sizeof(struct btrfs_ioctl_search_header
);
1558 dev_item
= (struct btrfs_dev_item
*)buf
;
1560 return btrfs_stack_device_id(dev_item
);
1563 static int search_chunk_tree_for_fs_info(int fd
,
1564 struct btrfs_ioctl_fs_info_args
*fi_args
)
1568 u64 start_devid
= 1;
1569 struct btrfs_ioctl_search_args search_args
;
1570 struct btrfs_ioctl_search_key
*search_key
= &search_args
.key
;
1572 fi_args
->num_devices
= 0;
1574 max_items
= BTRFS_SEARCH_ARGS_BUFSIZE
1575 / (sizeof(struct btrfs_ioctl_search_header
)
1576 + sizeof(struct btrfs_dev_item
));
1578 search_key
->tree_id
= BTRFS_CHUNK_TREE_OBJECTID
;
1579 search_key
->min_objectid
= BTRFS_DEV_ITEMS_OBJECTID
;
1580 search_key
->max_objectid
= BTRFS_DEV_ITEMS_OBJECTID
;
1581 search_key
->min_type
= BTRFS_DEV_ITEM_KEY
;
1582 search_key
->max_type
= BTRFS_DEV_ITEM_KEY
;
1583 search_key
->min_transid
= 0;
1584 search_key
->max_transid
= (u64
)-1;
1585 search_key
->nr_items
= max_items
;
1586 search_key
->max_offset
= (u64
)-1;
1589 search_key
->min_offset
= start_devid
;
1591 ret
= ioctl(fd
, BTRFS_IOC_TREE_SEARCH
, &search_args
);
1595 fi_args
->num_devices
+= (u64
)search_key
->nr_items
;
1597 if (search_key
->nr_items
== max_items
) {
1598 start_devid
= find_max_device_id(&search_args
,
1599 search_key
->nr_items
) + 1;
1603 /* get the lastest max_id to stay consistent with the num_devices */
1604 if (search_key
->nr_items
== 0)
1606 * last tree_search returns an empty buf, use the devid of
1607 * the last dev_item of the previous tree_search
1609 fi_args
->max_id
= start_devid
- 1;
1611 fi_args
->max_id
= find_max_device_id(&search_args
,
1612 search_key
->nr_items
);
1618 * For a given path, fill in the ioctl fs_ and info_ args.
1619 * If the path is a btrfs mountpoint, fill info for all devices.
1620 * If the path is a btrfs device, fill in only that device.
1622 * The path provided must be either on a mounted btrfs fs,
1623 * or be a mounted btrfs device.
1625 * Returns 0 on success, or a negative errno.
1627 int get_fs_info(const char *path
, struct btrfs_ioctl_fs_info_args
*fi_args
,
1628 struct btrfs_ioctl_dev_info_args
**di_ret
)
1635 struct btrfs_fs_devices
*fs_devices_mnt
= NULL
;
1636 struct btrfs_ioctl_dev_info_args
*di_args
;
1637 struct btrfs_ioctl_dev_info_args tmp
;
1639 DIR *dirstream
= NULL
;
1641 memset(fi_args
, 0, sizeof(*fi_args
));
1643 if (is_block_device(path
) == 1) {
1644 struct btrfs_super_block
*disk_super
;
1645 char buf
[BTRFS_SUPER_INFO_SIZE
];
1647 /* Ensure it's mounted, then set path to the mountpoint */
1648 fd
= open(path
, O_RDONLY
);
1651 error("cannot open %s: %s", path
, strerror(errno
));
1654 ret
= check_mounted_where(fd
, path
, mp
, sizeof(mp
),
1663 /* Only fill in this one device */
1664 fi_args
->num_devices
= 1;
1666 disk_super
= (struct btrfs_super_block
*)buf
;
1667 ret
= btrfs_read_dev_super(fd
, disk_super
,
1668 BTRFS_SUPER_INFO_OFFSET
, 0);
1673 last_devid
= btrfs_stack_device_id(&disk_super
->dev_item
);
1674 fi_args
->max_id
= last_devid
;
1676 memcpy(fi_args
->fsid
, fs_devices_mnt
->fsid
, BTRFS_FSID_SIZE
);
1680 /* at this point path must not be for a block device */
1681 fd
= open_file_or_dir(path
, &dirstream
);
1687 /* fill in fi_args if not just a single device */
1688 if (fi_args
->num_devices
!= 1) {
1689 ret
= ioctl(fd
, BTRFS_IOC_FS_INFO
, fi_args
);
1696 * The fs_args->num_devices does not include seed devices
1698 ret
= search_chunk_tree_for_fs_info(fd
, fi_args
);
1703 * search_chunk_tree_for_fs_info() will lacks the devid 0
1704 * so manual probe for it here.
1706 ret
= get_device_info(fd
, 0, &tmp
);
1708 fi_args
->num_devices
++;
1711 if (last_devid
== 0)
1716 if (!fi_args
->num_devices
)
1719 di_args
= *di_ret
= malloc((fi_args
->num_devices
) * sizeof(*di_args
));
1726 memcpy(di_args
, &tmp
, sizeof(tmp
));
1727 for (; last_devid
<= fi_args
->max_id
; last_devid
++) {
1728 ret
= get_device_info(fd
, last_devid
, &di_args
[ndevs
]);
1737 * only when the only dev we wanted to find is not there then
1738 * let any error be returned
1740 if (fi_args
->num_devices
!= 1) {
1746 close_file_or_dir(fd
, dirstream
);
1750 static int group_profile_devs_min(u64 flag
)
1752 switch (flag
& BTRFS_BLOCK_GROUP_PROFILE_MASK
) {
1753 case 0: /* single */
1754 case BTRFS_BLOCK_GROUP_DUP
:
1756 case BTRFS_BLOCK_GROUP_RAID0
:
1757 case BTRFS_BLOCK_GROUP_RAID1
:
1758 case BTRFS_BLOCK_GROUP_RAID5
:
1760 case BTRFS_BLOCK_GROUP_RAID6
:
1762 case BTRFS_BLOCK_GROUP_RAID10
:
1769 int test_num_disk_vs_raid(u64 metadata_profile
, u64 data_profile
,
1770 u64 dev_cnt
, int mixed
, int ssd
)
1773 u64 profile
= metadata_profile
| data_profile
;
1778 allowed
|= BTRFS_BLOCK_GROUP_RAID10
;
1780 allowed
|= BTRFS_BLOCK_GROUP_RAID6
;
1782 allowed
|= BTRFS_BLOCK_GROUP_RAID0
| BTRFS_BLOCK_GROUP_RAID1
|
1783 BTRFS_BLOCK_GROUP_RAID5
;
1785 allowed
|= BTRFS_BLOCK_GROUP_DUP
;
1788 if (dev_cnt
> 1 && profile
& BTRFS_BLOCK_GROUP_DUP
) {
1789 warning("DUP is not recommended on filesystem with multiple devices");
1791 if (metadata_profile
& ~allowed
) {
1793 "ERROR: unable to create FS with metadata profile %s "
1794 "(have %llu devices but %d devices are required)\n",
1795 btrfs_group_profile_str(metadata_profile
), dev_cnt
,
1796 group_profile_devs_min(metadata_profile
));
1799 if (data_profile
& ~allowed
) {
1801 "ERROR: unable to create FS with data profile %s "
1802 "(have %llu devices but %d devices are required)\n",
1803 btrfs_group_profile_str(data_profile
), dev_cnt
,
1804 group_profile_devs_min(data_profile
));
1808 if (dev_cnt
== 3 && profile
& BTRFS_BLOCK_GROUP_RAID6
) {
1809 warning("RAID6 is not recommended on filesystem with 3 devices only");
1811 if (dev_cnt
== 2 && profile
& BTRFS_BLOCK_GROUP_RAID5
) {
1812 warning("RAID5 is not recommended on filesystem with 2 devices only");
1814 warning_on(!mixed
&& (data_profile
& BTRFS_BLOCK_GROUP_DUP
) && ssd
,
1815 "DUP may not actually lead to 2 copies on the device, see manual page");
1820 int group_profile_max_safe_loss(u64 flags
)
1822 switch (flags
& BTRFS_BLOCK_GROUP_PROFILE_MASK
) {
1823 case 0: /* single */
1824 case BTRFS_BLOCK_GROUP_DUP
:
1825 case BTRFS_BLOCK_GROUP_RAID0
:
1827 case BTRFS_BLOCK_GROUP_RAID1
:
1828 case BTRFS_BLOCK_GROUP_RAID5
:
1829 case BTRFS_BLOCK_GROUP_RAID10
:
1831 case BTRFS_BLOCK_GROUP_RAID6
:
1838 int btrfs_scan_devices(void)
1843 struct btrfs_fs_devices
*tmp_devices
;
1844 blkid_dev_iterate iter
= NULL
;
1845 blkid_dev dev
= NULL
;
1846 blkid_cache cache
= NULL
;
1847 char path
[PATH_MAX
];
1849 if (btrfs_scan_done
)
1852 if (blkid_get_cache(&cache
, NULL
) < 0) {
1853 error("blkid cache get failed");
1856 blkid_probe_all(cache
);
1857 iter
= blkid_dev_iterate_begin(cache
);
1858 blkid_dev_set_search(iter
, "TYPE", "btrfs");
1859 while (blkid_dev_next(iter
, &dev
) == 0) {
1860 dev
= blkid_verify(cache
, dev
);
1863 /* if we are here its definitely a btrfs disk*/
1864 strncpy_null(path
, blkid_dev_devname(dev
));
1866 fd
= open(path
, O_RDONLY
);
1868 error("cannot open %s: %s", path
, strerror(errno
));
1871 ret
= btrfs_scan_one_device(fd
, path
, &tmp_devices
,
1872 &num_devices
, BTRFS_SUPER_INFO_OFFSET
,
1875 error("cannot scan %s: %s", path
, strerror(-ret
));
1882 blkid_dev_iterate_end(iter
);
1883 blkid_put_cache(cache
);
1885 btrfs_scan_done
= 1;
1891 * This reads a line from the stdin and only returns non-zero if the
1892 * first whitespace delimited token is a case insensitive match with yes
1895 int ask_user(const char *question
)
1897 char buf
[30] = {0,};
1898 char *saveptr
= NULL
;
1901 printf("%s [y/N]: ", question
);
1903 return fgets(buf
, sizeof(buf
) - 1, stdin
) &&
1904 (answer
= strtok_r(buf
, " \t\n\r", &saveptr
)) &&
1905 (!strcasecmp(answer
, "yes") || !strcasecmp(answer
, "y"));
1909 * return 0 if a btrfs mount point is found
1910 * return 1 if a mount point is found but not btrfs
1911 * return <0 if something goes wrong
1913 int find_mount_root(const char *path
, char **mount_root
)
1921 int longest_matchlen
= 0;
1922 char *longest_match
= NULL
;
1924 fd
= open(path
, O_RDONLY
| O_NOATIME
);
1929 mnttab
= setmntent("/proc/self/mounts", "r");
1933 while ((ent
= getmntent(mnttab
))) {
1934 len
= strlen(ent
->mnt_dir
);
1935 if (strncmp(ent
->mnt_dir
, path
, len
) == 0) {
1936 /* match found and use the latest match */
1937 if (longest_matchlen
<= len
) {
1938 free(longest_match
);
1939 longest_matchlen
= len
;
1940 longest_match
= strdup(ent
->mnt_dir
);
1941 not_btrfs
= strcmp(ent
->mnt_type
, "btrfs");
1950 free(longest_match
);
1955 *mount_root
= realpath(longest_match
, NULL
);
1959 free(longest_match
);
1964 * Test if path is a directory
1966 * 0 - path exists but it is not a directory
1967 * 1 - path exists and it is a directory
1970 int test_isdir(const char *path
)
1975 ret
= stat(path
, &st
);
1979 return !!S_ISDIR(st
.st_mode
);
1982 void units_set_mode(unsigned *units
, unsigned mode
)
1984 unsigned base
= *units
& UNITS_MODE_MASK
;
1986 *units
= base
| mode
;
1989 void units_set_base(unsigned *units
, unsigned base
)
1991 unsigned mode
= *units
& ~UNITS_MODE_MASK
;
1993 *units
= base
| mode
;
1996 int find_next_key(struct btrfs_path
*path
, struct btrfs_key
*key
)
2000 for (level
= 0; level
< BTRFS_MAX_LEVEL
; level
++) {
2001 if (!path
->nodes
[level
])
2003 if (path
->slots
[level
] + 1 >=
2004 btrfs_header_nritems(path
->nodes
[level
]))
2007 btrfs_item_key_to_cpu(path
->nodes
[level
], key
,
2008 path
->slots
[level
] + 1);
2010 btrfs_node_key_to_cpu(path
->nodes
[level
], key
,
2011 path
->slots
[level
] + 1);
2017 const char* btrfs_group_type_str(u64 flag
)
2019 u64 mask
= BTRFS_BLOCK_GROUP_TYPE_MASK
|
2020 BTRFS_SPACE_INFO_GLOBAL_RSV
;
2022 switch (flag
& mask
) {
2023 case BTRFS_BLOCK_GROUP_DATA
:
2025 case BTRFS_BLOCK_GROUP_SYSTEM
:
2027 case BTRFS_BLOCK_GROUP_METADATA
:
2029 case BTRFS_BLOCK_GROUP_DATA
|BTRFS_BLOCK_GROUP_METADATA
:
2030 return "Data+Metadata";
2031 case BTRFS_SPACE_INFO_GLOBAL_RSV
:
2032 return "GlobalReserve";
2038 const char* btrfs_group_profile_str(u64 flag
)
2040 switch (flag
& BTRFS_BLOCK_GROUP_PROFILE_MASK
) {
2043 case BTRFS_BLOCK_GROUP_RAID0
:
2045 case BTRFS_BLOCK_GROUP_RAID1
:
2047 case BTRFS_BLOCK_GROUP_RAID5
:
2049 case BTRFS_BLOCK_GROUP_RAID6
:
2051 case BTRFS_BLOCK_GROUP_DUP
:
2053 case BTRFS_BLOCK_GROUP_RAID10
:
2060 u64
disk_size(const char *path
)
2064 if (statfs(path
, &sfs
) < 0)
2067 return sfs
.f_bsize
* sfs
.f_blocks
;
2070 u64
get_partition_size(const char *dev
)
2073 int fd
= open(dev
, O_RDONLY
);
2077 if (ioctl(fd
, BLKGETSIZE64
, &result
) < 0) {
2087 * Check if the BTRFS_IOC_TREE_SEARCH_V2 ioctl is supported on a given
2088 * filesystem, opened at fd
2090 int btrfs_tree_search2_ioctl_supported(int fd
)
2092 struct btrfs_ioctl_search_args_v2
*args2
;
2093 struct btrfs_ioctl_search_key
*sk
;
2094 int args2_size
= 1024;
2095 char args2_buf
[args2_size
];
2098 args2
= (struct btrfs_ioctl_search_args_v2
*)args2_buf
;
2102 * Search for the extent tree item in the root tree.
2104 sk
->tree_id
= BTRFS_ROOT_TREE_OBJECTID
;
2105 sk
->min_objectid
= BTRFS_EXTENT_TREE_OBJECTID
;
2106 sk
->max_objectid
= BTRFS_EXTENT_TREE_OBJECTID
;
2107 sk
->min_type
= BTRFS_ROOT_ITEM_KEY
;
2108 sk
->max_type
= BTRFS_ROOT_ITEM_KEY
;
2110 sk
->max_offset
= (u64
)-1;
2111 sk
->min_transid
= 0;
2112 sk
->max_transid
= (u64
)-1;
2114 args2
->buf_size
= args2_size
- sizeof(struct btrfs_ioctl_search_args_v2
);
2115 ret
= ioctl(fd
, BTRFS_IOC_TREE_SEARCH_V2
, args2
);
2116 if (ret
== -EOPNOTSUPP
)
2123 int btrfs_check_nodesize(u32 nodesize
, u32 sectorsize
, u64 features
)
2125 if (nodesize
< sectorsize
) {
2126 error("illegal nodesize %u (smaller than %u)",
2127 nodesize
, sectorsize
);
2129 } else if (nodesize
> BTRFS_MAX_METADATA_BLOCKSIZE
) {
2130 error("illegal nodesize %u (larger than %u)",
2131 nodesize
, BTRFS_MAX_METADATA_BLOCKSIZE
);
2133 } else if (nodesize
& (sectorsize
- 1)) {
2134 error("illegal nodesize %u (not aligned to %u)",
2135 nodesize
, sectorsize
);
2137 } else if (features
& BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS
&&
2138 nodesize
!= sectorsize
) {
2139 error("illegal nodesize %u (not equal to %u for mixed block group)",
2140 nodesize
, sectorsize
);
2147 * Copy a path argument from SRC to DEST and check the SRC length if it's at
2148 * most PATH_MAX and fits into DEST. DESTLEN is supposed to be exact size of
2150 * The destination buffer is zero terminated.
2151 * Return < 0 for error, 0 otherwise.
2153 int arg_copy_path(char *dest
, const char *src
, int destlen
)
2155 size_t len
= strlen(src
);
2157 if (len
>= PATH_MAX
|| len
>= destlen
)
2158 return -ENAMETOOLONG
;
2160 __strncpy_null(dest
, src
, destlen
);
2165 unsigned int get_unit_mode_from_arg(int *argc
, char *argv
[], int df_mode
)
2167 unsigned int unit_mode
= UNITS_DEFAULT
;
2171 for (arg_i
= 0; arg_i
< *argc
; arg_i
++) {
2172 if (!strcmp(argv
[arg_i
], "--"))
2175 if (!strcmp(argv
[arg_i
], "--raw")) {
2176 unit_mode
= UNITS_RAW
;
2180 if (!strcmp(argv
[arg_i
], "--human-readable")) {
2181 unit_mode
= UNITS_HUMAN_BINARY
;
2186 if (!strcmp(argv
[arg_i
], "--iec")) {
2187 units_set_mode(&unit_mode
, UNITS_BINARY
);
2191 if (!strcmp(argv
[arg_i
], "--si")) {
2192 units_set_mode(&unit_mode
, UNITS_DECIMAL
);
2197 if (!strcmp(argv
[arg_i
], "--kbytes")) {
2198 units_set_base(&unit_mode
, UNITS_KBYTES
);
2202 if (!strcmp(argv
[arg_i
], "--mbytes")) {
2203 units_set_base(&unit_mode
, UNITS_MBYTES
);
2207 if (!strcmp(argv
[arg_i
], "--gbytes")) {
2208 units_set_base(&unit_mode
, UNITS_GBYTES
);
2212 if (!strcmp(argv
[arg_i
], "--tbytes")) {
2213 units_set_base(&unit_mode
, UNITS_TBYTES
);
2221 if (!strcmp(argv
[arg_i
], "-b")) {
2222 unit_mode
= UNITS_RAW
;
2226 if (!strcmp(argv
[arg_i
], "-h")) {
2227 unit_mode
= UNITS_HUMAN_BINARY
;
2231 if (!strcmp(argv
[arg_i
], "-H")) {
2232 unit_mode
= UNITS_HUMAN_DECIMAL
;
2236 if (!strcmp(argv
[arg_i
], "-k")) {
2237 units_set_base(&unit_mode
, UNITS_KBYTES
);
2241 if (!strcmp(argv
[arg_i
], "-m")) {
2242 units_set_base(&unit_mode
, UNITS_MBYTES
);
2246 if (!strcmp(argv
[arg_i
], "-g")) {
2247 units_set_base(&unit_mode
, UNITS_GBYTES
);
2251 if (!strcmp(argv
[arg_i
], "-t")) {
2252 units_set_base(&unit_mode
, UNITS_TBYTES
);
2258 for (arg_i
= 0, arg_end
= 0; arg_i
< *argc
; arg_i
++) {
2261 argv
[arg_end
] = argv
[arg_i
];
2270 u64
div_factor(u64 num
, int factor
)
2279 * Get the length of the string converted from a u64 number.
2281 * Result is equal to log10(num) + 1, but without the use of math library.
2283 int count_digits(u64 num
)
2296 int string_is_numerical(const char *str
)
2300 if (!(*str
>= '0' && *str
<= '9'))
2302 while (*str
>= '0' && *str
<= '9')
2309 int prefixcmp(const char *str
, const char *prefix
)
2311 for (; ; str
++, prefix
++)
2314 else if (*str
!= *prefix
)
2315 return (unsigned char)*prefix
- (unsigned char)*str
;
2318 /* Subvolume helper functions */
2320 * test if name is a correct subvolume name
2321 * this function return
2322 * 0-> name is not a correct subvolume name
2323 * 1-> name is a correct subvolume name
2325 int test_issubvolname(const char *name
)
2327 return name
[0] != '\0' && !strchr(name
, '/') &&
2328 strcmp(name
, ".") && strcmp(name
, "..");
2332 * Test if path is a subvolume
2334 * 0 - path exists but it is not a subvolume
2335 * 1 - path exists and it is a subvolume
2338 int test_issubvolume(const char *path
)
2344 res
= stat(path
, &st
);
2348 if (st
.st_ino
!= BTRFS_FIRST_FREE_OBJECTID
|| !S_ISDIR(st
.st_mode
))
2351 res
= statfs(path
, &stfs
);
2355 return (int)stfs
.f_type
== BTRFS_SUPER_MAGIC
;
2358 const char *subvol_strip_mountpoint(const char *mnt
, const char *full_path
)
2360 int len
= strlen(mnt
);
2364 if (mnt
[len
- 1] != '/')
2367 return full_path
+ len
;
2374 * 1: Error; and error info printed to the terminal. Fixme.
2375 * 2: If the fullpath is root tree instead of subvol tree
2377 int get_subvol_info(const char *fullpath
, struct root_info
*get_ri
)
2384 const char *svpath
= NULL
;
2385 DIR *dirstream1
= NULL
;
2386 DIR *dirstream2
= NULL
;
2388 ret
= test_issubvolume(fullpath
);
2392 error("not a subvolume: %s", fullpath
);
2396 ret
= find_mount_root(fullpath
, &mnt
);
2400 error("%s doesn't belong to btrfs mount point", fullpath
);
2404 svpath
= subvol_strip_mountpoint(mnt
, fullpath
);
2406 fd
= btrfs_open_dir(fullpath
, &dirstream1
, 1);
2410 ret
= btrfs_list_get_path_rootid(fd
, &sv_id
);
2414 mntfd
= btrfs_open_dir(mnt
, &dirstream2
, 1);
2418 memset(get_ri
, 0, sizeof(*get_ri
));
2419 get_ri
->root_id
= sv_id
;
2421 if (sv_id
== BTRFS_FS_TREE_OBJECTID
)
2422 ret
= btrfs_get_toplevel_subvol(mntfd
, get_ri
);
2424 ret
= btrfs_get_subvol(mntfd
, get_ri
);
2426 error("can't find '%s': %d", svpath
, ret
);
2429 close_file_or_dir(mntfd
, dirstream2
);
2430 close_file_or_dir(fd
, dirstream1
);
2436 int get_subvol_info_by_rootid(const char *mnt
, struct root_info
*get_ri
, u64 r_id
)
2440 DIR *dirstream
= NULL
;
2442 fd
= btrfs_open_dir(mnt
, &dirstream
, 1);
2446 memset(get_ri
, 0, sizeof(*get_ri
));
2447 get_ri
->root_id
= r_id
;
2449 if (r_id
== BTRFS_FS_TREE_OBJECTID
)
2450 ret
= btrfs_get_toplevel_subvol(fd
, get_ri
);
2452 ret
= btrfs_get_subvol(fd
, get_ri
);
2455 error("can't find rootid '%llu' on '%s': %d", r_id
, mnt
, ret
);
2457 close_file_or_dir(fd
, dirstream
);
2462 int get_subvol_info_by_uuid(const char *mnt
, struct root_info
*get_ri
, u8
*uuid_arg
)
2466 DIR *dirstream
= NULL
;
2468 fd
= btrfs_open_dir(mnt
, &dirstream
, 1);
2472 memset(get_ri
, 0, sizeof(*get_ri
));
2473 uuid_copy(get_ri
->uuid
, uuid_arg
);
2475 ret
= btrfs_get_subvol(fd
, get_ri
);
2477 char uuid_parsed
[BTRFS_UUID_UNPARSED_SIZE
];
2478 uuid_unparse(uuid_arg
, uuid_parsed
);
2479 error("can't find uuid '%s' on '%s': %d",
2480 uuid_parsed
, mnt
, ret
);
2483 close_file_or_dir(fd
, dirstream
);
2488 /* Set the seed manually */
2489 void init_rand_seed(u64 seed
)
2493 /* only use the last 48 bits */
2494 for (i
= 0; i
< 3; i
++) {
2495 rand_seed
[i
] = (unsigned short)(seed
^ (unsigned short)(-1));
2498 rand_seed_initlized
= 1;
2501 static void __init_seed(void)
2507 if(rand_seed_initlized
)
2509 /* Use urandom as primary seed source. */
2510 fd
= open("/dev/urandom", O_RDONLY
);
2512 ret
= read(fd
, rand_seed
, sizeof(rand_seed
));
2514 if (ret
< sizeof(rand_seed
))
2518 /* Use time and pid as fallback seed */
2519 warning("failed to read /dev/urandom, use time and pid as random seed");
2520 gettimeofday(&tv
, 0);
2521 rand_seed
[0] = getpid() ^ (tv
.tv_sec
& 0xFFFF);
2522 rand_seed
[1] = getppid() ^ (tv
.tv_usec
& 0xFFFF);
2523 rand_seed
[2] = (tv
.tv_sec
^ tv
.tv_usec
) >> 16;
2525 rand_seed_initlized
= 1;
2532 * Don't use nrand48, its range is [0,2^31) The highest bit will alwasy
2533 * be 0. Use jrand48 to include the highest bit.
2535 return (u32
)jrand48(rand_seed
);
2538 /* Return random number in range [0, upper) */
2539 unsigned int rand_range(unsigned int upper
)
2543 * Use the full 48bits to mod, which would be more uniformly
2546 return (unsigned int)(jrand48(rand_seed
) % upper
);
2551 return (int)(rand_u32());
2566 return (u16
)(rand_u32());
2571 return (u8
)(rand_u32());
2574 void btrfs_config_init(void)