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