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