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