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_super_block
*super
= root
->fs_info
->super_copy
;
183 struct btrfs_device
*device
;
184 struct btrfs_dev_item
*dev_item
;
190 device_total_bytes
= (device_total_bytes
/ sectorsize
) * sectorsize
;
192 device
= calloc(1, sizeof(*device
));
197 buf
= calloc(1, sectorsize
);
203 disk_super
= (struct btrfs_super_block
*)buf
;
204 dev_item
= &disk_super
->dev_item
;
206 uuid_generate(device
->uuid
);
209 device
->io_width
= io_width
;
210 device
->io_align
= io_align
;
211 device
->sector_size
= sectorsize
;
213 device
->writeable
= 1;
214 device
->total_bytes
= device_total_bytes
;
215 device
->bytes_used
= 0;
216 device
->total_ios
= 0;
217 device
->dev_root
= root
->fs_info
->dev_root
;
218 device
->name
= strdup(path
);
224 INIT_LIST_HEAD(&device
->dev_list
);
225 ret
= btrfs_add_device(trans
, root
, device
);
229 fs_total_bytes
= btrfs_super_total_bytes(super
) + device_total_bytes
;
230 btrfs_set_super_total_bytes(super
, fs_total_bytes
);
232 num_devs
= btrfs_super_num_devices(super
) + 1;
233 btrfs_set_super_num_devices(super
, num_devs
);
235 memcpy(disk_super
, super
, sizeof(*disk_super
));
237 btrfs_set_super_bytenr(disk_super
, BTRFS_SUPER_INFO_OFFSET
);
238 btrfs_set_stack_device_id(dev_item
, device
->devid
);
239 btrfs_set_stack_device_type(dev_item
, device
->type
);
240 btrfs_set_stack_device_io_align(dev_item
, device
->io_align
);
241 btrfs_set_stack_device_io_width(dev_item
, device
->io_width
);
242 btrfs_set_stack_device_sector_size(dev_item
, device
->sector_size
);
243 btrfs_set_stack_device_total_bytes(dev_item
, device
->total_bytes
);
244 btrfs_set_stack_device_bytes_used(dev_item
, device
->bytes_used
);
245 memcpy(&dev_item
->uuid
, device
->uuid
, BTRFS_UUID_SIZE
);
247 ret
= pwrite(fd
, buf
, sectorsize
, BTRFS_SUPER_INFO_OFFSET
);
248 BUG_ON(ret
!= sectorsize
);
251 list_add(&device
->dev_list
, &root
->fs_info
->fs_devices
->devices
);
252 device
->fs_devices
= root
->fs_info
->fs_devices
;
261 static int btrfs_wipe_existing_sb(int fd
)
263 const char *off
= NULL
;
268 blkid_probe pr
= NULL
;
270 pr
= blkid_new_probe();
274 if (blkid_probe_set_device(pr
, fd
, 0, 0)) {
279 ret
= blkid_probe_lookup_value(pr
, "SBMAGIC_OFFSET", &off
, NULL
);
281 ret
= blkid_probe_lookup_value(pr
, "SBMAGIC", NULL
, &len
);
283 if (ret
|| len
== 0 || off
== NULL
) {
285 * If lookup fails, the probe did not find any values, eg. for
286 * a file image or a loop device. Soft error.
292 offset
= strtoll(off
, NULL
, 10);
293 if (len
> sizeof(buf
))
297 ret
= pwrite(fd
, buf
, len
, offset
);
299 error("cannot wipe existing superblock: %s", strerror(errno
));
301 } else if (ret
!= len
) {
302 error("cannot wipe existing superblock: wrote %d of %zd", ret
, len
);
308 blkid_free_probe(pr
);
312 int btrfs_prepare_device(int fd
, const char *file
, u64
*block_count_ret
,
313 u64 max_block_count
, unsigned opflags
)
319 ret
= fstat(fd
, &st
);
321 error("unable to stat %s: %s", file
, strerror(errno
));
325 block_count
= btrfs_device_size(fd
, &st
);
326 if (block_count
== 0) {
327 error("unable to determine size of %s", file
);
331 block_count
= min(block_count
, max_block_count
);
333 if (opflags
& PREP_DEVICE_DISCARD
) {
335 * We intentionally ignore errors from the discard ioctl. It
336 * is not necessary for the mkfs functionality but just an
339 if (discard_range(fd
, 0, 0) == 0) {
340 if (opflags
& PREP_DEVICE_VERBOSE
)
341 printf("Performing full device TRIM %s (%s) ...\n",
342 file
, pretty_size(block_count
));
343 discard_blocks(fd
, 0, block_count
);
347 ret
= zero_dev_clamped(fd
, 0, ZERO_DEV_BYTES
, block_count
);
348 for (i
= 0 ; !ret
&& i
< BTRFS_SUPER_MIRROR_MAX
; i
++)
349 ret
= zero_dev_clamped(fd
, btrfs_sb_offset(i
),
350 BTRFS_SUPER_INFO_SIZE
, block_count
);
351 if (!ret
&& (opflags
& PREP_DEVICE_ZERO_END
))
352 ret
= zero_dev_clamped(fd
, block_count
- ZERO_DEV_BYTES
,
353 ZERO_DEV_BYTES
, block_count
);
356 error("failed to zero device '%s': %s", file
, strerror(-ret
));
360 ret
= btrfs_wipe_existing_sb(fd
);
362 error("cannot wipe superblocks on %s", file
);
366 *block_count_ret
= block_count
;
370 int btrfs_make_root_dir(struct btrfs_trans_handle
*trans
,
371 struct btrfs_root
*root
, u64 objectid
)
374 struct btrfs_inode_item inode_item
;
375 time_t now
= time(NULL
);
377 memset(&inode_item
, 0, sizeof(inode_item
));
378 btrfs_set_stack_inode_generation(&inode_item
, trans
->transid
);
379 btrfs_set_stack_inode_size(&inode_item
, 0);
380 btrfs_set_stack_inode_nlink(&inode_item
, 1);
381 btrfs_set_stack_inode_nbytes(&inode_item
, root
->nodesize
);
382 btrfs_set_stack_inode_mode(&inode_item
, S_IFDIR
| 0755);
383 btrfs_set_stack_timespec_sec(&inode_item
.atime
, now
);
384 btrfs_set_stack_timespec_nsec(&inode_item
.atime
, 0);
385 btrfs_set_stack_timespec_sec(&inode_item
.ctime
, now
);
386 btrfs_set_stack_timespec_nsec(&inode_item
.ctime
, 0);
387 btrfs_set_stack_timespec_sec(&inode_item
.mtime
, now
);
388 btrfs_set_stack_timespec_nsec(&inode_item
.mtime
, 0);
389 btrfs_set_stack_timespec_sec(&inode_item
.otime
, now
);
390 btrfs_set_stack_timespec_nsec(&inode_item
.otime
, 0);
392 if (root
->fs_info
->tree_root
== root
)
393 btrfs_set_super_root_dir(root
->fs_info
->super_copy
, objectid
);
395 ret
= btrfs_insert_inode(trans
, root
, objectid
, &inode_item
);
399 ret
= btrfs_insert_inode_ref(trans
, root
, "..", 2, objectid
, objectid
, 0);
403 btrfs_set_root_dirid(&root
->root_item
, objectid
);
410 * checks if a path is a block device node
411 * Returns negative errno on failure, otherwise
412 * returns 1 for blockdev, 0 for not-blockdev
414 int is_block_device(const char *path
)
418 if (stat(path
, &statbuf
) < 0)
421 return !!S_ISBLK(statbuf
.st_mode
);
425 * check if given path is a mount point
426 * return 1 if yes. 0 if no. -1 for error
428 int is_mount_point(const char *path
)
434 f
= setmntent("/proc/self/mounts", "r");
438 while ((mnt
= getmntent(f
)) != NULL
) {
439 if (strcmp(mnt
->mnt_dir
, path
))
448 static int is_reg_file(const char *path
)
452 if (stat(path
, &statbuf
) < 0)
454 return S_ISREG(statbuf
.st_mode
);
458 * This function checks if the given input parameter is
460 * return <0 : some error in the given input
461 * return BTRFS_ARG_UNKNOWN: unknown input
462 * return BTRFS_ARG_UUID: given input is uuid
463 * return BTRFS_ARG_MNTPOINT: given input is path
464 * return BTRFS_ARG_REG: given input is regular file
465 * return BTRFS_ARG_BLKDEV: given input is block device
467 int check_arg_type(const char *input
)
475 if (realpath(input
, path
)) {
476 if (is_block_device(path
) == 1)
477 return BTRFS_ARG_BLKDEV
;
479 if (is_mount_point(path
) == 1)
480 return BTRFS_ARG_MNTPOINT
;
482 if (is_reg_file(path
))
483 return BTRFS_ARG_REG
;
485 return BTRFS_ARG_UNKNOWN
;
488 if (strlen(input
) == (BTRFS_UUID_UNPARSED_SIZE
- 1) &&
489 !uuid_parse(input
, uuid
))
490 return BTRFS_ARG_UUID
;
492 return BTRFS_ARG_UNKNOWN
;
496 * Find the mount point for a mounted device.
497 * On success, returns 0 with mountpoint in *mp.
498 * On failure, returns -errno (not mounted yields -EINVAL)
499 * Is noisy on failures, expects to be given a mounted device.
501 int get_btrfs_mount(const char *dev
, char *mp
, size_t mp_size
)
506 ret
= is_block_device(dev
);
509 error("not a block device: %s", dev
);
512 error("cannot check %s: %s", dev
, strerror(-ret
));
517 fd
= open(dev
, O_RDONLY
);
520 error("cannot open %s: %s", dev
, strerror(errno
));
524 ret
= check_mounted_where(fd
, dev
, mp
, mp_size
, NULL
);
527 } else { /* mounted, all good */
537 * Given a pathname, return a filehandle to:
538 * the original pathname or,
539 * if the pathname is a mounted btrfs device, to its mountpoint.
541 * On error, return -1, errno should be set.
543 int open_path_or_dev_mnt(const char *path
, DIR **dirstream
, int verbose
)
548 if (is_block_device(path
)) {
549 ret
= get_btrfs_mount(path
, mp
, sizeof(mp
));
551 /* not a mounted btrfs dev */
552 error_on(verbose
, "'%s' is not a mounted btrfs device",
557 ret
= open_file_or_dir(mp
, dirstream
);
558 error_on(verbose
&& ret
< 0, "can't access '%s': %s",
559 path
, strerror(errno
));
561 ret
= btrfs_open_dir(path
, dirstream
, 1);
568 * Do the following checks before calling open_file_or_dir():
569 * 1: path is in a btrfs filesystem
570 * 2: path is a directory
572 int btrfs_open_dir(const char *path
, DIR **dirstream
, int verbose
)
578 if (statfs(path
, &stfs
) != 0) {
579 error_on(verbose
, "cannot access '%s': %s", path
,
584 if (stfs
.f_type
!= BTRFS_SUPER_MAGIC
) {
585 error_on(verbose
, "not a btrfs filesystem: %s", path
);
589 if (stat(path
, &st
) != 0) {
590 error_on(verbose
, "cannot access '%s': %s", path
,
595 if (!S_ISDIR(st
.st_mode
)) {
596 error_on(verbose
, "not a directory: %s", path
);
600 ret
= open_file_or_dir(path
, dirstream
);
602 error_on(verbose
, "cannot access '%s': %s", path
,
609 /* checks if a device is a loop device */
610 static int is_loop_device (const char* device
) {
613 if(stat(device
, &statbuf
) < 0)
616 return (S_ISBLK(statbuf
.st_mode
) &&
617 MAJOR(statbuf
.st_rdev
) == LOOP_MAJOR
);
621 * Takes a loop device path (e.g. /dev/loop0) and returns
622 * the associated file (e.g. /images/my_btrfs.img) using
625 static int resolve_loop_device_with_loopdev(const char* loop_dev
, char* loop_file
)
629 struct loop_info64 lo64
;
631 fd
= open(loop_dev
, O_RDONLY
| O_NONBLOCK
);
634 ret
= ioctl(fd
, LOOP_GET_STATUS64
, &lo64
);
640 memcpy(loop_file
, lo64
.lo_file_name
, sizeof(lo64
.lo_file_name
));
641 loop_file
[sizeof(lo64
.lo_file_name
)] = 0;
649 /* Takes a loop device path (e.g. /dev/loop0) and returns
650 * the associated file (e.g. /images/my_btrfs.img) */
651 static int resolve_loop_device(const char* loop_dev
, char* loop_file
,
658 char real_loop_dev
[PATH_MAX
];
660 if (!realpath(loop_dev
, real_loop_dev
))
662 snprintf(p
, PATH_MAX
, "/sys/block/%s/loop/backing_file", strrchr(real_loop_dev
, '/'));
663 if (!(f
= fopen(p
, "r"))) {
666 * It's possibly a partitioned loop device, which is
667 * resolvable with loopdev API.
669 return resolve_loop_device_with_loopdev(loop_dev
, loop_file
);
673 snprintf(fmt
, 20, "%%%i[^\n]", max_len
-1);
674 ret
= fscanf(f
, fmt
, loop_file
);
683 * Checks whether a and b are identical or device
684 * files associated with the same block device
686 static int is_same_blk_file(const char* a
, const char* b
)
688 struct stat st_buf_a
, st_buf_b
;
689 char real_a
[PATH_MAX
];
690 char real_b
[PATH_MAX
];
692 if (!realpath(a
, real_a
))
693 strncpy_null(real_a
, a
);
695 if (!realpath(b
, real_b
))
696 strncpy_null(real_b
, b
);
698 /* Identical path? */
699 if (strcmp(real_a
, real_b
) == 0)
702 if (stat(a
, &st_buf_a
) < 0 || stat(b
, &st_buf_b
) < 0) {
708 /* Same blockdevice? */
709 if (S_ISBLK(st_buf_a
.st_mode
) && S_ISBLK(st_buf_b
.st_mode
) &&
710 st_buf_a
.st_rdev
== st_buf_b
.st_rdev
) {
715 if (st_buf_a
.st_dev
== st_buf_b
.st_dev
&&
716 st_buf_a
.st_ino
== st_buf_b
.st_ino
) {
723 /* checks if a and b are identical or device
724 * files associated with the same block device or
725 * if one file is a loop device that uses the other
728 static int is_same_loop_file(const char* a
, const char* b
)
730 char res_a
[PATH_MAX
];
731 char res_b
[PATH_MAX
];
732 const char* final_a
= NULL
;
733 const char* final_b
= NULL
;
736 /* Resolve a if it is a loop device */
737 if((ret
= is_loop_device(a
)) < 0) {
742 ret
= resolve_loop_device(a
, res_a
, sizeof(res_a
));
753 /* Resolve b if it is a loop device */
754 if ((ret
= is_loop_device(b
)) < 0) {
759 ret
= resolve_loop_device(b
, res_b
, sizeof(res_b
));
770 return is_same_blk_file(final_a
, final_b
);
773 /* Checks if a file exists and is a block or regular file*/
774 static int is_existing_blk_or_reg_file(const char* filename
)
778 if(stat(filename
, &st_buf
) < 0) {
785 return (S_ISBLK(st_buf
.st_mode
) || S_ISREG(st_buf
.st_mode
));
788 /* Checks if a file is used (directly or indirectly via a loop device)
789 * by a device in fs_devices
791 static int blk_file_in_dev_list(struct btrfs_fs_devices
* fs_devices
,
795 struct list_head
*head
;
796 struct list_head
*cur
;
797 struct btrfs_device
*device
;
799 head
= &fs_devices
->devices
;
800 list_for_each(cur
, head
) {
801 device
= list_entry(cur
, struct btrfs_device
, dev_list
);
803 if((ret
= is_same_loop_file(device
->name
, file
)))
811 * Resolve a pathname to a device mapper node to /dev/mapper/<name>
812 * Returns NULL on invalid input or malloc failure; Other failures
813 * will be handled by the caller using the input pathame.
815 char *canonicalize_dm_name(const char *ptname
)
819 char path
[PATH_MAX
], name
[PATH_MAX
], *res
= NULL
;
821 if (!ptname
|| !*ptname
)
824 snprintf(path
, sizeof(path
), "/sys/block/%s/dm/name", ptname
);
825 if (!(f
= fopen(path
, "r")))
828 /* read <name>\n from sysfs */
829 if (fgets(name
, sizeof(name
), f
) && (sz
= strlen(name
)) > 1) {
831 snprintf(path
, sizeof(path
), "/dev/mapper/%s", name
);
833 if (access(path
, F_OK
) == 0)
841 * Resolve a pathname to a canonical device node, e.g. /dev/sda1 or
842 * to a device mapper pathname.
843 * Returns NULL on invalid input or malloc failure; Other failures
844 * will be handled by the caller using the input pathame.
846 char *canonicalize_path(const char *path
)
853 canonical
= realpath(path
, NULL
);
856 p
= strrchr(canonical
, '/');
857 if (p
&& strncmp(p
, "/dm-", 4) == 0 && isdigit(*(p
+ 4))) {
858 char *dm
= canonicalize_dm_name(p
+ 1);
869 * returns 1 if the device was mounted, < 0 on error or 0 if everything
870 * is safe to continue.
872 int check_mounted(const char* file
)
877 fd
= open(file
, O_RDONLY
);
879 error("mount check: cannot open %s: %s", file
,
884 ret
= check_mounted_where(fd
, file
, NULL
, 0, NULL
);
890 int check_mounted_where(int fd
, const char *file
, char *where
, int size
,
891 struct btrfs_fs_devices
**fs_dev_ret
)
896 struct btrfs_fs_devices
*fs_devices_mnt
= NULL
;
900 /* scan the initial device */
901 ret
= btrfs_scan_one_device(fd
, file
, &fs_devices_mnt
,
902 &total_devs
, BTRFS_SUPER_INFO_OFFSET
, SBREAD_DEFAULT
);
903 is_btrfs
= (ret
>= 0);
905 /* scan other devices */
906 if (is_btrfs
&& total_devs
> 1) {
907 ret
= btrfs_scan_devices();
912 /* iterate over the list of currently mounted filesystems */
913 if ((f
= setmntent ("/proc/self/mounts", "r")) == NULL
)
916 while ((mnt
= getmntent (f
)) != NULL
) {
918 if(strcmp(mnt
->mnt_type
, "btrfs") != 0)
921 ret
= blk_file_in_dev_list(fs_devices_mnt
, mnt
->mnt_fsname
);
923 /* ignore entries in the mount table that are not
924 associated with a file*/
925 if((ret
= is_existing_blk_or_reg_file(mnt
->mnt_fsname
)) < 0)
926 goto out_mntloop_err
;
930 ret
= is_same_loop_file(file
, mnt
->mnt_fsname
);
934 goto out_mntloop_err
;
939 /* Did we find an entry in mnt table? */
940 if (mnt
&& size
&& where
) {
941 strncpy(where
, mnt
->mnt_dir
, size
);
945 *fs_dev_ret
= fs_devices_mnt
;
956 struct list_head list
;
960 int btrfs_register_one_device(const char *fname
)
962 struct btrfs_ioctl_vol_args args
;
966 fd
= open("/dev/btrfs-control", O_RDWR
);
969 "failed to open /dev/btrfs-control, skipping device registration: %s",
973 memset(&args
, 0, sizeof(args
));
974 strncpy_null(args
.name
, fname
);
975 ret
= ioctl(fd
, BTRFS_IOC_SCAN_DEV
, &args
);
977 error("device scan failed on '%s': %s", fname
,
986 * Register all devices in the fs_uuid list created in the user
987 * space. Ensure btrfs_scan_devices() is called before this func.
989 int btrfs_register_all_devices(void)
993 struct btrfs_fs_devices
*fs_devices
;
994 struct btrfs_device
*device
;
995 struct list_head
*all_uuids
;
997 all_uuids
= btrfs_scanned_uuids();
999 list_for_each_entry(fs_devices
, all_uuids
, list
) {
1000 list_for_each_entry(device
, &fs_devices
->devices
, dev_list
) {
1002 err
= btrfs_register_one_device(device
->name
);
1012 int btrfs_device_already_in_root(struct btrfs_root
*root
, int fd
,
1015 struct btrfs_super_block
*disk_super
;
1019 buf
= malloc(BTRFS_SUPER_INFO_SIZE
);
1024 ret
= pread(fd
, buf
, BTRFS_SUPER_INFO_SIZE
, super_offset
);
1025 if (ret
!= BTRFS_SUPER_INFO_SIZE
)
1029 disk_super
= (struct btrfs_super_block
*)buf
;
1031 * Accept devices from the same filesystem, allow partially created
1034 if (btrfs_super_magic(disk_super
) != BTRFS_MAGIC
&&
1035 btrfs_super_magic(disk_super
) != BTRFS_MAGIC_PARTIAL
)
1038 if (!memcmp(disk_super
->fsid
, root
->fs_info
->super_copy
->fsid
,
1048 * Note: this function uses a static per-thread buffer. Do not call this
1049 * function more than 10 times within one argument list!
1051 const char *pretty_size_mode(u64 size
, unsigned mode
)
1053 static __thread
int ps_index
= 0;
1054 static __thread
char ps_array
[10][32];
1057 ret
= ps_array
[ps_index
];
1060 (void)pretty_size_snprintf(size
, ret
, 32, mode
);
1065 static const char* unit_suffix_binary
[] =
1066 { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"};
1067 static const char* unit_suffix_decimal
[] =
1068 { "B", "kB", "MB", "GB", "TB", "PB", "EB"};
1070 int pretty_size_snprintf(u64 size
, char *str
, size_t str_size
, unsigned unit_mode
)
1076 const char** suffix
= NULL
;
1083 negative
= !!(unit_mode
& UNITS_NEGATIVE
);
1084 unit_mode
&= ~UNITS_NEGATIVE
;
1086 if ((unit_mode
& ~UNITS_MODE_MASK
) == UNITS_RAW
) {
1088 snprintf(str
, str_size
, "%lld", size
);
1090 snprintf(str
, str_size
, "%llu", size
);
1094 if ((unit_mode
& ~UNITS_MODE_MASK
) == UNITS_BINARY
) {
1097 suffix
= unit_suffix_binary
;
1098 } else if ((unit_mode
& ~UNITS_MODE_MASK
) == UNITS_DECIMAL
) {
1101 suffix
= unit_suffix_decimal
;
1106 fprintf(stderr
, "INTERNAL ERROR: unknown unit base, mode %d\n",
1114 switch (unit_mode
& UNITS_MODE_MASK
) {
1115 case UNITS_TBYTES
: base
*= mult
; num_divs
++;
1116 case UNITS_GBYTES
: base
*= mult
; num_divs
++;
1117 case UNITS_MBYTES
: base
*= mult
; num_divs
++;
1118 case UNITS_KBYTES
: num_divs
++;
1126 s64 ssize
= (s64
)size
;
1127 s64 last_ssize
= ssize
;
1129 while ((ssize
< 0 ? -ssize
: ssize
) >= mult
) {
1134 last_size
= (u64
)last_ssize
;
1136 while (size
>= mult
) {
1143 * If the value is smaller than base, we didn't do any
1144 * division, in that case, base should be 1, not original
1145 * base, or the unit will be wrong
1151 if (num_divs
>= ARRAY_SIZE(unit_suffix_binary
)) {
1153 printf("INTERNAL ERROR: unsupported unit suffix, index %d\n",
1160 fraction
= (float)(s64
)last_size
/ base
;
1162 fraction
= (float)last_size
/ base
;
1165 return snprintf(str
, str_size
, "%.2f%s", fraction
, suffix
[num_divs
]);
1169 * __strncpy_null - strncpy with null termination
1170 * @dest: the target array
1171 * @src: the source string
1172 * @n: maximum bytes to copy (size of *dest)
1174 * Like strncpy, but ensures destination is null-terminated.
1176 * Copies the string pointed to by src, including the terminating null
1177 * byte ('\0'), to the buffer pointed to by dest, up to a maximum
1178 * of n bytes. Then ensure that dest is null-terminated.
1180 char *__strncpy_null(char *dest
, const char *src
, size_t n
)
1182 strncpy(dest
, src
, n
);
1189 * Checks to make sure that the label matches our requirements.
1191 0 if everything is safe and usable
1192 -1 if the label is too long
1194 static int check_label(const char *input
)
1196 int len
= strlen(input
);
1198 if (len
> BTRFS_LABEL_SIZE
- 1) {
1199 error("label %s is too long (max %d)", input
,
1200 BTRFS_LABEL_SIZE
- 1);
1207 static int set_label_unmounted(const char *dev
, const char *label
)
1209 struct btrfs_trans_handle
*trans
;
1210 struct btrfs_root
*root
;
1213 ret
= check_mounted(dev
);
1215 error("checking mount status of %s failed: %d", dev
, ret
);
1219 error("device %s is mounted, use mount point", dev
);
1223 /* Open the super_block at the default location
1224 * and as read-write.
1226 root
= open_ctree(dev
, 0, OPEN_CTREE_WRITES
);
1227 if (!root
) /* errors are printed by open_ctree() */
1230 trans
= btrfs_start_transaction(root
, 1);
1231 __strncpy_null(root
->fs_info
->super_copy
->label
, label
, BTRFS_LABEL_SIZE
- 1);
1233 btrfs_commit_transaction(trans
, root
);
1235 /* Now we close it since we are done. */
1240 static int set_label_mounted(const char *mount_path
, const char *labelp
)
1243 char label
[BTRFS_LABEL_SIZE
];
1245 fd
= open(mount_path
, O_RDONLY
| O_NOATIME
);
1247 error("unable to access %s: %s", mount_path
, strerror(errno
));
1251 memset(label
, 0, sizeof(label
));
1252 __strncpy_null(label
, labelp
, BTRFS_LABEL_SIZE
- 1);
1253 if (ioctl(fd
, BTRFS_IOC_SET_FSLABEL
, label
) < 0) {
1254 error("unable to set label of %s: %s", mount_path
,
1264 int get_label_unmounted(const char *dev
, char *label
)
1266 struct btrfs_root
*root
;
1269 ret
= check_mounted(dev
);
1271 error("checking mount status of %s failed: %d", dev
, ret
);
1275 /* Open the super_block at the default location
1278 root
= open_ctree(dev
, 0, 0);
1282 __strncpy_null(label
, root
->fs_info
->super_copy
->label
,
1283 BTRFS_LABEL_SIZE
- 1);
1285 /* Now we close it since we are done. */
1291 * If a partition is mounted, try to get the filesystem label via its
1292 * mounted path rather than device. Return the corresponding error
1293 * the user specified the device path.
1295 int get_label_mounted(const char *mount_path
, char *labelp
)
1297 char label
[BTRFS_LABEL_SIZE
];
1301 fd
= open(mount_path
, O_RDONLY
| O_NOATIME
);
1303 error("unable to access %s: %s", mount_path
, strerror(errno
));
1307 memset(label
, '\0', sizeof(label
));
1308 ret
= ioctl(fd
, BTRFS_IOC_GET_FSLABEL
, label
);
1310 if (errno
!= ENOTTY
)
1311 error("unable to get label of %s: %s", mount_path
,
1318 __strncpy_null(labelp
, label
, BTRFS_LABEL_SIZE
- 1);
1323 int get_label(const char *btrfs_dev
, char *label
)
1327 ret
= is_existing_blk_or_reg_file(btrfs_dev
);
1329 ret
= get_label_mounted(btrfs_dev
, label
);
1331 ret
= get_label_unmounted(btrfs_dev
, label
);
1336 int set_label(const char *btrfs_dev
, const char *label
)
1340 if (check_label(label
))
1343 ret
= is_existing_blk_or_reg_file(btrfs_dev
);
1345 ret
= set_label_mounted(btrfs_dev
, label
);
1347 ret
= set_label_unmounted(btrfs_dev
, label
);
1353 * A not-so-good version fls64. No fascinating optimization since
1354 * no one except parse_size use it
1356 static int fls64(u64 x
)
1360 for (i
= 0; i
<64; i
++)
1361 if (x
<< i
& (1ULL << 63))
1366 u64
parse_size(char *s
)
1374 error("size value is empty");
1378 error("size value '%s' is less equal than 0", s
);
1381 ret
= strtoull(s
, &endptr
, 10);
1383 error("size value '%s' is invalid", s
);
1386 if (endptr
[0] && endptr
[1]) {
1387 error("illegal suffix contains character '%c' in wrong position",
1392 * strtoll returns LLONG_MAX when overflow, if this happens,
1393 * need to call strtoull to get the real size
1395 if (errno
== ERANGE
&& ret
== ULLONG_MAX
) {
1396 error("size value '%s' is too large for u64", s
);
1400 c
= tolower(endptr
[0]);
1423 error("unknown size descriptor '%c'", c
);
1427 /* Check whether ret * mult overflow */
1428 if (fls64(ret
) + fls64(mult
) - 1 > 64) {
1429 error("size value '%s' is too large for u64", s
);
1436 u64
parse_qgroupid(const char *p
)
1438 char *s
= strchr(p
, '/');
1439 const char *ptr_src_end
= p
+ strlen(p
);
1440 char *ptr_parse_end
= NULL
;
1449 /* Numeric format like '0/257' is the primary case */
1451 id
= strtoull(p
, &ptr_parse_end
, 10);
1452 if (ptr_parse_end
!= ptr_src_end
)
1456 level
= strtoull(p
, &ptr_parse_end
, 10);
1457 if (ptr_parse_end
!= s
)
1460 id
= strtoull(s
+ 1, &ptr_parse_end
, 10);
1461 if (ptr_parse_end
!= ptr_src_end
)
1464 return (level
<< BTRFS_QGROUP_LEVEL_SHIFT
) | id
;
1467 /* Path format like subv at 'my_subvol' is the fallback case */
1468 ret
= test_issubvolume(p
);
1469 if (ret
< 0 || !ret
)
1471 fd
= open(p
, O_RDONLY
);
1474 ret
= lookup_path_rootid(fd
, &id
);
1476 error("failed to lookup root id: %s", strerror(-ret
));
1483 error("invalid qgroupid or subvolume path: %s", p
);
1487 int open_file_or_dir3(const char *fname
, DIR **dirstream
, int open_flags
)
1493 ret
= stat(fname
, &st
);
1497 if (S_ISDIR(st
.st_mode
)) {
1498 *dirstream
= opendir(fname
);
1501 fd
= dirfd(*dirstream
);
1502 } else if (S_ISREG(st
.st_mode
) || S_ISLNK(st
.st_mode
)) {
1503 fd
= open(fname
, open_flags
);
1506 * we set this on purpose, in case the caller output
1507 * strerror(errno) as success
1515 closedir(*dirstream
);
1522 int open_file_or_dir(const char *fname
, DIR **dirstream
)
1524 return open_file_or_dir3(fname
, dirstream
, O_RDWR
);
1527 void close_file_or_dir(int fd
, DIR *dirstream
)
1530 closedir(dirstream
);
1535 int get_device_info(int fd
, u64 devid
,
1536 struct btrfs_ioctl_dev_info_args
*di_args
)
1540 di_args
->devid
= devid
;
1541 memset(&di_args
->uuid
, '\0', sizeof(di_args
->uuid
));
1543 ret
= ioctl(fd
, BTRFS_IOC_DEV_INFO
, di_args
);
1544 return ret
< 0 ? -errno
: 0;
1547 static u64
find_max_device_id(struct btrfs_ioctl_search_args
*search_args
,
1550 struct btrfs_dev_item
*dev_item
;
1551 char *buf
= search_args
->buf
;
1553 buf
+= (nr_items
- 1) * (sizeof(struct btrfs_ioctl_search_header
)
1554 + sizeof(struct btrfs_dev_item
));
1555 buf
+= sizeof(struct btrfs_ioctl_search_header
);
1557 dev_item
= (struct btrfs_dev_item
*)buf
;
1559 return btrfs_stack_device_id(dev_item
);
1562 static int search_chunk_tree_for_fs_info(int fd
,
1563 struct btrfs_ioctl_fs_info_args
*fi_args
)
1567 u64 start_devid
= 1;
1568 struct btrfs_ioctl_search_args search_args
;
1569 struct btrfs_ioctl_search_key
*search_key
= &search_args
.key
;
1571 fi_args
->num_devices
= 0;
1573 max_items
= BTRFS_SEARCH_ARGS_BUFSIZE
1574 / (sizeof(struct btrfs_ioctl_search_header
)
1575 + sizeof(struct btrfs_dev_item
));
1577 search_key
->tree_id
= BTRFS_CHUNK_TREE_OBJECTID
;
1578 search_key
->min_objectid
= BTRFS_DEV_ITEMS_OBJECTID
;
1579 search_key
->max_objectid
= BTRFS_DEV_ITEMS_OBJECTID
;
1580 search_key
->min_type
= BTRFS_DEV_ITEM_KEY
;
1581 search_key
->max_type
= BTRFS_DEV_ITEM_KEY
;
1582 search_key
->min_transid
= 0;
1583 search_key
->max_transid
= (u64
)-1;
1584 search_key
->nr_items
= max_items
;
1585 search_key
->max_offset
= (u64
)-1;
1588 search_key
->min_offset
= start_devid
;
1590 ret
= ioctl(fd
, BTRFS_IOC_TREE_SEARCH
, &search_args
);
1594 fi_args
->num_devices
+= (u64
)search_key
->nr_items
;
1596 if (search_key
->nr_items
== max_items
) {
1597 start_devid
= find_max_device_id(&search_args
,
1598 search_key
->nr_items
) + 1;
1602 /* get the lastest max_id to stay consistent with the num_devices */
1603 if (search_key
->nr_items
== 0)
1605 * last tree_search returns an empty buf, use the devid of
1606 * the last dev_item of the previous tree_search
1608 fi_args
->max_id
= start_devid
- 1;
1610 fi_args
->max_id
= find_max_device_id(&search_args
,
1611 search_key
->nr_items
);
1617 * For a given path, fill in the ioctl fs_ and info_ args.
1618 * If the path is a btrfs mountpoint, fill info for all devices.
1619 * If the path is a btrfs device, fill in only that device.
1621 * The path provided must be either on a mounted btrfs fs,
1622 * or be a mounted btrfs device.
1624 * Returns 0 on success, or a negative errno.
1626 int get_fs_info(const char *path
, struct btrfs_ioctl_fs_info_args
*fi_args
,
1627 struct btrfs_ioctl_dev_info_args
**di_ret
)
1634 struct btrfs_fs_devices
*fs_devices_mnt
= NULL
;
1635 struct btrfs_ioctl_dev_info_args
*di_args
;
1636 struct btrfs_ioctl_dev_info_args tmp
;
1638 DIR *dirstream
= NULL
;
1640 memset(fi_args
, 0, sizeof(*fi_args
));
1642 if (is_block_device(path
) == 1) {
1643 struct btrfs_super_block
*disk_super
;
1644 char buf
[BTRFS_SUPER_INFO_SIZE
];
1646 /* Ensure it's mounted, then set path to the mountpoint */
1647 fd
= open(path
, O_RDONLY
);
1650 error("cannot open %s: %s", path
, strerror(errno
));
1653 ret
= check_mounted_where(fd
, path
, mp
, sizeof(mp
),
1662 /* Only fill in this one device */
1663 fi_args
->num_devices
= 1;
1665 disk_super
= (struct btrfs_super_block
*)buf
;
1666 ret
= btrfs_read_dev_super(fd
, disk_super
,
1667 BTRFS_SUPER_INFO_OFFSET
, 0);
1672 last_devid
= btrfs_stack_device_id(&disk_super
->dev_item
);
1673 fi_args
->max_id
= last_devid
;
1675 memcpy(fi_args
->fsid
, fs_devices_mnt
->fsid
, BTRFS_FSID_SIZE
);
1679 /* at this point path must not be for a block device */
1680 fd
= open_file_or_dir(path
, &dirstream
);
1686 /* fill in fi_args if not just a single device */
1687 if (fi_args
->num_devices
!= 1) {
1688 ret
= ioctl(fd
, BTRFS_IOC_FS_INFO
, fi_args
);
1695 * The fs_args->num_devices does not include seed devices
1697 ret
= search_chunk_tree_for_fs_info(fd
, fi_args
);
1702 * search_chunk_tree_for_fs_info() will lacks the devid 0
1703 * so manual probe for it here.
1705 ret
= get_device_info(fd
, 0, &tmp
);
1707 fi_args
->num_devices
++;
1710 if (last_devid
== 0)
1715 if (!fi_args
->num_devices
)
1718 di_args
= *di_ret
= malloc((fi_args
->num_devices
) * sizeof(*di_args
));
1725 memcpy(di_args
, &tmp
, sizeof(tmp
));
1726 for (; last_devid
<= fi_args
->max_id
; last_devid
++) {
1727 ret
= get_device_info(fd
, last_devid
, &di_args
[ndevs
]);
1736 * only when the only dev we wanted to find is not there then
1737 * let any error be returned
1739 if (fi_args
->num_devices
!= 1) {
1745 close_file_or_dir(fd
, dirstream
);
1749 static int group_profile_devs_min(u64 flag
)
1751 switch (flag
& BTRFS_BLOCK_GROUP_PROFILE_MASK
) {
1752 case 0: /* single */
1753 case BTRFS_BLOCK_GROUP_DUP
:
1755 case BTRFS_BLOCK_GROUP_RAID0
:
1756 case BTRFS_BLOCK_GROUP_RAID1
:
1757 case BTRFS_BLOCK_GROUP_RAID5
:
1759 case BTRFS_BLOCK_GROUP_RAID6
:
1761 case BTRFS_BLOCK_GROUP_RAID10
:
1768 int test_num_disk_vs_raid(u64 metadata_profile
, u64 data_profile
,
1769 u64 dev_cnt
, int mixed
, int ssd
)
1772 u64 profile
= metadata_profile
| data_profile
;
1777 allowed
|= BTRFS_BLOCK_GROUP_RAID10
;
1779 allowed
|= BTRFS_BLOCK_GROUP_RAID6
;
1781 allowed
|= BTRFS_BLOCK_GROUP_RAID0
| BTRFS_BLOCK_GROUP_RAID1
|
1782 BTRFS_BLOCK_GROUP_RAID5
;
1784 allowed
|= BTRFS_BLOCK_GROUP_DUP
;
1787 if (dev_cnt
> 1 && profile
& BTRFS_BLOCK_GROUP_DUP
) {
1788 warning("DUP is not recommended on filesystem with multiple devices");
1790 if (metadata_profile
& ~allowed
) {
1792 "ERROR: unable to create FS with metadata profile %s "
1793 "(have %llu devices but %d devices are required)\n",
1794 btrfs_group_profile_str(metadata_profile
), dev_cnt
,
1795 group_profile_devs_min(metadata_profile
));
1798 if (data_profile
& ~allowed
) {
1800 "ERROR: unable to create FS with data profile %s "
1801 "(have %llu devices but %d devices are required)\n",
1802 btrfs_group_profile_str(data_profile
), dev_cnt
,
1803 group_profile_devs_min(data_profile
));
1807 if (dev_cnt
== 3 && profile
& BTRFS_BLOCK_GROUP_RAID6
) {
1808 warning("RAID6 is not recommended on filesystem with 3 devices only");
1810 if (dev_cnt
== 2 && profile
& BTRFS_BLOCK_GROUP_RAID5
) {
1811 warning("RAID5 is not recommended on filesystem with 2 devices only");
1813 warning_on(!mixed
&& (data_profile
& BTRFS_BLOCK_GROUP_DUP
) && ssd
,
1814 "DUP may not actually lead to 2 copies on the device, see manual page");
1819 int group_profile_max_safe_loss(u64 flags
)
1821 switch (flags
& BTRFS_BLOCK_GROUP_PROFILE_MASK
) {
1822 case 0: /* single */
1823 case BTRFS_BLOCK_GROUP_DUP
:
1824 case BTRFS_BLOCK_GROUP_RAID0
:
1826 case BTRFS_BLOCK_GROUP_RAID1
:
1827 case BTRFS_BLOCK_GROUP_RAID5
:
1828 case BTRFS_BLOCK_GROUP_RAID10
:
1830 case BTRFS_BLOCK_GROUP_RAID6
:
1837 int btrfs_scan_devices(void)
1842 struct btrfs_fs_devices
*tmp_devices
;
1843 blkid_dev_iterate iter
= NULL
;
1844 blkid_dev dev
= NULL
;
1845 blkid_cache cache
= NULL
;
1846 char path
[PATH_MAX
];
1848 if (btrfs_scan_done
)
1851 if (blkid_get_cache(&cache
, NULL
) < 0) {
1852 error("blkid cache get failed");
1855 blkid_probe_all(cache
);
1856 iter
= blkid_dev_iterate_begin(cache
);
1857 blkid_dev_set_search(iter
, "TYPE", "btrfs");
1858 while (blkid_dev_next(iter
, &dev
) == 0) {
1859 dev
= blkid_verify(cache
, dev
);
1862 /* if we are here its definitely a btrfs disk*/
1863 strncpy_null(path
, blkid_dev_devname(dev
));
1865 fd
= open(path
, O_RDONLY
);
1867 error("cannot open %s: %s", path
, strerror(errno
));
1870 ret
= btrfs_scan_one_device(fd
, path
, &tmp_devices
,
1871 &num_devices
, BTRFS_SUPER_INFO_OFFSET
,
1874 error("cannot scan %s: %s", path
, strerror(-ret
));
1881 blkid_dev_iterate_end(iter
);
1882 blkid_put_cache(cache
);
1884 btrfs_scan_done
= 1;
1890 * This reads a line from the stdin and only returns non-zero if the
1891 * first whitespace delimited token is a case insensitive match with yes
1894 int ask_user(const char *question
)
1896 char buf
[30] = {0,};
1897 char *saveptr
= NULL
;
1900 printf("%s [y/N]: ", question
);
1902 return fgets(buf
, sizeof(buf
) - 1, stdin
) &&
1903 (answer
= strtok_r(buf
, " \t\n\r", &saveptr
)) &&
1904 (!strcasecmp(answer
, "yes") || !strcasecmp(answer
, "y"));
1908 * return 0 if a btrfs mount point is found
1909 * return 1 if a mount point is found but not btrfs
1910 * return <0 if something goes wrong
1912 int find_mount_root(const char *path
, char **mount_root
)
1920 int longest_matchlen
= 0;
1921 char *longest_match
= NULL
;
1923 fd
= open(path
, O_RDONLY
| O_NOATIME
);
1928 mnttab
= setmntent("/proc/self/mounts", "r");
1932 while ((ent
= getmntent(mnttab
))) {
1933 len
= strlen(ent
->mnt_dir
);
1934 if (strncmp(ent
->mnt_dir
, path
, len
) == 0) {
1935 /* match found and use the latest match */
1936 if (longest_matchlen
<= len
) {
1937 free(longest_match
);
1938 longest_matchlen
= len
;
1939 longest_match
= strdup(ent
->mnt_dir
);
1940 not_btrfs
= strcmp(ent
->mnt_type
, "btrfs");
1949 free(longest_match
);
1954 *mount_root
= realpath(longest_match
, NULL
);
1958 free(longest_match
);
1963 * Test if path is a directory
1965 * 0 - path exists but it is not a directory
1966 * 1 - path exists and it is a directory
1969 int test_isdir(const char *path
)
1974 ret
= stat(path
, &st
);
1978 return !!S_ISDIR(st
.st_mode
);
1981 void units_set_mode(unsigned *units
, unsigned mode
)
1983 unsigned base
= *units
& UNITS_MODE_MASK
;
1985 *units
= base
| mode
;
1988 void units_set_base(unsigned *units
, unsigned base
)
1990 unsigned mode
= *units
& ~UNITS_MODE_MASK
;
1992 *units
= base
| mode
;
1995 int find_next_key(struct btrfs_path
*path
, struct btrfs_key
*key
)
1999 for (level
= 0; level
< BTRFS_MAX_LEVEL
; level
++) {
2000 if (!path
->nodes
[level
])
2002 if (path
->slots
[level
] + 1 >=
2003 btrfs_header_nritems(path
->nodes
[level
]))
2006 btrfs_item_key_to_cpu(path
->nodes
[level
], key
,
2007 path
->slots
[level
] + 1);
2009 btrfs_node_key_to_cpu(path
->nodes
[level
], key
,
2010 path
->slots
[level
] + 1);
2016 const char* btrfs_group_type_str(u64 flag
)
2018 u64 mask
= BTRFS_BLOCK_GROUP_TYPE_MASK
|
2019 BTRFS_SPACE_INFO_GLOBAL_RSV
;
2021 switch (flag
& mask
) {
2022 case BTRFS_BLOCK_GROUP_DATA
:
2024 case BTRFS_BLOCK_GROUP_SYSTEM
:
2026 case BTRFS_BLOCK_GROUP_METADATA
:
2028 case BTRFS_BLOCK_GROUP_DATA
|BTRFS_BLOCK_GROUP_METADATA
:
2029 return "Data+Metadata";
2030 case BTRFS_SPACE_INFO_GLOBAL_RSV
:
2031 return "GlobalReserve";
2037 const char* btrfs_group_profile_str(u64 flag
)
2039 switch (flag
& BTRFS_BLOCK_GROUP_PROFILE_MASK
) {
2042 case BTRFS_BLOCK_GROUP_RAID0
:
2044 case BTRFS_BLOCK_GROUP_RAID1
:
2046 case BTRFS_BLOCK_GROUP_RAID5
:
2048 case BTRFS_BLOCK_GROUP_RAID6
:
2050 case BTRFS_BLOCK_GROUP_DUP
:
2052 case BTRFS_BLOCK_GROUP_RAID10
:
2059 u64
disk_size(const char *path
)
2063 if (statfs(path
, &sfs
) < 0)
2066 return sfs
.f_bsize
* sfs
.f_blocks
;
2069 u64
get_partition_size(const char *dev
)
2072 int fd
= open(dev
, O_RDONLY
);
2076 if (ioctl(fd
, BLKGETSIZE64
, &result
) < 0) {
2086 * Check if the BTRFS_IOC_TREE_SEARCH_V2 ioctl is supported on a given
2087 * filesystem, opened at fd
2089 int btrfs_tree_search2_ioctl_supported(int fd
)
2091 struct btrfs_ioctl_search_args_v2
*args2
;
2092 struct btrfs_ioctl_search_key
*sk
;
2093 int args2_size
= 1024;
2094 char args2_buf
[args2_size
];
2097 args2
= (struct btrfs_ioctl_search_args_v2
*)args2_buf
;
2101 * Search for the extent tree item in the root tree.
2103 sk
->tree_id
= BTRFS_ROOT_TREE_OBJECTID
;
2104 sk
->min_objectid
= BTRFS_EXTENT_TREE_OBJECTID
;
2105 sk
->max_objectid
= BTRFS_EXTENT_TREE_OBJECTID
;
2106 sk
->min_type
= BTRFS_ROOT_ITEM_KEY
;
2107 sk
->max_type
= BTRFS_ROOT_ITEM_KEY
;
2109 sk
->max_offset
= (u64
)-1;
2110 sk
->min_transid
= 0;
2111 sk
->max_transid
= (u64
)-1;
2113 args2
->buf_size
= args2_size
- sizeof(struct btrfs_ioctl_search_args_v2
);
2114 ret
= ioctl(fd
, BTRFS_IOC_TREE_SEARCH_V2
, args2
);
2115 if (ret
== -EOPNOTSUPP
)
2122 int btrfs_check_nodesize(u32 nodesize
, u32 sectorsize
, u64 features
)
2124 if (nodesize
< sectorsize
) {
2125 error("illegal nodesize %u (smaller than %u)",
2126 nodesize
, sectorsize
);
2128 } else if (nodesize
> BTRFS_MAX_METADATA_BLOCKSIZE
) {
2129 error("illegal nodesize %u (larger than %u)",
2130 nodesize
, BTRFS_MAX_METADATA_BLOCKSIZE
);
2132 } else if (nodesize
& (sectorsize
- 1)) {
2133 error("illegal nodesize %u (not aligned to %u)",
2134 nodesize
, sectorsize
);
2136 } else if (features
& BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS
&&
2137 nodesize
!= sectorsize
) {
2138 error("illegal nodesize %u (not equal to %u for mixed block group)",
2139 nodesize
, sectorsize
);
2146 * Copy a path argument from SRC to DEST and check the SRC length if it's at
2147 * most PATH_MAX and fits into DEST. DESTLEN is supposed to be exact size of
2149 * The destination buffer is zero terminated.
2150 * Return < 0 for error, 0 otherwise.
2152 int arg_copy_path(char *dest
, const char *src
, int destlen
)
2154 size_t len
= strlen(src
);
2156 if (len
>= PATH_MAX
|| len
>= destlen
)
2157 return -ENAMETOOLONG
;
2159 __strncpy_null(dest
, src
, destlen
);
2164 unsigned int get_unit_mode_from_arg(int *argc
, char *argv
[], int df_mode
)
2166 unsigned int unit_mode
= UNITS_DEFAULT
;
2170 for (arg_i
= 0; arg_i
< *argc
; arg_i
++) {
2171 if (!strcmp(argv
[arg_i
], "--"))
2174 if (!strcmp(argv
[arg_i
], "--raw")) {
2175 unit_mode
= UNITS_RAW
;
2179 if (!strcmp(argv
[arg_i
], "--human-readable")) {
2180 unit_mode
= UNITS_HUMAN_BINARY
;
2185 if (!strcmp(argv
[arg_i
], "--iec")) {
2186 units_set_mode(&unit_mode
, UNITS_BINARY
);
2190 if (!strcmp(argv
[arg_i
], "--si")) {
2191 units_set_mode(&unit_mode
, UNITS_DECIMAL
);
2196 if (!strcmp(argv
[arg_i
], "--kbytes")) {
2197 units_set_base(&unit_mode
, UNITS_KBYTES
);
2201 if (!strcmp(argv
[arg_i
], "--mbytes")) {
2202 units_set_base(&unit_mode
, UNITS_MBYTES
);
2206 if (!strcmp(argv
[arg_i
], "--gbytes")) {
2207 units_set_base(&unit_mode
, UNITS_GBYTES
);
2211 if (!strcmp(argv
[arg_i
], "--tbytes")) {
2212 units_set_base(&unit_mode
, UNITS_TBYTES
);
2220 if (!strcmp(argv
[arg_i
], "-b")) {
2221 unit_mode
= UNITS_RAW
;
2225 if (!strcmp(argv
[arg_i
], "-h")) {
2226 unit_mode
= UNITS_HUMAN_BINARY
;
2230 if (!strcmp(argv
[arg_i
], "-H")) {
2231 unit_mode
= UNITS_HUMAN_DECIMAL
;
2235 if (!strcmp(argv
[arg_i
], "-k")) {
2236 units_set_base(&unit_mode
, UNITS_KBYTES
);
2240 if (!strcmp(argv
[arg_i
], "-m")) {
2241 units_set_base(&unit_mode
, UNITS_MBYTES
);
2245 if (!strcmp(argv
[arg_i
], "-g")) {
2246 units_set_base(&unit_mode
, UNITS_GBYTES
);
2250 if (!strcmp(argv
[arg_i
], "-t")) {
2251 units_set_base(&unit_mode
, UNITS_TBYTES
);
2257 for (arg_i
= 0, arg_end
= 0; arg_i
< *argc
; arg_i
++) {
2260 argv
[arg_end
] = argv
[arg_i
];
2269 u64
div_factor(u64 num
, int factor
)
2278 * Get the length of the string converted from a u64 number.
2280 * Result is equal to log10(num) + 1, but without the use of math library.
2282 int count_digits(u64 num
)
2295 int string_is_numerical(const char *str
)
2299 if (!(*str
>= '0' && *str
<= '9'))
2301 while (*str
>= '0' && *str
<= '9')
2308 int prefixcmp(const char *str
, const char *prefix
)
2310 for (; ; str
++, prefix
++)
2313 else if (*str
!= *prefix
)
2314 return (unsigned char)*prefix
- (unsigned char)*str
;
2317 /* Subvolume helper functions */
2319 * test if name is a correct subvolume name
2320 * this function return
2321 * 0-> name is not a correct subvolume name
2322 * 1-> name is a correct subvolume name
2324 int test_issubvolname(const char *name
)
2326 return name
[0] != '\0' && !strchr(name
, '/') &&
2327 strcmp(name
, ".") && strcmp(name
, "..");
2331 * Test if path is a subvolume
2333 * 0 - path exists but it is not a subvolume
2334 * 1 - path exists and it is a subvolume
2337 int test_issubvolume(const char *path
)
2343 res
= stat(path
, &st
);
2347 if (st
.st_ino
!= BTRFS_FIRST_FREE_OBJECTID
|| !S_ISDIR(st
.st_mode
))
2350 res
= statfs(path
, &stfs
);
2354 return (int)stfs
.f_type
== BTRFS_SUPER_MAGIC
;
2357 const char *subvol_strip_mountpoint(const char *mnt
, const char *full_path
)
2359 int len
= strlen(mnt
);
2363 if (mnt
[len
- 1] != '/')
2366 return full_path
+ len
;
2373 * 1: Error; and error info printed to the terminal. Fixme.
2374 * 2: If the fullpath is root tree instead of subvol tree
2376 int get_subvol_info(const char *fullpath
, struct root_info
*get_ri
)
2383 const char *svpath
= NULL
;
2384 DIR *dirstream1
= NULL
;
2385 DIR *dirstream2
= NULL
;
2387 ret
= test_issubvolume(fullpath
);
2391 error("not a subvolume: %s", fullpath
);
2395 ret
= find_mount_root(fullpath
, &mnt
);
2399 error("%s doesn't belong to btrfs mount point", fullpath
);
2403 svpath
= subvol_strip_mountpoint(mnt
, fullpath
);
2405 fd
= btrfs_open_dir(fullpath
, &dirstream1
, 1);
2409 ret
= btrfs_list_get_path_rootid(fd
, &sv_id
);
2413 mntfd
= btrfs_open_dir(mnt
, &dirstream2
, 1);
2417 memset(get_ri
, 0, sizeof(*get_ri
));
2418 get_ri
->root_id
= sv_id
;
2420 if (sv_id
== BTRFS_FS_TREE_OBJECTID
)
2421 ret
= btrfs_get_toplevel_subvol(mntfd
, get_ri
);
2423 ret
= btrfs_get_subvol(mntfd
, get_ri
);
2425 error("can't find '%s': %d", svpath
, ret
);
2428 close_file_or_dir(mntfd
, dirstream2
);
2429 close_file_or_dir(fd
, dirstream1
);
2435 /* Set the seed manually */
2436 void init_rand_seed(u64 seed
)
2440 /* only use the last 48 bits */
2441 for (i
= 0; i
< 3; i
++) {
2442 rand_seed
[i
] = (unsigned short)(seed
^ (unsigned short)(-1));
2445 rand_seed_initlized
= 1;
2448 static void __init_seed(void)
2454 if(rand_seed_initlized
)
2456 /* Use urandom as primary seed source. */
2457 fd
= open("/dev/urandom", O_RDONLY
);
2459 ret
= read(fd
, rand_seed
, sizeof(rand_seed
));
2461 if (ret
< sizeof(rand_seed
))
2465 /* Use time and pid as fallback seed */
2466 warning("failed to read /dev/urandom, use time and pid as random seed");
2467 gettimeofday(&tv
, 0);
2468 rand_seed
[0] = getpid() ^ (tv
.tv_sec
& 0xFFFF);
2469 rand_seed
[1] = getppid() ^ (tv
.tv_usec
& 0xFFFF);
2470 rand_seed
[2] = (tv
.tv_sec
^ tv
.tv_usec
) >> 16;
2472 rand_seed_initlized
= 1;
2479 * Don't use nrand48, its range is [0,2^31) The highest bit will alwasy
2480 * be 0. Use jrand48 to include the highest bit.
2482 return (u32
)jrand48(rand_seed
);
2485 /* Return random number in range [0, upper) */
2486 unsigned int rand_range(unsigned int upper
)
2490 * Use the full 48bits to mod, which would be more uniformly
2493 return (unsigned int)(jrand48(rand_seed
) % upper
);
2498 return (int)(rand_u32());
2513 return (u16
)(rand_u32());
2518 return (u8
)(rand_u32());
2521 void btrfs_config_init(void)