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