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