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