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