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