btrfs-progs: Refactor nodesize users in utils.c
[platform/upstream/btrfs-progs.git] / utils.c
1 /*
2  * Copyright (C) 2007 Oracle.  All rights reserved.
3  * Copyright (C) 2008 Morey Roof.  All rights reserved.
4  *
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.
8  *
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.
13  *
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.
18  */
19
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <sys/ioctl.h>
24 #include <sys/mount.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <uuid/uuid.h>
28 #include <fcntl.h>
29 #include <unistd.h>
30 #include <mntent.h>
31 #include <ctype.h>
32 #include <linux/loop.h>
33 #include <linux/major.h>
34 #include <linux/kdev_t.h>
35 #include <limits.h>
36 #include <blkid/blkid.h>
37 #include <sys/vfs.h>
38 #include <sys/statfs.h>
39 #include <linux/magic.h>
40 #include <getopt.h>
41
42 #include "kerncompat.h"
43 #include "radix-tree.h"
44 #include "ctree.h"
45 #include "disk-io.h"
46 #include "transaction.h"
47 #include "crc32c.h"
48 #include "utils.h"
49 #include "volumes.h"
50 #include "ioctl.h"
51 #include "commands.h"
52 #include "mkfs/common.h"
53
54 #ifndef BLKDISCARD
55 #define BLKDISCARD      _IO(0x12,119)
56 #endif
57
58 static int btrfs_scan_done = 0;
59
60 static int rand_seed_initlized = 0;
61 static unsigned short rand_seed[3];
62
63 struct btrfs_config bconf;
64
65 /*
66  * Discard the given range in one go
67  */
68 static int discard_range(int fd, u64 start, u64 len)
69 {
70         u64 range[2] = { start, len };
71
72         if (ioctl(fd, BLKDISCARD, &range) < 0)
73                 return errno;
74         return 0;
75 }
76
77 /*
78  * Discard blocks in the given range in 1G chunks, the process is interruptible
79  */
80 static int discard_blocks(int fd, u64 start, u64 len)
81 {
82         while (len > 0) {
83                 /* 1G granularity */
84                 u64 chunk_size = min_t(u64, len, SZ_1G);
85                 int ret;
86
87                 ret = discard_range(fd, start, chunk_size);
88                 if (ret)
89                         return ret;
90                 len -= chunk_size;
91                 start += chunk_size;
92         }
93
94         return 0;
95 }
96
97 int test_uuid_unique(char *fs_uuid)
98 {
99         int unique = 1;
100         blkid_dev_iterate iter = NULL;
101         blkid_dev dev = NULL;
102         blkid_cache cache = NULL;
103
104         if (blkid_get_cache(&cache, NULL) < 0) {
105                 printf("ERROR: lblkid cache get failed\n");
106                 return 1;
107         }
108         blkid_probe_all(cache);
109         iter = blkid_dev_iterate_begin(cache);
110         blkid_dev_set_search(iter, "UUID", fs_uuid);
111
112         while (blkid_dev_next(iter, &dev) == 0) {
113                 dev = blkid_verify(cache, dev);
114                 if (dev) {
115                         unique = 0;
116                         break;
117                 }
118         }
119
120         blkid_dev_iterate_end(iter);
121         blkid_put_cache(cache);
122
123         return unique;
124 }
125
126 u64 btrfs_device_size(int fd, struct stat *st)
127 {
128         u64 size;
129         if (S_ISREG(st->st_mode)) {
130                 return st->st_size;
131         }
132         if (!S_ISBLK(st->st_mode)) {
133                 return 0;
134         }
135         if (ioctl(fd, BLKGETSIZE64, &size) >= 0) {
136                 return size;
137         }
138         return 0;
139 }
140
141 static int zero_blocks(int fd, off_t start, size_t len)
142 {
143         char *buf = malloc(len);
144         int ret = 0;
145         ssize_t written;
146
147         if (!buf)
148                 return -ENOMEM;
149         memset(buf, 0, len);
150         written = pwrite(fd, buf, len, start);
151         if (written != len)
152                 ret = -EIO;
153         free(buf);
154         return ret;
155 }
156
157 #define ZERO_DEV_BYTES SZ_2M
158
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)
161 {
162         off_t end = max(start, start + len);
163
164 #ifdef __sparc__
165         /* and don't overwrite the disk labels on sparc */
166         start = max(start, 1024);
167         end = max(end, 1024);
168 #endif
169
170         start = min_t(u64, start, dev_size);
171         end = min_t(u64, end, dev_size);
172
173         return zero_blocks(fd, start, end - start);
174 }
175
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,
179                       u32 sectorsize)
180 {
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;
185         char *buf = NULL;
186         u64 fs_total_bytes;
187         u64 num_devs;
188         int ret;
189
190         device_total_bytes = (device_total_bytes / sectorsize) * sectorsize;
191
192         device = calloc(1, sizeof(*device));
193         if (!device) {
194                 ret = -ENOMEM;
195                 goto out;
196         }
197         buf = calloc(1, sectorsize);
198         if (!buf) {
199                 ret = -ENOMEM;
200                 goto out;
201         }
202
203         disk_super = (struct btrfs_super_block *)buf;
204         dev_item = &disk_super->dev_item;
205
206         uuid_generate(device->uuid);
207         device->devid = 0;
208         device->type = 0;
209         device->io_width = io_width;
210         device->io_align = io_align;
211         device->sector_size = sectorsize;
212         device->fd = fd;
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);
219         if (!device->name) {
220                 ret = -ENOMEM;
221                 goto out;
222         }
223
224         INIT_LIST_HEAD(&device->dev_list);
225         ret = btrfs_add_device(trans, root, device);
226         if (ret)
227                 goto out;
228
229         fs_total_bytes = btrfs_super_total_bytes(super) + device_total_bytes;
230         btrfs_set_super_total_bytes(super, fs_total_bytes);
231
232         num_devs = btrfs_super_num_devices(super) + 1;
233         btrfs_set_super_num_devices(super, num_devs);
234
235         memcpy(disk_super, super, sizeof(*disk_super));
236
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);
246
247         ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
248         BUG_ON(ret != sectorsize);
249
250         free(buf);
251         list_add(&device->dev_list, &root->fs_info->fs_devices->devices);
252         device->fs_devices = root->fs_info->fs_devices;
253         return 0;
254
255 out:
256         free(device);
257         free(buf);
258         return ret;
259 }
260
261 static int btrfs_wipe_existing_sb(int fd)
262 {
263         const char *off = NULL;
264         size_t len = 0;
265         loff_t offset;
266         char buf[BUFSIZ];
267         int ret = 0;
268         blkid_probe pr = NULL;
269
270         pr = blkid_new_probe();
271         if (!pr)
272                 return -1;
273
274         if (blkid_probe_set_device(pr, fd, 0, 0)) {
275                 ret = -1;
276                 goto out;
277         }
278
279         ret = blkid_probe_lookup_value(pr, "SBMAGIC_OFFSET", &off, NULL);
280         if (!ret)
281                 ret = blkid_probe_lookup_value(pr, "SBMAGIC", NULL, &len);
282
283         if (ret || len == 0 || off == NULL) {
284                 /*
285                  * If lookup fails, the probe did not find any values, eg. for
286                  * a file image or a loop device. Soft error.
287                  */
288                 ret = 1;
289                 goto out;
290         }
291
292         offset = strtoll(off, NULL, 10);
293         if (len > sizeof(buf))
294                 len = sizeof(buf);
295
296         memset(buf, 0, len);
297         ret = pwrite(fd, buf, len, offset);
298         if (ret < 0) {
299                 error("cannot wipe existing superblock: %s", strerror(errno));
300                 ret = -1;
301         } else if (ret != len) {
302                 error("cannot wipe existing superblock: wrote %d of %zd", ret, len);
303                 ret = -1;
304         }
305         fsync(fd);
306
307 out:
308         blkid_free_probe(pr);
309         return ret;
310 }
311
312 int btrfs_prepare_device(int fd, const char *file, u64 *block_count_ret,
313                 u64 max_block_count, unsigned opflags)
314 {
315         u64 block_count;
316         struct stat st;
317         int i, ret;
318
319         ret = fstat(fd, &st);
320         if (ret < 0) {
321                 error("unable to stat %s: %s", file, strerror(errno));
322                 return 1;
323         }
324
325         block_count = btrfs_device_size(fd, &st);
326         if (block_count == 0) {
327                 error("unable to determine size of %s", file);
328                 return 1;
329         }
330         if (max_block_count)
331                 block_count = min(block_count, max_block_count);
332
333         if (opflags & PREP_DEVICE_DISCARD) {
334                 /*
335                  * We intentionally ignore errors from the discard ioctl.  It
336                  * is not necessary for the mkfs functionality but just an
337                  * optimization.
338                  */
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);
344                 }
345         }
346
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);
354
355         if (ret < 0) {
356                 error("failed to zero device '%s': %s", file, strerror(-ret));
357                 return 1;
358         }
359
360         ret = btrfs_wipe_existing_sb(fd);
361         if (ret < 0) {
362                 error("cannot wipe superblocks on %s", file);
363                 return 1;
364         }
365
366         *block_count_ret = block_count;
367         return 0;
368 }
369
370 int btrfs_make_root_dir(struct btrfs_trans_handle *trans,
371                         struct btrfs_root *root, u64 objectid)
372 {
373         int ret;
374         struct btrfs_inode_item inode_item;
375         time_t now = time(NULL);
376
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->fs_info->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);
391
392         if (root->fs_info->tree_root == root)
393                 btrfs_set_super_root_dir(root->fs_info->super_copy, objectid);
394
395         ret = btrfs_insert_inode(trans, root, objectid, &inode_item);
396         if (ret)
397                 goto error;
398
399         ret = btrfs_insert_inode_ref(trans, root, "..", 2, objectid, objectid, 0);
400         if (ret)
401                 goto error;
402
403         btrfs_set_root_dirid(&root->root_item, objectid);
404         ret = 0;
405 error:
406         return ret;
407 }
408
409 /*
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
413  */
414 int is_block_device(const char *path)
415 {
416         struct stat statbuf;
417
418         if (stat(path, &statbuf) < 0)
419                 return -errno;
420
421         return !!S_ISBLK(statbuf.st_mode);
422 }
423
424 /*
425  * check if given path is a mount point
426  * return 1 if yes. 0 if no. -1 for error
427  */
428 int is_mount_point(const char *path)
429 {
430         FILE *f;
431         struct mntent *mnt;
432         int ret = 0;
433
434         f = setmntent("/proc/self/mounts", "r");
435         if (f == NULL)
436                 return -1;
437
438         while ((mnt = getmntent(f)) != NULL) {
439                 if (strcmp(mnt->mnt_dir, path))
440                         continue;
441                 ret = 1;
442                 break;
443         }
444         endmntent(f);
445         return ret;
446 }
447
448 static int is_reg_file(const char *path)
449 {
450         struct stat statbuf;
451
452         if (stat(path, &statbuf) < 0)
453                 return -errno;
454         return S_ISREG(statbuf.st_mode);
455 }
456
457 /*
458  * This function checks if the given input parameter is
459  * an uuid or a path
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
466  */
467 int check_arg_type(const char *input)
468 {
469         uuid_t uuid;
470         char path[PATH_MAX];
471
472         if (!input)
473                 return -EINVAL;
474
475         if (realpath(input, path)) {
476                 if (is_block_device(path) == 1)
477                         return BTRFS_ARG_BLKDEV;
478
479                 if (is_mount_point(path) == 1)
480                         return BTRFS_ARG_MNTPOINT;
481
482                 if (is_reg_file(path))
483                         return BTRFS_ARG_REG;
484
485                 return BTRFS_ARG_UNKNOWN;
486         }
487
488         if (strlen(input) == (BTRFS_UUID_UNPARSED_SIZE - 1) &&
489                 !uuid_parse(input, uuid))
490                 return BTRFS_ARG_UUID;
491
492         return BTRFS_ARG_UNKNOWN;
493 }
494
495 /*
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.
500  */
501 int get_btrfs_mount(const char *dev, char *mp, size_t mp_size)
502 {
503         int ret;
504         int fd = -1;
505
506         ret = is_block_device(dev);
507         if (ret <= 0) {
508                 if (!ret) {
509                         error("not a block device: %s", dev);
510                         ret = -EINVAL;
511                 } else {
512                         error("cannot check %s: %s", dev, strerror(-ret));
513                 }
514                 goto out;
515         }
516
517         fd = open(dev, O_RDONLY);
518         if (fd < 0) {
519                 ret = -errno;
520                 error("cannot open %s: %s", dev, strerror(errno));
521                 goto out;
522         }
523
524         ret = check_mounted_where(fd, dev, mp, mp_size, NULL);
525         if (!ret) {
526                 ret = -EINVAL;
527         } else { /* mounted, all good */
528                 ret = 0;
529         }
530 out:
531         if (fd != -1)
532                 close(fd);
533         return ret;
534 }
535
536 /*
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.
540  *
541  * On error, return -1, errno should be set.
542  */
543 int open_path_or_dev_mnt(const char *path, DIR **dirstream, int verbose)
544 {
545         char mp[PATH_MAX];
546         int ret;
547
548         if (is_block_device(path)) {
549                 ret = get_btrfs_mount(path, mp, sizeof(mp));
550                 if (ret < 0) {
551                         /* not a mounted btrfs dev */
552                         error_on(verbose, "'%s' is not a mounted btrfs device",
553                                  path);
554                         errno = EINVAL;
555                         return -1;
556                 }
557                 ret = open_file_or_dir(mp, dirstream);
558                 error_on(verbose && ret < 0, "can't access '%s': %s",
559                          path, strerror(errno));
560         } else {
561                 ret = btrfs_open_dir(path, dirstream, 1);
562         }
563
564         return ret;
565 }
566
567 /*
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
571  */
572 int btrfs_open_dir(const char *path, DIR **dirstream, int verbose)
573 {
574         struct statfs stfs;
575         struct stat st;
576         int ret;
577
578         if (statfs(path, &stfs) != 0) {
579                 error_on(verbose, "cannot access '%s': %s", path,
580                                 strerror(errno));
581                 return -1;
582         }
583
584         if (stfs.f_type != BTRFS_SUPER_MAGIC) {
585                 error_on(verbose, "not a btrfs filesystem: %s", path);
586                 return -2;
587         }
588
589         if (stat(path, &st) != 0) {
590                 error_on(verbose, "cannot access '%s': %s", path,
591                                 strerror(errno));
592                 return -1;
593         }
594
595         if (!S_ISDIR(st.st_mode)) {
596                 error_on(verbose, "not a directory: %s", path);
597                 return -3;
598         }
599
600         ret = open_file_or_dir(path, dirstream);
601         if (ret < 0) {
602                 error_on(verbose, "cannot access '%s': %s", path,
603                                 strerror(errno));
604         }
605
606         return ret;
607 }
608
609 /* checks if a device is a loop device */
610 static int is_loop_device (const char* device) {
611         struct stat statbuf;
612
613         if(stat(device, &statbuf) < 0)
614                 return -errno;
615
616         return (S_ISBLK(statbuf.st_mode) &&
617                 MAJOR(statbuf.st_rdev) == LOOP_MAJOR);
618 }
619
620 /*
621  * Takes a loop device path (e.g. /dev/loop0) and returns
622  * the associated file (e.g. /images/my_btrfs.img) using
623  * loopdev API
624  */
625 static int resolve_loop_device_with_loopdev(const char* loop_dev, char* loop_file)
626 {
627         int fd;
628         int ret;
629         struct loop_info64 lo64;
630
631         fd = open(loop_dev, O_RDONLY | O_NONBLOCK);
632         if (fd < 0)
633                 return -errno;
634         ret = ioctl(fd, LOOP_GET_STATUS64, &lo64);
635         if (ret < 0) {
636                 ret = -errno;
637                 goto out;
638         }
639
640         memcpy(loop_file, lo64.lo_file_name, sizeof(lo64.lo_file_name));
641         loop_file[sizeof(lo64.lo_file_name)] = 0;
642
643 out:
644         close(fd);
645
646         return ret;
647 }
648
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,
652                 int max_len)
653 {
654         int ret;
655         FILE *f;
656         char fmt[20];
657         char p[PATH_MAX];
658         char real_loop_dev[PATH_MAX];
659
660         if (!realpath(loop_dev, real_loop_dev))
661                 return -errno;
662         snprintf(p, PATH_MAX, "/sys/block/%s/loop/backing_file", strrchr(real_loop_dev, '/'));
663         if (!(f = fopen(p, "r"))) {
664                 if (errno == ENOENT)
665                         /*
666                          * It's possibly a partitioned loop device, which is
667                          * resolvable with loopdev API.
668                          */
669                         return resolve_loop_device_with_loopdev(loop_dev, loop_file);
670                 return -errno;
671         }
672
673         snprintf(fmt, 20, "%%%i[^\n]", max_len-1);
674         ret = fscanf(f, fmt, loop_file);
675         fclose(f);
676         if (ret == EOF)
677                 return -errno;
678
679         return 0;
680 }
681
682 /*
683  * Checks whether a and b are identical or device
684  * files associated with the same block device
685  */
686 static int is_same_blk_file(const char* a, const char* b)
687 {
688         struct stat st_buf_a, st_buf_b;
689         char real_a[PATH_MAX];
690         char real_b[PATH_MAX];
691
692         if (!realpath(a, real_a))
693                 strncpy_null(real_a, a);
694
695         if (!realpath(b, real_b))
696                 strncpy_null(real_b, b);
697
698         /* Identical path? */
699         if (strcmp(real_a, real_b) == 0)
700                 return 1;
701
702         if (stat(a, &st_buf_a) < 0 || stat(b, &st_buf_b) < 0) {
703                 if (errno == ENOENT)
704                         return 0;
705                 return -errno;
706         }
707
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) {
711                 return 1;
712         }
713
714         /* Hardlink? */
715         if (st_buf_a.st_dev == st_buf_b.st_dev &&
716             st_buf_a.st_ino == st_buf_b.st_ino) {
717                 return 1;
718         }
719
720         return 0;
721 }
722
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
726  * file.
727  */
728 static int is_same_loop_file(const char* a, const char* b)
729 {
730         char res_a[PATH_MAX];
731         char res_b[PATH_MAX];
732         const char* final_a = NULL;
733         const char* final_b = NULL;
734         int ret;
735
736         /* Resolve a if it is a loop device */
737         if((ret = is_loop_device(a)) < 0) {
738                 if (ret == -ENOENT)
739                         return 0;
740                 return ret;
741         } else if (ret) {
742                 ret = resolve_loop_device(a, res_a, sizeof(res_a));
743                 if (ret < 0) {
744                         if (errno != EPERM)
745                                 return ret;
746                 } else {
747                         final_a = res_a;
748                 }
749         } else {
750                 final_a = a;
751         }
752
753         /* Resolve b if it is a loop device */
754         if ((ret = is_loop_device(b)) < 0) {
755                 if (ret == -ENOENT)
756                         return 0;
757                 return ret;
758         } else if (ret) {
759                 ret = resolve_loop_device(b, res_b, sizeof(res_b));
760                 if (ret < 0) {
761                         if (errno != EPERM)
762                                 return ret;
763                 } else {
764                         final_b = res_b;
765                 }
766         } else {
767                 final_b = b;
768         }
769
770         return is_same_blk_file(final_a, final_b);
771 }
772
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)
775 {
776         struct stat st_buf;
777
778         if(stat(filename, &st_buf) < 0) {
779                 if(errno == ENOENT)
780                         return 0;
781                 else
782                         return -errno;
783         }
784
785         return (S_ISBLK(st_buf.st_mode) || S_ISREG(st_buf.st_mode));
786 }
787
788 /* Checks if a file is used (directly or indirectly via a loop device)
789  * by a device in fs_devices
790  */
791 static int blk_file_in_dev_list(struct btrfs_fs_devices* fs_devices,
792                 const char* file)
793 {
794         int ret;
795         struct list_head *head;
796         struct list_head *cur;
797         struct btrfs_device *device;
798
799         head = &fs_devices->devices;
800         list_for_each(cur, head) {
801                 device = list_entry(cur, struct btrfs_device, dev_list);
802
803                 if((ret = is_same_loop_file(device->name, file)))
804                         return ret;
805         }
806
807         return 0;
808 }
809
810 /*
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.
814  */
815 char *canonicalize_dm_name(const char *ptname)
816 {
817         FILE    *f;
818         size_t  sz;
819         char    path[PATH_MAX], name[PATH_MAX], *res = NULL;
820
821         if (!ptname || !*ptname)
822                 return NULL;
823
824         snprintf(path, sizeof(path), "/sys/block/%s/dm/name", ptname);
825         if (!(f = fopen(path, "r")))
826                 return NULL;
827
828         /* read <name>\n from sysfs */
829         if (fgets(name, sizeof(name), f) && (sz = strlen(name)) > 1) {
830                 name[sz - 1] = '\0';
831                 snprintf(path, sizeof(path), "/dev/mapper/%s", name);
832
833                 if (access(path, F_OK) == 0)
834                         res = strdup(path);
835         }
836         fclose(f);
837         return res;
838 }
839
840 /*
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.
845  */
846 char *canonicalize_path(const char *path)
847 {
848         char *canonical, *p;
849
850         if (!path || !*path)
851                 return NULL;
852
853         canonical = realpath(path, NULL);
854         if (!canonical)
855                 return strdup(path);
856         p = strrchr(canonical, '/');
857         if (p && strncmp(p, "/dm-", 4) == 0 && isdigit(*(p + 4))) {
858                 char *dm = canonicalize_dm_name(p + 1);
859
860                 if (dm) {
861                         free(canonical);
862                         return dm;
863                 }
864         }
865         return canonical;
866 }
867
868 /*
869  * returns 1 if the device was mounted, < 0 on error or 0 if everything
870  * is safe to continue.
871  */
872 int check_mounted(const char* file)
873 {
874         int fd;
875         int ret;
876
877         fd = open(file, O_RDONLY);
878         if (fd < 0) {
879                 error("mount check: cannot open %s: %s", file,
880                                 strerror(errno));
881                 return -errno;
882         }
883
884         ret =  check_mounted_where(fd, file, NULL, 0, NULL);
885         close(fd);
886
887         return ret;
888 }
889
890 int check_mounted_where(int fd, const char *file, char *where, int size,
891                         struct btrfs_fs_devices **fs_dev_ret)
892 {
893         int ret;
894         u64 total_devs = 1;
895         int is_btrfs;
896         struct btrfs_fs_devices *fs_devices_mnt = NULL;
897         FILE *f;
898         struct mntent *mnt;
899
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);
904
905         /* scan other devices */
906         if (is_btrfs && total_devs > 1) {
907                 ret = btrfs_scan_devices();
908                 if (ret)
909                         return ret;
910         }
911
912         /* iterate over the list of currently mounted filesystems */
913         if ((f = setmntent ("/proc/self/mounts", "r")) == NULL)
914                 return -errno;
915
916         while ((mnt = getmntent (f)) != NULL) {
917                 if(is_btrfs) {
918                         if(strcmp(mnt->mnt_type, "btrfs") != 0)
919                                 continue;
920
921                         ret = blk_file_in_dev_list(fs_devices_mnt, mnt->mnt_fsname);
922                 } else {
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;
927                         else if(!ret)
928                                 continue;
929
930                         ret = is_same_loop_file(file, mnt->mnt_fsname);
931                 }
932
933                 if(ret < 0)
934                         goto out_mntloop_err;
935                 else if(ret)
936                         break;
937         }
938
939         /* Did we find an entry in mnt table? */
940         if (mnt && size && where) {
941                 strncpy(where, mnt->mnt_dir, size);
942                 where[size-1] = 0;
943         }
944         if (fs_dev_ret)
945                 *fs_dev_ret = fs_devices_mnt;
946
947         ret = (mnt != NULL);
948
949 out_mntloop_err:
950         endmntent (f);
951
952         return ret;
953 }
954
955 struct pending_dir {
956         struct list_head list;
957         char name[PATH_MAX];
958 };
959
960 int btrfs_register_one_device(const char *fname)
961 {
962         struct btrfs_ioctl_vol_args args;
963         int fd;
964         int ret;
965
966         fd = open("/dev/btrfs-control", O_RDWR);
967         if (fd < 0) {
968                 warning(
969         "failed to open /dev/btrfs-control, skipping device registration: %s",
970                         strerror(errno));
971                 return -errno;
972         }
973         memset(&args, 0, sizeof(args));
974         strncpy_null(args.name, fname);
975         ret = ioctl(fd, BTRFS_IOC_SCAN_DEV, &args);
976         if (ret < 0) {
977                 error("device scan failed on '%s': %s", fname,
978                                 strerror(errno));
979                 ret = -errno;
980         }
981         close(fd);
982         return ret;
983 }
984
985 /*
986  * Register all devices in the fs_uuid list created in the user
987  * space. Ensure btrfs_scan_devices() is called before this func.
988  */
989 int btrfs_register_all_devices(void)
990 {
991         int err = 0;
992         int ret = 0;
993         struct btrfs_fs_devices *fs_devices;
994         struct btrfs_device *device;
995         struct list_head *all_uuids;
996
997         all_uuids = btrfs_scanned_uuids();
998
999         list_for_each_entry(fs_devices, all_uuids, list) {
1000                 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1001                         if (*device->name)
1002                                 err = btrfs_register_one_device(device->name);
1003
1004                         if (err)
1005                                 ret++;
1006                 }
1007         }
1008
1009         return ret;
1010 }
1011
1012 int btrfs_device_already_in_root(struct btrfs_root *root, int fd,
1013                                  int super_offset)
1014 {
1015         struct btrfs_super_block *disk_super;
1016         char *buf;
1017         int ret = 0;
1018
1019         buf = malloc(BTRFS_SUPER_INFO_SIZE);
1020         if (!buf) {
1021                 ret = -ENOMEM;
1022                 goto out;
1023         }
1024         ret = pread(fd, buf, BTRFS_SUPER_INFO_SIZE, super_offset);
1025         if (ret != BTRFS_SUPER_INFO_SIZE)
1026                 goto brelse;
1027
1028         ret = 0;
1029         disk_super = (struct btrfs_super_block *)buf;
1030         /*
1031          * Accept devices from the same filesystem, allow partially created
1032          * structures.
1033          */
1034         if (btrfs_super_magic(disk_super) != BTRFS_MAGIC &&
1035                         btrfs_super_magic(disk_super) != BTRFS_MAGIC_PARTIAL)
1036                 goto brelse;
1037
1038         if (!memcmp(disk_super->fsid, root->fs_info->super_copy->fsid,
1039                     BTRFS_FSID_SIZE))
1040                 ret = 1;
1041 brelse:
1042         free(buf);
1043 out:
1044         return ret;
1045 }
1046
1047 /*
1048  * Note: this function uses a static per-thread buffer. Do not call this
1049  * function more than 10 times within one argument list!
1050  */
1051 const char *pretty_size_mode(u64 size, unsigned mode)
1052 {
1053         static __thread int ps_index = 0;
1054         static __thread char ps_array[10][32];
1055         char *ret;
1056
1057         ret = ps_array[ps_index];
1058         ps_index++;
1059         ps_index %= 10;
1060         (void)pretty_size_snprintf(size, ret, 32, mode);
1061
1062         return ret;
1063 }
1064
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"};
1069
1070 int pretty_size_snprintf(u64 size, char *str, size_t str_size, unsigned unit_mode)
1071 {
1072         int num_divs;
1073         float fraction;
1074         u64 base = 0;
1075         int mult = 0;
1076         const char** suffix = NULL;
1077         u64 last_size;
1078         int negative;
1079
1080         if (str_size == 0)
1081                 return 0;
1082
1083         negative = !!(unit_mode & UNITS_NEGATIVE);
1084         unit_mode &= ~UNITS_NEGATIVE;
1085
1086         if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_RAW) {
1087                 if (negative)
1088                         snprintf(str, str_size, "%lld", size);
1089                 else
1090                         snprintf(str, str_size, "%llu", size);
1091                 return 0;
1092         }
1093
1094         if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_BINARY) {
1095                 base = 1024;
1096                 mult = 1024;
1097                 suffix = unit_suffix_binary;
1098         } else if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_DECIMAL) {
1099                 base = 1000;
1100                 mult = 1000;
1101                 suffix = unit_suffix_decimal;
1102         }
1103
1104         /* Unknown mode */
1105         if (!base) {
1106                 fprintf(stderr, "INTERNAL ERROR: unknown unit base, mode %d\n",
1107                                 unit_mode);
1108                 assert(0);
1109                 return -1;
1110         }
1111
1112         num_divs = 0;
1113         last_size = size;
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++;
1119                            break;
1120         case UNITS_BYTES:
1121                            base = 1;
1122                            num_divs = 0;
1123                            break;
1124         default:
1125                 if (negative) {
1126                         s64 ssize = (s64)size;
1127                         s64 last_ssize = ssize;
1128
1129                         while ((ssize < 0 ? -ssize : ssize) >= mult) {
1130                                 last_ssize = ssize;
1131                                 ssize /= mult;
1132                                 num_divs++;
1133                         }
1134                         last_size = (u64)last_ssize;
1135                 } else {
1136                         while (size >= mult) {
1137                                 last_size = size;
1138                                 size /= mult;
1139                                 num_divs++;
1140                         }
1141                 }
1142                 /*
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
1146                  */
1147                 if (num_divs == 0)
1148                         base = 1;
1149         }
1150
1151         if (num_divs >= ARRAY_SIZE(unit_suffix_binary)) {
1152                 str[0] = '\0';
1153                 printf("INTERNAL ERROR: unsupported unit suffix, index %d\n",
1154                                 num_divs);
1155                 assert(0);
1156                 return -1;
1157         }
1158
1159         if (negative) {
1160                 fraction = (float)(s64)last_size / base;
1161         } else {
1162                 fraction = (float)last_size / base;
1163         }
1164
1165         return snprintf(str, str_size, "%.2f%s", fraction, suffix[num_divs]);
1166 }
1167
1168 /*
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)
1173  *
1174  * Like strncpy, but ensures destination is null-terminated.
1175  *
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.
1179  */
1180 char *__strncpy_null(char *dest, const char *src, size_t n)
1181 {
1182         strncpy(dest, src, n);
1183         if (n > 0)
1184                 dest[n - 1] = '\0';
1185         return dest;
1186 }
1187
1188 /*
1189  * Checks to make sure that the label matches our requirements.
1190  * Returns:
1191        0    if everything is safe and usable
1192       -1    if the label is too long
1193  */
1194 static int check_label(const char *input)
1195 {
1196        int len = strlen(input);
1197
1198        if (len > BTRFS_LABEL_SIZE - 1) {
1199                 error("label %s is too long (max %d)", input,
1200                                 BTRFS_LABEL_SIZE - 1);
1201                return -1;
1202        }
1203
1204        return 0;
1205 }
1206
1207 static int set_label_unmounted(const char *dev, const char *label)
1208 {
1209         struct btrfs_trans_handle *trans;
1210         struct btrfs_root *root;
1211         int ret;
1212
1213         ret = check_mounted(dev);
1214         if (ret < 0) {
1215                error("checking mount status of %s failed: %d", dev, ret);
1216                return -1;
1217         }
1218         if (ret > 0) {
1219                 error("device %s is mounted, use mount point", dev);
1220                 return -1;
1221         }
1222
1223         /* Open the super_block at the default location
1224          * and as read-write.
1225          */
1226         root = open_ctree(dev, 0, OPEN_CTREE_WRITES);
1227         if (!root) /* errors are printed by open_ctree() */
1228                 return -1;
1229
1230         trans = btrfs_start_transaction(root, 1);
1231         __strncpy_null(root->fs_info->super_copy->label, label, BTRFS_LABEL_SIZE - 1);
1232
1233         btrfs_commit_transaction(trans, root);
1234
1235         /* Now we close it since we are done. */
1236         close_ctree(root);
1237         return 0;
1238 }
1239
1240 static int set_label_mounted(const char *mount_path, const char *labelp)
1241 {
1242         int fd;
1243         char label[BTRFS_LABEL_SIZE];
1244
1245         fd = open(mount_path, O_RDONLY | O_NOATIME);
1246         if (fd < 0) {
1247                 error("unable to access %s: %s", mount_path, strerror(errno));
1248                 return -1;
1249         }
1250
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,
1255                                 strerror(errno));
1256                 close(fd);
1257                 return -1;
1258         }
1259
1260         close(fd);
1261         return 0;
1262 }
1263
1264 int get_label_unmounted(const char *dev, char *label)
1265 {
1266         struct btrfs_root *root;
1267         int ret;
1268
1269         ret = check_mounted(dev);
1270         if (ret < 0) {
1271                error("checking mount status of %s failed: %d", dev, ret);
1272                return -1;
1273         }
1274
1275         /* Open the super_block at the default location
1276          * and as read-only.
1277          */
1278         root = open_ctree(dev, 0, 0);
1279         if(!root)
1280                 return -1;
1281
1282         __strncpy_null(label, root->fs_info->super_copy->label,
1283                         BTRFS_LABEL_SIZE - 1);
1284
1285         /* Now we close it since we are done. */
1286         close_ctree(root);
1287         return 0;
1288 }
1289
1290 /*
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.
1294  */
1295 int get_label_mounted(const char *mount_path, char *labelp)
1296 {
1297         char label[BTRFS_LABEL_SIZE];
1298         int fd;
1299         int ret;
1300
1301         fd = open(mount_path, O_RDONLY | O_NOATIME);
1302         if (fd < 0) {
1303                 error("unable to access %s: %s", mount_path, strerror(errno));
1304                 return -1;
1305         }
1306
1307         memset(label, '\0', sizeof(label));
1308         ret = ioctl(fd, BTRFS_IOC_GET_FSLABEL, label);
1309         if (ret < 0) {
1310                 if (errno != ENOTTY)
1311                         error("unable to get label of %s: %s", mount_path,
1312                                         strerror(errno));
1313                 ret = -errno;
1314                 close(fd);
1315                 return ret;
1316         }
1317
1318         __strncpy_null(labelp, label, BTRFS_LABEL_SIZE - 1);
1319         close(fd);
1320         return 0;
1321 }
1322
1323 int get_label(const char *btrfs_dev, char *label)
1324 {
1325         int ret;
1326
1327         ret = is_existing_blk_or_reg_file(btrfs_dev);
1328         if (!ret)
1329                 ret = get_label_mounted(btrfs_dev, label);
1330         else if (ret > 0)
1331                 ret = get_label_unmounted(btrfs_dev, label);
1332
1333         return ret;
1334 }
1335
1336 int set_label(const char *btrfs_dev, const char *label)
1337 {
1338         int ret;
1339
1340         if (check_label(label))
1341                 return -1;
1342
1343         ret = is_existing_blk_or_reg_file(btrfs_dev);
1344         if (!ret)
1345                 ret = set_label_mounted(btrfs_dev, label);
1346         else if (ret > 0)
1347                 ret = set_label_unmounted(btrfs_dev, label);
1348
1349         return ret;
1350 }
1351
1352 /*
1353  * A not-so-good version fls64. No fascinating optimization since
1354  * no one except parse_size use it
1355  */
1356 static int fls64(u64 x)
1357 {
1358         int i;
1359
1360         for (i = 0; i <64; i++)
1361                 if (x << i & (1ULL << 63))
1362                         return 64 - i;
1363         return 64 - i;
1364 }
1365
1366 u64 parse_size(char *s)
1367 {
1368         char c;
1369         char *endptr;
1370         u64 mult = 1;
1371         u64 ret;
1372
1373         if (!s) {
1374                 error("size value is empty");
1375                 exit(1);
1376         }
1377         if (s[0] == '-') {
1378                 error("size value '%s' is less equal than 0", s);
1379                 exit(1);
1380         }
1381         ret = strtoull(s, &endptr, 10);
1382         if (endptr == s) {
1383                 error("size value '%s' is invalid", s);
1384                 exit(1);
1385         }
1386         if (endptr[0] && endptr[1]) {
1387                 error("illegal suffix contains character '%c' in wrong position",
1388                         endptr[1]);
1389                 exit(1);
1390         }
1391         /*
1392          * strtoll returns LLONG_MAX when overflow, if this happens,
1393          * need to call strtoull to get the real size
1394          */
1395         if (errno == ERANGE && ret == ULLONG_MAX) {
1396                 error("size value '%s' is too large for u64", s);
1397                 exit(1);
1398         }
1399         if (endptr[0]) {
1400                 c = tolower(endptr[0]);
1401                 switch (c) {
1402                 case 'e':
1403                         mult *= 1024;
1404                         /* fallthrough */
1405                 case 'p':
1406                         mult *= 1024;
1407                         /* fallthrough */
1408                 case 't':
1409                         mult *= 1024;
1410                         /* fallthrough */
1411                 case 'g':
1412                         mult *= 1024;
1413                         /* fallthrough */
1414                 case 'm':
1415                         mult *= 1024;
1416                         /* fallthrough */
1417                 case 'k':
1418                         mult *= 1024;
1419                         /* fallthrough */
1420                 case 'b':
1421                         break;
1422                 default:
1423                         error("unknown size descriptor '%c'", c);
1424                         exit(1);
1425                 }
1426         }
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);
1430                 exit(1);
1431         }
1432         ret *= mult;
1433         return ret;
1434 }
1435
1436 u64 parse_qgroupid(const char *p)
1437 {
1438         char *s = strchr(p, '/');
1439         const char *ptr_src_end = p + strlen(p);
1440         char *ptr_parse_end = NULL;
1441         u64 level;
1442         u64 id;
1443         int fd;
1444         int ret = 0;
1445
1446         if (p[0] == '/')
1447                 goto path;
1448
1449         /* Numeric format like '0/257' is the primary case */
1450         if (!s) {
1451                 id = strtoull(p, &ptr_parse_end, 10);
1452                 if (ptr_parse_end != ptr_src_end)
1453                         goto path;
1454                 return id;
1455         }
1456         level = strtoull(p, &ptr_parse_end, 10);
1457         if (ptr_parse_end != s)
1458                 goto path;
1459
1460         id = strtoull(s + 1, &ptr_parse_end, 10);
1461         if (ptr_parse_end != ptr_src_end)
1462                 goto  path;
1463
1464         return (level << BTRFS_QGROUP_LEVEL_SHIFT) | id;
1465
1466 path:
1467         /* Path format like subv at 'my_subvol' is the fallback case */
1468         ret = test_issubvolume(p);
1469         if (ret < 0 || !ret)
1470                 goto err;
1471         fd = open(p, O_RDONLY);
1472         if (fd < 0)
1473                 goto err;
1474         ret = lookup_path_rootid(fd, &id);
1475         if (ret)
1476                 error("failed to lookup root id: %s", strerror(-ret));
1477         close(fd);
1478         if (ret < 0)
1479                 goto err;
1480         return id;
1481
1482 err:
1483         error("invalid qgroupid or subvolume path: %s", p);
1484         exit(-1);
1485 }
1486
1487 int open_file_or_dir3(const char *fname, DIR **dirstream, int open_flags)
1488 {
1489         int ret;
1490         struct stat st;
1491         int fd;
1492
1493         ret = stat(fname, &st);
1494         if (ret < 0) {
1495                 return -1;
1496         }
1497         if (S_ISDIR(st.st_mode)) {
1498                 *dirstream = opendir(fname);
1499                 if (!*dirstream)
1500                         return -1;
1501                 fd = dirfd(*dirstream);
1502         } else if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
1503                 fd = open(fname, open_flags);
1504         } else {
1505                 /*
1506                  * we set this on purpose, in case the caller output
1507                  * strerror(errno) as success
1508                  */
1509                 errno = EINVAL;
1510                 return -1;
1511         }
1512         if (fd < 0) {
1513                 fd = -1;
1514                 if (*dirstream) {
1515                         closedir(*dirstream);
1516                         *dirstream = NULL;
1517                 }
1518         }
1519         return fd;
1520 }
1521
1522 int open_file_or_dir(const char *fname, DIR **dirstream)
1523 {
1524         return open_file_or_dir3(fname, dirstream, O_RDWR);
1525 }
1526
1527 void close_file_or_dir(int fd, DIR *dirstream)
1528 {
1529         if (dirstream)
1530                 closedir(dirstream);
1531         else if (fd >= 0)
1532                 close(fd);
1533 }
1534
1535 int get_device_info(int fd, u64 devid,
1536                 struct btrfs_ioctl_dev_info_args *di_args)
1537 {
1538         int ret;
1539
1540         di_args->devid = devid;
1541         memset(&di_args->uuid, '\0', sizeof(di_args->uuid));
1542
1543         ret = ioctl(fd, BTRFS_IOC_DEV_INFO, di_args);
1544         return ret < 0 ? -errno : 0;
1545 }
1546
1547 static u64 find_max_device_id(struct btrfs_ioctl_search_args *search_args,
1548                               int nr_items)
1549 {
1550         struct btrfs_dev_item *dev_item;
1551         char *buf = search_args->buf;
1552
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);
1556
1557         dev_item = (struct btrfs_dev_item *)buf;
1558
1559         return btrfs_stack_device_id(dev_item);
1560 }
1561
1562 static int search_chunk_tree_for_fs_info(int fd,
1563                                 struct btrfs_ioctl_fs_info_args *fi_args)
1564 {
1565         int ret;
1566         int max_items;
1567         u64 start_devid = 1;
1568         struct btrfs_ioctl_search_args search_args;
1569         struct btrfs_ioctl_search_key *search_key = &search_args.key;
1570
1571         fi_args->num_devices = 0;
1572
1573         max_items = BTRFS_SEARCH_ARGS_BUFSIZE
1574                / (sizeof(struct btrfs_ioctl_search_header)
1575                                + sizeof(struct btrfs_dev_item));
1576
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;
1586
1587 again:
1588         search_key->min_offset = start_devid;
1589
1590         ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH, &search_args);
1591         if (ret < 0)
1592                 return -errno;
1593
1594         fi_args->num_devices += (u64)search_key->nr_items;
1595
1596         if (search_key->nr_items == max_items) {
1597                 start_devid = find_max_device_id(&search_args,
1598                                         search_key->nr_items) + 1;
1599                 goto again;
1600         }
1601
1602         /* get the lastest max_id to stay consistent with the num_devices */
1603         if (search_key->nr_items == 0)
1604                 /*
1605                  * last tree_search returns an empty buf, use the devid of
1606                  * the last dev_item of the previous tree_search
1607                  */
1608                 fi_args->max_id = start_devid - 1;
1609         else
1610                 fi_args->max_id = find_max_device_id(&search_args,
1611                                                 search_key->nr_items);
1612
1613         return 0;
1614 }
1615
1616 /*
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.
1620  *
1621  * The path provided must be either on a mounted btrfs fs,
1622  * or be a mounted btrfs device.
1623  *
1624  * Returns 0 on success, or a negative errno.
1625  */
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)
1628 {
1629         int fd = -1;
1630         int ret = 0;
1631         int ndevs = 0;
1632         u64 last_devid = 0;
1633         int replacing = 0;
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;
1637         char mp[PATH_MAX];
1638         DIR *dirstream = NULL;
1639
1640         memset(fi_args, 0, sizeof(*fi_args));
1641
1642         if (is_block_device(path) == 1) {
1643                 struct btrfs_super_block *disk_super;
1644                 char buf[BTRFS_SUPER_INFO_SIZE];
1645
1646                 /* Ensure it's mounted, then set path to the mountpoint */
1647                 fd = open(path, O_RDONLY);
1648                 if (fd < 0) {
1649                         ret = -errno;
1650                         error("cannot open %s: %s", path, strerror(errno));
1651                         goto out;
1652                 }
1653                 ret = check_mounted_where(fd, path, mp, sizeof(mp),
1654                                           &fs_devices_mnt);
1655                 if (!ret) {
1656                         ret = -EINVAL;
1657                         goto out;
1658                 }
1659                 if (ret < 0)
1660                         goto out;
1661                 path = mp;
1662                 /* Only fill in this one device */
1663                 fi_args->num_devices = 1;
1664
1665                 disk_super = (struct btrfs_super_block *)buf;
1666                 ret = btrfs_read_dev_super(fd, disk_super,
1667                                            BTRFS_SUPER_INFO_OFFSET, 0);
1668                 if (ret < 0) {
1669                         ret = -EIO;
1670                         goto out;
1671                 }
1672                 last_devid = btrfs_stack_device_id(&disk_super->dev_item);
1673                 fi_args->max_id = last_devid;
1674
1675                 memcpy(fi_args->fsid, fs_devices_mnt->fsid, BTRFS_FSID_SIZE);
1676                 close(fd);
1677         }
1678
1679         /* at this point path must not be for a block device */
1680         fd = open_file_or_dir(path, &dirstream);
1681         if (fd < 0) {
1682                 ret = -errno;
1683                 goto out;
1684         }
1685
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);
1689                 if (ret < 0) {
1690                         ret = -errno;
1691                         goto out;
1692                 }
1693
1694                 /*
1695                  * The fs_args->num_devices does not include seed devices
1696                  */
1697                 ret = search_chunk_tree_for_fs_info(fd, fi_args);
1698                 if (ret)
1699                         goto out;
1700
1701                 /*
1702                  * search_chunk_tree_for_fs_info() will lacks the devid 0
1703                  * so manual probe for it here.
1704                  */
1705                 ret = get_device_info(fd, 0, &tmp);
1706                 if (!ret) {
1707                         fi_args->num_devices++;
1708                         ndevs++;
1709                         replacing = 1;
1710                         if (last_devid == 0)
1711                                 last_devid++;
1712                 }
1713         }
1714
1715         if (!fi_args->num_devices)
1716                 goto out;
1717
1718         di_args = *di_ret = malloc((fi_args->num_devices) * sizeof(*di_args));
1719         if (!di_args) {
1720                 ret = -errno;
1721                 goto out;
1722         }
1723
1724         if (replacing)
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]);
1728                 if (ret == -ENODEV)
1729                         continue;
1730                 if (ret)
1731                         goto out;
1732                 ndevs++;
1733         }
1734
1735         /*
1736         * only when the only dev we wanted to find is not there then
1737         * let any error be returned
1738         */
1739         if (fi_args->num_devices != 1) {
1740                 BUG_ON(ndevs == 0);
1741                 ret = 0;
1742         }
1743
1744 out:
1745         close_file_or_dir(fd, dirstream);
1746         return ret;
1747 }
1748
1749 static int group_profile_devs_min(u64 flag)
1750 {
1751         switch (flag & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
1752         case 0: /* single */
1753         case BTRFS_BLOCK_GROUP_DUP:
1754                 return 1;
1755         case BTRFS_BLOCK_GROUP_RAID0:
1756         case BTRFS_BLOCK_GROUP_RAID1:
1757         case BTRFS_BLOCK_GROUP_RAID5:
1758                 return 2;
1759         case BTRFS_BLOCK_GROUP_RAID6:
1760                 return 3;
1761         case BTRFS_BLOCK_GROUP_RAID10:
1762                 return 4;
1763         default:
1764                 return -1;
1765         }
1766 }
1767
1768 int test_num_disk_vs_raid(u64 metadata_profile, u64 data_profile,
1769         u64 dev_cnt, int mixed, int ssd)
1770 {
1771         u64 allowed = 0;
1772         u64 profile = metadata_profile | data_profile;
1773
1774         switch (dev_cnt) {
1775         default:
1776         case 4:
1777                 allowed |= BTRFS_BLOCK_GROUP_RAID10;
1778         case 3:
1779                 allowed |= BTRFS_BLOCK_GROUP_RAID6;
1780         case 2:
1781                 allowed |= BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
1782                         BTRFS_BLOCK_GROUP_RAID5;
1783         case 1:
1784                 allowed |= BTRFS_BLOCK_GROUP_DUP;
1785         }
1786
1787         if (dev_cnt > 1 && profile & BTRFS_BLOCK_GROUP_DUP) {
1788                 warning("DUP is not recommended on filesystem with multiple devices");
1789         }
1790         if (metadata_profile & ~allowed) {
1791                 fprintf(stderr,
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));
1796                 return 1;
1797         }
1798         if (data_profile & ~allowed) {
1799                 fprintf(stderr,
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));
1804                 return 1;
1805         }
1806
1807         if (dev_cnt == 3 && profile & BTRFS_BLOCK_GROUP_RAID6) {
1808                 warning("RAID6 is not recommended on filesystem with 3 devices only");
1809         }
1810         if (dev_cnt == 2 && profile & BTRFS_BLOCK_GROUP_RAID5) {
1811                 warning("RAID5 is not recommended on filesystem with 2 devices only");
1812         }
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");
1815
1816         return 0;
1817 }
1818
1819 int group_profile_max_safe_loss(u64 flags)
1820 {
1821         switch (flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
1822         case 0: /* single */
1823         case BTRFS_BLOCK_GROUP_DUP:
1824         case BTRFS_BLOCK_GROUP_RAID0:
1825                 return 0;
1826         case BTRFS_BLOCK_GROUP_RAID1:
1827         case BTRFS_BLOCK_GROUP_RAID5:
1828         case BTRFS_BLOCK_GROUP_RAID10:
1829                 return 1;
1830         case BTRFS_BLOCK_GROUP_RAID6:
1831                 return 2;
1832         default:
1833                 return -1;
1834         }
1835 }
1836
1837 int btrfs_scan_devices(void)
1838 {
1839         int fd = -1;
1840         int ret;
1841         u64 num_devices;
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];
1847
1848         if (btrfs_scan_done)
1849                 return 0;
1850
1851         if (blkid_get_cache(&cache, NULL) < 0) {
1852                 error("blkid cache get failed");
1853                 return 1;
1854         }
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);
1860                 if (!dev)
1861                         continue;
1862                 /* if we are here its definitely a btrfs disk*/
1863                 strncpy_null(path, blkid_dev_devname(dev));
1864
1865                 fd = open(path, O_RDONLY);
1866                 if (fd < 0) {
1867                         error("cannot open %s: %s", path, strerror(errno));
1868                         continue;
1869                 }
1870                 ret = btrfs_scan_one_device(fd, path, &tmp_devices,
1871                                 &num_devices, BTRFS_SUPER_INFO_OFFSET,
1872                                 SBREAD_DEFAULT);
1873                 if (ret) {
1874                         error("cannot scan %s: %s", path, strerror(-ret));
1875                         close (fd);
1876                         continue;
1877                 }
1878
1879                 close(fd);
1880         }
1881         blkid_dev_iterate_end(iter);
1882         blkid_put_cache(cache);
1883
1884         btrfs_scan_done = 1;
1885
1886         return 0;
1887 }
1888
1889 /*
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
1892  * or y.
1893  */
1894 int ask_user(const char *question)
1895 {
1896         char buf[30] = {0,};
1897         char *saveptr = NULL;
1898         char *answer;
1899
1900         printf("%s [y/N]: ", question);
1901
1902         return fgets(buf, sizeof(buf) - 1, stdin) &&
1903                (answer = strtok_r(buf, " \t\n\r", &saveptr)) &&
1904                (!strcasecmp(answer, "yes") || !strcasecmp(answer, "y"));
1905 }
1906
1907 /*
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
1911  */
1912 int find_mount_root(const char *path, char **mount_root)
1913 {
1914         FILE *mnttab;
1915         int fd;
1916         struct mntent *ent;
1917         int len;
1918         int ret;
1919         int not_btrfs = 1;
1920         int longest_matchlen = 0;
1921         char *longest_match = NULL;
1922
1923         fd = open(path, O_RDONLY | O_NOATIME);
1924         if (fd < 0)
1925                 return -errno;
1926         close(fd);
1927
1928         mnttab = setmntent("/proc/self/mounts", "r");
1929         if (!mnttab)
1930                 return -errno;
1931
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");
1941                         }
1942                 }
1943         }
1944         endmntent(mnttab);
1945
1946         if (!longest_match)
1947                 return -ENOENT;
1948         if (not_btrfs) {
1949                 free(longest_match);
1950                 return 1;
1951         }
1952
1953         ret = 0;
1954         *mount_root = realpath(longest_match, NULL);
1955         if (!*mount_root)
1956                 ret = -errno;
1957
1958         free(longest_match);
1959         return ret;
1960 }
1961
1962 /*
1963  * Test if path is a directory
1964  * Returns:
1965  *   0 - path exists but it is not a directory
1966  *   1 - path exists and it is a directory
1967  * < 0 - error
1968  */
1969 int test_isdir(const char *path)
1970 {
1971         struct stat st;
1972         int ret;
1973
1974         ret = stat(path, &st);
1975         if (ret < 0)
1976                 return -errno;
1977
1978         return !!S_ISDIR(st.st_mode);
1979 }
1980
1981 void units_set_mode(unsigned *units, unsigned mode)
1982 {
1983         unsigned base = *units & UNITS_MODE_MASK;
1984
1985         *units = base | mode;
1986 }
1987
1988 void units_set_base(unsigned *units, unsigned base)
1989 {
1990         unsigned mode = *units & ~UNITS_MODE_MASK;
1991
1992         *units = base | mode;
1993 }
1994
1995 int find_next_key(struct btrfs_path *path, struct btrfs_key *key)
1996 {
1997         int level;
1998
1999         for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2000                 if (!path->nodes[level])
2001                         break;
2002                 if (path->slots[level] + 1 >=
2003                     btrfs_header_nritems(path->nodes[level]))
2004                         continue;
2005                 if (level == 0)
2006                         btrfs_item_key_to_cpu(path->nodes[level], key,
2007                                               path->slots[level] + 1);
2008                 else
2009                         btrfs_node_key_to_cpu(path->nodes[level], key,
2010                                               path->slots[level] + 1);
2011                 return 0;
2012         }
2013         return 1;
2014 }
2015
2016 const char* btrfs_group_type_str(u64 flag)
2017 {
2018         u64 mask = BTRFS_BLOCK_GROUP_TYPE_MASK |
2019                 BTRFS_SPACE_INFO_GLOBAL_RSV;
2020
2021         switch (flag & mask) {
2022         case BTRFS_BLOCK_GROUP_DATA:
2023                 return "Data";
2024         case BTRFS_BLOCK_GROUP_SYSTEM:
2025                 return "System";
2026         case BTRFS_BLOCK_GROUP_METADATA:
2027                 return "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";
2032         default:
2033                 return "unknown";
2034         }
2035 }
2036
2037 const char* btrfs_group_profile_str(u64 flag)
2038 {
2039         switch (flag & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
2040         case 0:
2041                 return "single";
2042         case BTRFS_BLOCK_GROUP_RAID0:
2043                 return "RAID0";
2044         case BTRFS_BLOCK_GROUP_RAID1:
2045                 return "RAID1";
2046         case BTRFS_BLOCK_GROUP_RAID5:
2047                 return "RAID5";
2048         case BTRFS_BLOCK_GROUP_RAID6:
2049                 return "RAID6";
2050         case BTRFS_BLOCK_GROUP_DUP:
2051                 return "DUP";
2052         case BTRFS_BLOCK_GROUP_RAID10:
2053                 return "RAID10";
2054         default:
2055                 return "unknown";
2056         }
2057 }
2058
2059 u64 disk_size(const char *path)
2060 {
2061         struct statfs sfs;
2062
2063         if (statfs(path, &sfs) < 0)
2064                 return 0;
2065         else
2066                 return sfs.f_bsize * sfs.f_blocks;
2067 }
2068
2069 u64 get_partition_size(const char *dev)
2070 {
2071         u64 result;
2072         int fd = open(dev, O_RDONLY);
2073
2074         if (fd < 0)
2075                 return 0;
2076         if (ioctl(fd, BLKGETSIZE64, &result) < 0) {
2077                 close(fd);
2078                 return 0;
2079         }
2080         close(fd);
2081
2082         return result;
2083 }
2084
2085 /*
2086  * Check if the BTRFS_IOC_TREE_SEARCH_V2 ioctl is supported on a given
2087  * filesystem, opened at fd
2088  */
2089 int btrfs_tree_search2_ioctl_supported(int fd)
2090 {
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];
2095         int ret;
2096
2097         args2 = (struct btrfs_ioctl_search_args_v2 *)args2_buf;
2098         sk = &(args2->key);
2099
2100         /*
2101          * Search for the extent tree item in the root tree.
2102          */
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;
2108         sk->min_offset = 0;
2109         sk->max_offset = (u64)-1;
2110         sk->min_transid = 0;
2111         sk->max_transid = (u64)-1;
2112         sk->nr_items = 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)
2116                 return 0;
2117         else if (ret == 0)
2118                 return 1;
2119         return ret;
2120 }
2121
2122 int btrfs_check_nodesize(u32 nodesize, u32 sectorsize, u64 features)
2123 {
2124         if (nodesize < sectorsize) {
2125                 error("illegal nodesize %u (smaller than %u)",
2126                                 nodesize, sectorsize);
2127                 return -1;
2128         } else if (nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
2129                 error("illegal nodesize %u (larger than %u)",
2130                         nodesize, BTRFS_MAX_METADATA_BLOCKSIZE);
2131                 return -1;
2132         } else if (nodesize & (sectorsize - 1)) {
2133                 error("illegal nodesize %u (not aligned to %u)",
2134                         nodesize, sectorsize);
2135                 return -1;
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);
2140                 return -1;
2141         }
2142         return 0;
2143 }
2144
2145 /*
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
2148  * the buffer.
2149  * The destination buffer is zero terminated.
2150  * Return < 0 for error, 0 otherwise.
2151  */
2152 int arg_copy_path(char *dest, const char *src, int destlen)
2153 {
2154         size_t len = strlen(src);
2155
2156         if (len >= PATH_MAX || len >= destlen)
2157                 return -ENAMETOOLONG;
2158
2159         __strncpy_null(dest, src, destlen);
2160
2161         return 0;
2162 }
2163
2164 unsigned int get_unit_mode_from_arg(int *argc, char *argv[], int df_mode)
2165 {
2166         unsigned int unit_mode = UNITS_DEFAULT;
2167         int arg_i;
2168         int arg_end;
2169
2170         for (arg_i = 0; arg_i < *argc; arg_i++) {
2171                 if (!strcmp(argv[arg_i], "--"))
2172                         break;
2173
2174                 if (!strcmp(argv[arg_i], "--raw")) {
2175                         unit_mode = UNITS_RAW;
2176                         argv[arg_i] = NULL;
2177                         continue;
2178                 }
2179                 if (!strcmp(argv[arg_i], "--human-readable")) {
2180                         unit_mode = UNITS_HUMAN_BINARY;
2181                         argv[arg_i] = NULL;
2182                         continue;
2183                 }
2184
2185                 if (!strcmp(argv[arg_i], "--iec")) {
2186                         units_set_mode(&unit_mode, UNITS_BINARY);
2187                         argv[arg_i] = NULL;
2188                         continue;
2189                 }
2190                 if (!strcmp(argv[arg_i], "--si")) {
2191                         units_set_mode(&unit_mode, UNITS_DECIMAL);
2192                         argv[arg_i] = NULL;
2193                         continue;
2194                 }
2195
2196                 if (!strcmp(argv[arg_i], "--kbytes")) {
2197                         units_set_base(&unit_mode, UNITS_KBYTES);
2198                         argv[arg_i] = NULL;
2199                         continue;
2200                 }
2201                 if (!strcmp(argv[arg_i], "--mbytes")) {
2202                         units_set_base(&unit_mode, UNITS_MBYTES);
2203                         argv[arg_i] = NULL;
2204                         continue;
2205                 }
2206                 if (!strcmp(argv[arg_i], "--gbytes")) {
2207                         units_set_base(&unit_mode, UNITS_GBYTES);
2208                         argv[arg_i] = NULL;
2209                         continue;
2210                 }
2211                 if (!strcmp(argv[arg_i], "--tbytes")) {
2212                         units_set_base(&unit_mode, UNITS_TBYTES);
2213                         argv[arg_i] = NULL;
2214                         continue;
2215                 }
2216
2217                 if (!df_mode)
2218                         continue;
2219
2220                 if (!strcmp(argv[arg_i], "-b")) {
2221                         unit_mode = UNITS_RAW;
2222                         argv[arg_i] = NULL;
2223                         continue;
2224                 }
2225                 if (!strcmp(argv[arg_i], "-h")) {
2226                         unit_mode = UNITS_HUMAN_BINARY;
2227                         argv[arg_i] = NULL;
2228                         continue;
2229                 }
2230                 if (!strcmp(argv[arg_i], "-H")) {
2231                         unit_mode = UNITS_HUMAN_DECIMAL;
2232                         argv[arg_i] = NULL;
2233                         continue;
2234                 }
2235                 if (!strcmp(argv[arg_i], "-k")) {
2236                         units_set_base(&unit_mode, UNITS_KBYTES);
2237                         argv[arg_i] = NULL;
2238                         continue;
2239                 }
2240                 if (!strcmp(argv[arg_i], "-m")) {
2241                         units_set_base(&unit_mode, UNITS_MBYTES);
2242                         argv[arg_i] = NULL;
2243                         continue;
2244                 }
2245                 if (!strcmp(argv[arg_i], "-g")) {
2246                         units_set_base(&unit_mode, UNITS_GBYTES);
2247                         argv[arg_i] = NULL;
2248                         continue;
2249                 }
2250                 if (!strcmp(argv[arg_i], "-t")) {
2251                         units_set_base(&unit_mode, UNITS_TBYTES);
2252                         argv[arg_i] = NULL;
2253                         continue;
2254                 }
2255         }
2256
2257         for (arg_i = 0, arg_end = 0; arg_i < *argc; arg_i++) {
2258                 if (!argv[arg_i])
2259                         continue;
2260                 argv[arg_end] = argv[arg_i];
2261                 arg_end++;
2262         }
2263
2264         *argc = arg_end;
2265
2266         return unit_mode;
2267 }
2268
2269 u64 div_factor(u64 num, int factor)
2270 {
2271         if (factor == 10)
2272                 return num;
2273         num *= factor;
2274         num /= 10;
2275         return num;
2276 }
2277 /*
2278  * Get the length of the string converted from a u64 number.
2279  *
2280  * Result is equal to log10(num) + 1, but without the use of math library.
2281  */
2282 int count_digits(u64 num)
2283 {
2284         int ret = 0;
2285
2286         if (num == 0)
2287                 return 1;
2288         while (num > 0) {
2289                 ret++;
2290                 num /= 10;
2291         }
2292         return ret;
2293 }
2294
2295 int string_is_numerical(const char *str)
2296 {
2297         if (!str)
2298                 return 0;
2299         if (!(*str >= '0' && *str <= '9'))
2300                 return 0;
2301         while (*str >= '0' && *str <= '9')
2302                 str++;
2303         if (*str != '\0')
2304                 return 0;
2305         return 1;
2306 }
2307
2308 int prefixcmp(const char *str, const char *prefix)
2309 {
2310         for (; ; str++, prefix++)
2311                 if (!*prefix)
2312                         return 0;
2313                 else if (*str != *prefix)
2314                         return (unsigned char)*prefix - (unsigned char)*str;
2315 }
2316
2317 /* Subvolume helper functions */
2318 /*
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
2323  */
2324 int test_issubvolname(const char *name)
2325 {
2326         return name[0] != '\0' && !strchr(name, '/') &&
2327                 strcmp(name, ".") && strcmp(name, "..");
2328 }
2329
2330 /*
2331  * Test if path is a subvolume
2332  * Returns:
2333  *   0 - path exists but it is not a subvolume
2334  *   1 - path exists and it is  a subvolume
2335  * < 0 - error
2336  */
2337 int test_issubvolume(const char *path)
2338 {
2339         struct stat     st;
2340         struct statfs stfs;
2341         int             res;
2342
2343         res = stat(path, &st);
2344         if (res < 0)
2345                 return -errno;
2346
2347         if (st.st_ino != BTRFS_FIRST_FREE_OBJECTID || !S_ISDIR(st.st_mode))
2348                 return 0;
2349
2350         res = statfs(path, &stfs);
2351         if (res < 0)
2352                 return -errno;
2353
2354         return (int)stfs.f_type == BTRFS_SUPER_MAGIC;
2355 }
2356
2357 const char *subvol_strip_mountpoint(const char *mnt, const char *full_path)
2358 {
2359         int len = strlen(mnt);
2360         if (!len)
2361                 return full_path;
2362
2363         if (mnt[len - 1] != '/')
2364                 len += 1;
2365
2366         return full_path + len;
2367 }
2368
2369 /*
2370  * Returns
2371  * <0: Std error
2372  * 0: All fine
2373  * 1: Error; and error info printed to the terminal. Fixme.
2374  * 2: If the fullpath is root tree instead of subvol tree
2375  */
2376 int get_subvol_info(const char *fullpath, struct root_info *get_ri)
2377 {
2378         u64 sv_id;
2379         int ret = 1;
2380         int fd = -1;
2381         int mntfd = -1;
2382         char *mnt = NULL;
2383         const char *svpath = NULL;
2384         DIR *dirstream1 = NULL;
2385         DIR *dirstream2 = NULL;
2386
2387         ret = test_issubvolume(fullpath);
2388         if (ret < 0)
2389                 return ret;
2390         if (!ret) {
2391                 error("not a subvolume: %s", fullpath);
2392                 return 1;
2393         }
2394
2395         ret = find_mount_root(fullpath, &mnt);
2396         if (ret < 0)
2397                 return ret;
2398         if (ret > 0) {
2399                 error("%s doesn't belong to btrfs mount point", fullpath);
2400                 return 1;
2401         }
2402         ret = 1;
2403         svpath = subvol_strip_mountpoint(mnt, fullpath);
2404
2405         fd = btrfs_open_dir(fullpath, &dirstream1, 1);
2406         if (fd < 0)
2407                 goto out;
2408
2409         ret = btrfs_list_get_path_rootid(fd, &sv_id);
2410         if (ret)
2411                 goto out;
2412
2413         mntfd = btrfs_open_dir(mnt, &dirstream2, 1);
2414         if (mntfd < 0)
2415                 goto out;
2416
2417         memset(get_ri, 0, sizeof(*get_ri));
2418         get_ri->root_id = sv_id;
2419
2420         if (sv_id == BTRFS_FS_TREE_OBJECTID)
2421                 ret = btrfs_get_toplevel_subvol(mntfd, get_ri);
2422         else
2423                 ret = btrfs_get_subvol(mntfd, get_ri);
2424         if (ret)
2425                 error("can't find '%s': %d", svpath, ret);
2426
2427 out:
2428         close_file_or_dir(mntfd, dirstream2);
2429         close_file_or_dir(fd, dirstream1);
2430         free(mnt);
2431
2432         return ret;
2433 }
2434
2435 /* Set the seed manually */
2436 void init_rand_seed(u64 seed)
2437 {
2438         int i;
2439
2440         /* only use the last 48 bits */
2441         for (i = 0; i < 3; i++) {
2442                 rand_seed[i] = (unsigned short)(seed ^ (unsigned short)(-1));
2443                 seed >>= 16;
2444         }
2445         rand_seed_initlized = 1;
2446 }
2447
2448 static void __init_seed(void)
2449 {
2450         struct timeval tv;
2451         int ret;
2452         int fd;
2453
2454         if(rand_seed_initlized)
2455                 return;
2456         /* Use urandom as primary seed source. */
2457         fd = open("/dev/urandom", O_RDONLY);
2458         if (fd >= 0) {
2459                 ret = read(fd, rand_seed, sizeof(rand_seed));
2460                 close(fd);
2461                 if (ret < sizeof(rand_seed))
2462                         goto fallback;
2463         } else {
2464 fallback:
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;
2471         }
2472         rand_seed_initlized = 1;
2473 }
2474
2475 u32 rand_u32(void)
2476 {
2477         __init_seed();
2478         /*
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.
2481          */
2482         return (u32)jrand48(rand_seed);
2483 }
2484
2485 /* Return random number in range [0, upper) */
2486 unsigned int rand_range(unsigned int upper)
2487 {
2488         __init_seed();
2489         /*
2490          * Use the full 48bits to mod, which would be more uniformly
2491          * distributed
2492          */
2493         return (unsigned int)(jrand48(rand_seed) % upper);
2494 }
2495
2496 int rand_int(void)
2497 {
2498         return (int)(rand_u32());
2499 }
2500
2501 u64 rand_u64(void)
2502 {
2503         u64 ret = 0;
2504
2505         ret += rand_u32();
2506         ret <<= 32;
2507         ret += rand_u32();
2508         return ret;
2509 }
2510
2511 u16 rand_u16(void)
2512 {
2513         return (u16)(rand_u32());
2514 }
2515
2516 u8 rand_u8(void)
2517 {
2518         return (u8)(rand_u32());
2519 }
2520
2521 void btrfs_config_init(void)
2522 {
2523 }