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