btrfs-progs: Introduce function to initialize device tree
[platform/upstream/btrfs-progs.git] / utils.c
1 /*
2  * Copyright (C) 2007 Oracle.  All rights reserved.
3  * Copyright (C) 2008 Morey Roof.  All rights reserved.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public
7  * License v2 as published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public
15  * License along with this program; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 021110-1307, USA.
18  */
19
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <sys/ioctl.h>
24 #include <sys/mount.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <uuid/uuid.h>
28 #include <fcntl.h>
29 #include <unistd.h>
30 #include <mntent.h>
31 #include <ctype.h>
32 #include <linux/loop.h>
33 #include <linux/major.h>
34 #include <linux/kdev_t.h>
35 #include <limits.h>
36 #include <blkid/blkid.h>
37 #include <sys/vfs.h>
38 #include <sys/statfs.h>
39 #include <linux/magic.h>
40 #include <getopt.h>
41
42 #include "kerncompat.h"
43 #include "radix-tree.h"
44 #include "ctree.h"
45 #include "disk-io.h"
46 #include "transaction.h"
47 #include "crc32c.h"
48 #include "utils.h"
49 #include "volumes.h"
50 #include "ioctl.h"
51 #include "commands.h"
52
53 #ifndef BLKDISCARD
54 #define BLKDISCARD      _IO(0x12,119)
55 #endif
56
57 static int btrfs_scan_done = 0;
58
59 static char argv0_buf[ARGV0_BUF_SIZE] = "btrfs";
60
61 static int rand_seed_initlized = 0;
62 static unsigned short rand_seed[3];
63
64 const char *get_argv0_buf(void)
65 {
66         return argv0_buf;
67 }
68
69 void fixup_argv0(char **argv, const char *token)
70 {
71         int len = strlen(argv0_buf);
72
73         snprintf(argv0_buf + len, sizeof(argv0_buf) - len, " %s", token);
74         argv[0] = argv0_buf;
75 }
76
77 void set_argv0(char **argv)
78 {
79         strncpy(argv0_buf, argv[0], sizeof(argv0_buf));
80         argv0_buf[sizeof(argv0_buf) - 1] = 0;
81 }
82
83 int check_argc_exact(int nargs, int expected)
84 {
85         if (nargs < expected)
86                 fprintf(stderr, "%s: too few arguments\n", argv0_buf);
87         if (nargs > expected)
88                 fprintf(stderr, "%s: too many arguments\n", argv0_buf);
89
90         return nargs != expected;
91 }
92
93 int check_argc_min(int nargs, int expected)
94 {
95         if (nargs < expected) {
96                 fprintf(stderr, "%s: too few arguments\n", argv0_buf);
97                 return 1;
98         }
99
100         return 0;
101 }
102
103 int check_argc_max(int nargs, int expected)
104 {
105         if (nargs > expected) {
106                 fprintf(stderr, "%s: too many arguments\n", argv0_buf);
107                 return 1;
108         }
109
110         return 0;
111 }
112
113
114 /*
115  * Discard the given range in one go
116  */
117 static int discard_range(int fd, u64 start, u64 len)
118 {
119         u64 range[2] = { start, len };
120
121         if (ioctl(fd, BLKDISCARD, &range) < 0)
122                 return errno;
123         return 0;
124 }
125
126 /*
127  * Discard blocks in the given range in 1G chunks, the process is interruptible
128  */
129 static int discard_blocks(int fd, u64 start, u64 len)
130 {
131         while (len > 0) {
132                 /* 1G granularity */
133                 u64 chunk_size = min_t(u64, len, 1*1024*1024*1024);
134                 int ret;
135
136                 ret = discard_range(fd, start, chunk_size);
137                 if (ret)
138                         return ret;
139                 len -= chunk_size;
140                 start += chunk_size;
141         }
142
143         return 0;
144 }
145
146 static u64 reference_root_table[] = {
147         [1] =   BTRFS_ROOT_TREE_OBJECTID,
148         [2] =   BTRFS_EXTENT_TREE_OBJECTID,
149         [3] =   BTRFS_CHUNK_TREE_OBJECTID,
150         [4] =   BTRFS_DEV_TREE_OBJECTID,
151         [5] =   BTRFS_FS_TREE_OBJECTID,
152         [6] =   BTRFS_CSUM_TREE_OBJECTID,
153 };
154
155 int test_uuid_unique(char *fs_uuid)
156 {
157         int unique = 1;
158         blkid_dev_iterate iter = NULL;
159         blkid_dev dev = NULL;
160         blkid_cache cache = NULL;
161
162         if (blkid_get_cache(&cache, NULL) < 0) {
163                 printf("ERROR: lblkid cache get failed\n");
164                 return 1;
165         }
166         blkid_probe_all(cache);
167         iter = blkid_dev_iterate_begin(cache);
168         blkid_dev_set_search(iter, "UUID", fs_uuid);
169
170         while (blkid_dev_next(iter, &dev) == 0) {
171                 dev = blkid_verify(cache, dev);
172                 if (dev) {
173                         unique = 0;
174                         break;
175                 }
176         }
177
178         blkid_dev_iterate_end(iter);
179         blkid_put_cache(cache);
180
181         return unique;
182 }
183
184 /*
185  * Reserve space from free_tree.
186  * The algorithm is very simple, find the first cache_extent with enough space
187  * and allocate from its beginning.
188  */
189 static int reserve_free_space(struct cache_tree *free_tree, u64 len,
190                               u64 *ret_start)
191 {
192         struct cache_extent *cache;
193         int found = 0;
194
195         BUG_ON(!ret_start);
196         cache = first_cache_extent(free_tree);
197         while (cache) {
198                 if (cache->size > len) {
199                         found = 1;
200                         *ret_start = cache->start;
201
202                         cache->size -= len;
203                         if (cache->size == 0) {
204                                 remove_cache_extent(free_tree, cache);
205                                 free(cache);
206                         } else {
207                                 cache->start += len;
208                         }
209                         break;
210                 }
211                 cache = next_cache_extent(cache);
212         }
213         if (!found)
214                 return -ENOSPC;
215         return 0;
216 }
217
218 static inline int write_temp_super(int fd, struct btrfs_super_block *sb,
219                                    u64 sb_bytenr)
220 {
221         u32 crc = ~(u32)0;
222         int ret;
223
224         crc = btrfs_csum_data(NULL, (char *)sb + BTRFS_CSUM_SIZE, crc,
225                               BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
226         btrfs_csum_final(crc, (char *)&sb->csum[0]);
227         ret = pwrite(fd, sb, BTRFS_SUPER_INFO_SIZE, sb_bytenr);
228         if (ret < BTRFS_SUPER_INFO_SIZE)
229                 ret = (ret < 0 ? -errno : -EIO);
230         else
231                 ret = 0;
232         return ret;
233 }
234
235 /*
236  * Setup temporary superblock at cfg->super_bynter
237  * Needed info are extracted from cfg, and root_bytenr, chunk_bytenr
238  *
239  * For now sys chunk array will be empty and dev_item is empty too.
240  * They will be re-initialized at temp chunk tree setup.
241  */
242 static int setup_temp_super(int fd, struct btrfs_mkfs_config *cfg,
243                             u64 root_bytenr, u64 chunk_bytenr)
244 {
245         unsigned char chunk_uuid[BTRFS_UUID_SIZE];
246         char super_buf[BTRFS_SUPER_INFO_SIZE];
247         struct btrfs_super_block *super = (struct btrfs_super_block *)super_buf;
248         int ret;
249
250         /*
251          * We rely on cfg->chunk_uuid and cfg->fs_uuid to pass uuid
252          * for other functions.
253          * Caller must allocate space for them
254          */
255         BUG_ON(!cfg->chunk_uuid || !cfg->fs_uuid);
256         memset(super_buf, 0, BTRFS_SUPER_INFO_SIZE);
257         cfg->num_bytes = round_down(cfg->num_bytes, cfg->sectorsize);
258
259         if (cfg->fs_uuid && *cfg->fs_uuid) {
260                 if (uuid_parse(cfg->fs_uuid, super->fsid) != 0) {
261                         error("cound not parse UUID: %s", cfg->fs_uuid);
262                         ret = -EINVAL;
263                         goto out;
264                 }
265                 if (!test_uuid_unique(cfg->fs_uuid)) {
266                         error("non-unique UUID: %s", cfg->fs_uuid);
267                         ret = -EINVAL;
268                         goto out;
269                 }
270         } else {
271                 uuid_generate(super->fsid);
272                 uuid_unparse(super->fsid, cfg->fs_uuid);
273         }
274         uuid_generate(chunk_uuid);
275         uuid_unparse(chunk_uuid, cfg->chunk_uuid);
276
277         btrfs_set_super_bytenr(super, cfg->super_bytenr);
278         btrfs_set_super_num_devices(super, 1);
279         btrfs_set_super_magic(super, BTRFS_MAGIC);
280         btrfs_set_super_generation(super, 1);
281         btrfs_set_super_root(super, root_bytenr);
282         btrfs_set_super_chunk_root(super, chunk_bytenr);
283         btrfs_set_super_total_bytes(super, cfg->num_bytes);
284         /*
285          * Temporary filesystem will only have 6 tree roots:
286          * chunk tree, root tree, extent_tree, device tree, fs tree
287          * and csum tree.
288          */
289         btrfs_set_super_bytes_used(super, 6 * cfg->nodesize);
290         btrfs_set_super_sectorsize(super, cfg->sectorsize);
291         btrfs_set_super_leafsize(super, cfg->nodesize);
292         btrfs_set_super_nodesize(super, cfg->nodesize);
293         btrfs_set_super_stripesize(super, cfg->stripesize);
294         btrfs_set_super_csum_type(super, BTRFS_CSUM_TYPE_CRC32);
295         btrfs_set_super_chunk_root(super, chunk_bytenr);
296         btrfs_set_super_cache_generation(super, -1);
297         btrfs_set_super_incompat_flags(super, cfg->features);
298         if (cfg->label)
299                 __strncpy_null(super->label, cfg->label, BTRFS_LABEL_SIZE - 1);
300
301         /* Sys chunk array will be re-initialized at chunk tree init time */
302         super->sys_chunk_array_size = 0;
303
304         ret = write_temp_super(fd, super, cfg->super_bytenr);
305 out:
306         return ret;
307 }
308
309 /*
310  * Setup an extent buffer for tree block.
311  */
312 static int setup_temp_extent_buffer(struct extent_buffer *buf,
313                                     struct btrfs_mkfs_config *cfg,
314                                     u64 bytenr, u64 owner)
315 {
316         unsigned char fsid[BTRFS_FSID_SIZE];
317         unsigned char chunk_uuid[BTRFS_UUID_SIZE];
318         int ret;
319
320         /* We rely on cfg->fs_uuid and chunk_uuid to fsid and chunk uuid */
321         BUG_ON(!cfg->fs_uuid || !cfg->chunk_uuid);
322         ret = uuid_parse(cfg->fs_uuid, fsid);
323         if (ret)
324                 return -EINVAL;
325         ret = uuid_parse(cfg->chunk_uuid, chunk_uuid);
326         if (ret)
327                 return -EINVAL;
328
329         memset(buf->data, 0, cfg->nodesize);
330         buf->len = cfg->nodesize;
331         btrfs_set_header_bytenr(buf, bytenr);
332         btrfs_set_header_generation(buf, 1);
333         btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
334         btrfs_set_header_owner(buf, owner);
335         btrfs_set_header_flags(buf, BTRFS_HEADER_FLAG_WRITTEN);
336         write_extent_buffer(buf, chunk_uuid, btrfs_header_chunk_tree_uuid(buf),
337                             BTRFS_UUID_SIZE);
338         write_extent_buffer(buf, fsid, btrfs_header_fsid(), BTRFS_FSID_SIZE);
339         return 0;
340 }
341
342 static inline int write_temp_extent_buffer(int fd, struct extent_buffer *buf,
343                                            u64 bytenr)
344 {
345         int ret;
346
347         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
348
349         /* Temporary extent buffer is always mapped 1:1 on disk */
350         ret = pwrite(fd, buf->data, buf->len, bytenr);
351         if (ret < buf->len)
352                 ret = (ret < 0 ? ret : -EIO);
353         else
354                 ret = 0;
355         return ret;
356 }
357
358 /*
359  * Insert a root item for temporary tree root
360  *
361  * Only used in make_btrfs_v2().
362  */
363 static void insert_temp_root_item(struct extent_buffer *buf,
364                                   struct btrfs_mkfs_config *cfg,
365                                   int *slot, u32 *itemoff, u64 objectid,
366                                   u64 bytenr)
367 {
368         struct btrfs_root_item root_item;
369         struct btrfs_inode_item *inode_item;
370         struct btrfs_disk_key disk_key;
371
372         btrfs_set_header_nritems(buf, *slot + 1);
373         (*itemoff) -= sizeof(root_item);
374         memset(&root_item, 0, sizeof(root_item));
375         inode_item = &root_item.inode;
376         btrfs_set_stack_inode_generation(inode_item, 1);
377         btrfs_set_stack_inode_size(inode_item, 3);
378         btrfs_set_stack_inode_nlink(inode_item, 1);
379         btrfs_set_stack_inode_nbytes(inode_item, cfg->nodesize);
380         btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
381         btrfs_set_root_refs(&root_item, 1);
382         btrfs_set_root_used(&root_item, cfg->nodesize);
383         btrfs_set_root_generation(&root_item, 1);
384         btrfs_set_root_bytenr(&root_item, bytenr);
385
386         memset(&disk_key, 0, sizeof(disk_key));
387         btrfs_set_disk_key_type(&disk_key, BTRFS_ROOT_ITEM_KEY);
388         btrfs_set_disk_key_objectid(&disk_key, objectid);
389         btrfs_set_disk_key_offset(&disk_key, 0);
390
391         btrfs_set_item_key(buf, &disk_key, *slot);
392         btrfs_set_item_offset(buf, btrfs_item_nr(*slot), *itemoff);
393         btrfs_set_item_size(buf, btrfs_item_nr(*slot), sizeof(root_item));
394         write_extent_buffer(buf, &root_item,
395                             btrfs_item_ptr_offset(buf, *slot),
396                             sizeof(root_item));
397         (*slot)++;
398 }
399
400 static int setup_temp_root_tree(int fd, struct btrfs_mkfs_config *cfg,
401                                 u64 root_bytenr, u64 extent_bytenr,
402                                 u64 dev_bytenr, u64 fs_bytenr, u64 csum_bytenr)
403 {
404         struct extent_buffer *buf = NULL;
405         u32 itemoff = __BTRFS_LEAF_DATA_SIZE(cfg->nodesize);
406         int slot = 0;
407         int ret;
408
409         /*
410          * Provided bytenr must in ascending order, or tree root will have a
411          * bad key order.
412          */
413         BUG_ON(!(root_bytenr < extent_bytenr && extent_bytenr < dev_bytenr &&
414                  dev_bytenr < fs_bytenr && fs_bytenr < csum_bytenr));
415         buf = malloc(sizeof(*buf) + cfg->nodesize);
416         if (!buf)
417                 return -ENOMEM;
418
419         ret = setup_temp_extent_buffer(buf, cfg, root_bytenr,
420                                        BTRFS_ROOT_TREE_OBJECTID);
421         if (ret < 0)
422                 goto out;
423
424         insert_temp_root_item(buf, cfg, &slot, &itemoff,
425                               BTRFS_EXTENT_TREE_OBJECTID, extent_bytenr);
426         insert_temp_root_item(buf, cfg, &slot, &itemoff,
427                               BTRFS_DEV_TREE_OBJECTID, dev_bytenr);
428         insert_temp_root_item(buf, cfg, &slot, &itemoff,
429                               BTRFS_FS_TREE_OBJECTID, fs_bytenr);
430         insert_temp_root_item(buf, cfg, &slot, &itemoff,
431                               BTRFS_CSUM_TREE_OBJECTID, csum_bytenr);
432
433         ret = write_temp_extent_buffer(fd, buf, root_bytenr);
434 out:
435         free(buf);
436         return ret;
437 }
438
439 static int insert_temp_dev_item(int fd, struct extent_buffer *buf,
440                                 struct btrfs_mkfs_config *cfg,
441                                 int *slot, u32 *itemoff)
442 {
443         struct btrfs_disk_key disk_key;
444         struct btrfs_dev_item *dev_item;
445         char super_buf[BTRFS_SUPER_INFO_SIZE];
446         unsigned char dev_uuid[BTRFS_UUID_SIZE];
447         unsigned char fsid[BTRFS_FSID_SIZE];
448         struct btrfs_super_block *super = (struct btrfs_super_block *)super_buf;
449         int ret;
450
451         ret = pread(fd, super_buf, BTRFS_SUPER_INFO_SIZE, cfg->super_bytenr);
452         if (ret < BTRFS_SUPER_INFO_SIZE) {
453                 ret = (ret < 0 ? -errno : -EIO);
454                 goto out;
455         }
456
457         btrfs_set_header_nritems(buf, *slot + 1);
458         (*itemoff) -= sizeof(*dev_item);
459         /* setup device item 1, 0 is for replace case */
460         btrfs_set_disk_key_type(&disk_key, BTRFS_DEV_ITEM_KEY);
461         btrfs_set_disk_key_objectid(&disk_key, BTRFS_DEV_ITEMS_OBJECTID);
462         btrfs_set_disk_key_offset(&disk_key, 1);
463         btrfs_set_item_key(buf, &disk_key, *slot);
464         btrfs_set_item_offset(buf, btrfs_item_nr(*slot), *itemoff);
465         btrfs_set_item_size(buf, btrfs_item_nr(*slot), sizeof(*dev_item));
466
467         dev_item = btrfs_item_ptr(buf, *slot, struct btrfs_dev_item);
468         /* Generate device uuid */
469         uuid_generate(dev_uuid);
470         write_extent_buffer(buf, dev_uuid,
471                         (unsigned long)btrfs_device_uuid(dev_item),
472                         BTRFS_UUID_SIZE);
473         uuid_parse(cfg->fs_uuid, fsid);
474         write_extent_buffer(buf, fsid,
475                         (unsigned long)btrfs_device_fsid(dev_item),
476                         BTRFS_FSID_SIZE);
477         btrfs_set_device_id(buf, dev_item, 1);
478         btrfs_set_device_generation(buf, dev_item, 0);
479         btrfs_set_device_total_bytes(buf, dev_item, cfg->num_bytes);
480         /*
481          * The number must match the initial SYSTEM and META chunk size
482          */
483         btrfs_set_device_bytes_used(buf, dev_item,
484                         BTRFS_MKFS_SYSTEM_GROUP_SIZE +
485                         BTRFS_CONVERT_META_GROUP_SIZE);
486         btrfs_set_device_io_align(buf, dev_item, cfg->sectorsize);
487         btrfs_set_device_io_width(buf, dev_item, cfg->sectorsize);
488         btrfs_set_device_sector_size(buf, dev_item, cfg->sectorsize);
489         btrfs_set_device_type(buf, dev_item, 0);
490
491         /* Super dev_item is not complete, copy the complete one to sb */
492         read_extent_buffer(buf, &super->dev_item, (unsigned long)dev_item,
493                            sizeof(*dev_item));
494         ret = write_temp_super(fd, super, cfg->super_bytenr);
495         (*slot)++;
496 out:
497         return ret;
498 }
499
500 static int insert_temp_chunk_item(int fd, struct extent_buffer *buf,
501                                   struct btrfs_mkfs_config *cfg,
502                                   int *slot, u32 *itemoff, u64 start, u64 len,
503                                   u64 type)
504 {
505         struct btrfs_chunk *chunk;
506         struct btrfs_disk_key disk_key;
507         char super_buf[BTRFS_SUPER_INFO_SIZE];
508         struct btrfs_super_block *sb = (struct btrfs_super_block *)super_buf;
509         int ret = 0;
510
511         ret = pread(fd, super_buf, BTRFS_SUPER_INFO_SIZE,
512                     cfg->super_bytenr);
513         if (ret < BTRFS_SUPER_INFO_SIZE) {
514                 ret = (ret < 0 ? ret : -EIO);
515                 return ret;
516         }
517
518         btrfs_set_header_nritems(buf, *slot + 1);
519         (*itemoff) -= btrfs_chunk_item_size(1);
520         btrfs_set_disk_key_type(&disk_key, BTRFS_CHUNK_ITEM_KEY);
521         btrfs_set_disk_key_objectid(&disk_key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
522         btrfs_set_disk_key_offset(&disk_key, start);
523         btrfs_set_item_key(buf, &disk_key, *slot);
524         btrfs_set_item_offset(buf, btrfs_item_nr(*slot), *itemoff);
525         btrfs_set_item_size(buf, btrfs_item_nr(*slot),
526                             btrfs_chunk_item_size(1));
527
528         chunk = btrfs_item_ptr(buf, *slot, struct btrfs_chunk);
529         btrfs_set_chunk_length(buf, chunk, len);
530         btrfs_set_chunk_owner(buf, chunk, BTRFS_EXTENT_TREE_OBJECTID);
531         btrfs_set_chunk_stripe_len(buf, chunk, 64 * 1024);
532         btrfs_set_chunk_type(buf, chunk, type);
533         btrfs_set_chunk_io_align(buf, chunk, cfg->sectorsize);
534         btrfs_set_chunk_io_width(buf, chunk, cfg->sectorsize);
535         btrfs_set_chunk_sector_size(buf, chunk, cfg->sectorsize);
536         btrfs_set_chunk_num_stripes(buf, chunk, 1);
537         /* TODO: Support DUP profile for system chunk */
538         btrfs_set_stripe_devid_nr(buf, chunk, 0, 1);
539         /* We are doing 1:1 mapping, so start is its dev offset */
540         btrfs_set_stripe_offset_nr(buf, chunk, 0, start);
541         write_extent_buffer(buf, &sb->dev_item.uuid,
542                             (unsigned long)btrfs_stripe_dev_uuid_nr(chunk, 0),
543                             BTRFS_UUID_SIZE);
544         (*slot)++;
545
546         /*
547          * If it's system chunk, also copy it to super block.
548          */
549         if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
550                 char *cur;
551
552                 cur = (char *)sb->sys_chunk_array + sb->sys_chunk_array_size;
553                 memcpy(cur, &disk_key, sizeof(disk_key));
554                 cur += sizeof(disk_key);
555                 read_extent_buffer(buf, cur, (unsigned long int)chunk,
556                                    btrfs_chunk_item_size(1));
557                 sb->sys_chunk_array_size += btrfs_chunk_item_size(1) +
558                                             sizeof(disk_key);
559
560                 ret = write_temp_super(fd, sb, cfg->super_bytenr);
561         }
562         return ret;
563 }
564
565 static int setup_temp_chunk_tree(int fd, struct btrfs_mkfs_config *cfg,
566                                  u64 sys_chunk_start, u64 meta_chunk_start,
567                                  u64 chunk_bytenr)
568 {
569         struct extent_buffer *buf = NULL;
570         u32 itemoff = __BTRFS_LEAF_DATA_SIZE(cfg->nodesize);
571         int slot = 0;
572         int ret;
573
574         /* Must ensure SYS chunk starts before META chunk */
575         BUG_ON(meta_chunk_start < sys_chunk_start);
576         buf = malloc(sizeof(*buf) + cfg->nodesize);
577         if (!buf)
578                 return -ENOMEM;
579         ret = setup_temp_extent_buffer(buf, cfg, chunk_bytenr,
580                                        BTRFS_CHUNK_TREE_OBJECTID);
581         if (ret < 0)
582                 goto out;
583
584         ret = insert_temp_dev_item(fd, buf, cfg, &slot, &itemoff);
585         if (ret < 0)
586                 goto out;
587         ret = insert_temp_chunk_item(fd, buf, cfg, &slot, &itemoff,
588                                      sys_chunk_start,
589                                      BTRFS_MKFS_SYSTEM_GROUP_SIZE,
590                                      BTRFS_BLOCK_GROUP_SYSTEM);
591         if (ret < 0)
592                 goto out;
593         ret = insert_temp_chunk_item(fd, buf, cfg, &slot, &itemoff,
594                                      meta_chunk_start,
595                                      BTRFS_CONVERT_META_GROUP_SIZE,
596                                      BTRFS_BLOCK_GROUP_METADATA);
597         if (ret < 0)
598                 goto out;
599         ret = write_temp_extent_buffer(fd, buf, chunk_bytenr);
600
601 out:
602         free(buf);
603         return ret;
604 }
605
606 static void insert_temp_dev_extent(struct extent_buffer *buf,
607                                    int *slot, u32 *itemoff, u64 start, u64 len)
608 {
609         struct btrfs_dev_extent *dev_extent;
610         struct btrfs_disk_key disk_key;
611
612         btrfs_set_header_nritems(buf, *slot + 1);
613         (*itemoff) -= sizeof(*dev_extent);
614         btrfs_set_disk_key_type(&disk_key, BTRFS_DEV_EXTENT_KEY);
615         btrfs_set_disk_key_objectid(&disk_key, 1);
616         btrfs_set_disk_key_offset(&disk_key, start);
617         btrfs_set_item_key(buf, &disk_key, *slot);
618         btrfs_set_item_offset(buf, btrfs_item_nr(*slot), *itemoff);
619         btrfs_set_item_size(buf, btrfs_item_nr(*slot), sizeof(*dev_extent));
620
621         dev_extent = btrfs_item_ptr(buf, *slot, struct btrfs_dev_extent);
622         btrfs_set_dev_extent_chunk_objectid(buf, dev_extent,
623                                             BTRFS_FIRST_CHUNK_TREE_OBJECTID);
624         btrfs_set_dev_extent_length(buf, dev_extent, len);
625         btrfs_set_dev_extent_chunk_offset(buf, dev_extent, start);
626         btrfs_set_dev_extent_chunk_tree(buf, dev_extent,
627                                         BTRFS_CHUNK_TREE_OBJECTID);
628         (*slot)++;
629 }
630
631 static int setup_temp_dev_tree(int fd, struct btrfs_mkfs_config *cfg,
632                                u64 sys_chunk_start, u64 meta_chunk_start,
633                                u64 dev_bytenr)
634 {
635         struct extent_buffer *buf = NULL;
636         u32 itemoff = __BTRFS_LEAF_DATA_SIZE(cfg->nodesize);
637         int slot = 0;
638         int ret;
639
640         /* Must ensure SYS chunk starts before META chunk */
641         BUG_ON(meta_chunk_start < sys_chunk_start);
642         buf = malloc(sizeof(*buf) + cfg->nodesize);
643         if (!buf)
644                 return -ENOMEM;
645         ret = setup_temp_extent_buffer(buf, cfg, dev_bytenr,
646                                        BTRFS_DEV_TREE_OBJECTID);
647         if (ret < 0)
648                 goto out;
649         insert_temp_dev_extent(buf, &slot, &itemoff, sys_chunk_start,
650                                BTRFS_MKFS_SYSTEM_GROUP_SIZE);
651         insert_temp_dev_extent(buf, &slot, &itemoff, meta_chunk_start,
652                                BTRFS_CONVERT_META_GROUP_SIZE);
653         ret = write_temp_extent_buffer(fd, buf, dev_bytenr);
654 out:
655         free(buf);
656         return ret;
657 }
658
659 /*
660  * Improved version of make_btrfs().
661  *
662  * This one will
663  * 1) Do chunk allocation to avoid used data
664  *    And after this function, extent type matches chunk type
665  * 2) Better structured code
666  *    No super long hand written codes to initialized all tree blocks
667  *    Split into small blocks and reuse codes.
668  *    TODO: Reuse tree operation facilities by introducing new flags
669  */
670 static int make_convert_btrfs(int fd, struct btrfs_mkfs_config *cfg,
671                               struct btrfs_convert_context *cctx)
672 {
673         struct cache_tree *free = &cctx->free;
674         struct cache_tree *used = &cctx->used;
675         u64 sys_chunk_start;
676         u64 meta_chunk_start;
677         /* chunk tree bytenr, in system chunk */
678         u64 chunk_bytenr;
679         /* metadata trees bytenr, in metadata chunk */
680         u64 root_bytenr;
681         u64 extent_bytenr;
682         u64 dev_bytenr;
683         u64 fs_bytenr;
684         u64 csum_bytenr;
685         int ret;
686
687         /* Shouldn't happen */
688         BUG_ON(cache_tree_empty(used));
689
690         /*
691          * reserve space for temporary superblock first
692          * Here we allocate a little larger space, to keep later
693          * free space will be STRIPE_LEN aligned
694          */
695         ret = reserve_free_space(free, BTRFS_STRIPE_LEN,
696                                  &cfg->super_bytenr);
697         if (ret < 0)
698                 goto out;
699
700         /*
701          * Then reserve system chunk space
702          * TODO: Change system group size depending on cctx->total_bytes.
703          * If using current 4M, it can only handle less than one TB for
704          * worst case and then run out of sys space.
705          */
706         ret = reserve_free_space(free, BTRFS_MKFS_SYSTEM_GROUP_SIZE,
707                                  &sys_chunk_start);
708         if (ret < 0)
709                 goto out;
710         ret = reserve_free_space(free, BTRFS_CONVERT_META_GROUP_SIZE,
711                                  &meta_chunk_start);
712         if (ret < 0)
713                 goto out;
714
715         /*
716          * Allocated meta/sys chunks will be mapped 1:1 with device offset.
717          *
718          * Inside the allocated metadata chunk, the layout will be:
719          *  | offset            | contents      |
720          *  -------------------------------------
721          *  | +0                | tree root     |
722          *  | +nodesize         | extent root   |
723          *  | +nodesize * 2     | device root   |
724          *  | +nodesize * 3     | fs tree       |
725          *  | +nodesize * 4     | csum tree     |
726          *  -------------------------------------
727          * Inside the allocated system chunk, the layout will be:
728          *  | offset            | contents      |
729          *  -------------------------------------
730          *  | +0                | chunk root    |
731          *  -------------------------------------
732          */
733         chunk_bytenr = sys_chunk_start;
734         root_bytenr = meta_chunk_start;
735         extent_bytenr = meta_chunk_start + cfg->nodesize;
736         dev_bytenr = meta_chunk_start + cfg->nodesize * 2;
737         fs_bytenr = meta_chunk_start + cfg->nodesize * 3;
738         csum_bytenr = meta_chunk_start + cfg->nodesize * 4;
739
740         ret = setup_temp_super(fd, cfg, root_bytenr, chunk_bytenr);
741         if (ret < 0)
742                 goto out;
743
744         ret = setup_temp_root_tree(fd, cfg, root_bytenr, extent_bytenr,
745                                    dev_bytenr, fs_bytenr, csum_bytenr);
746         if (ret < 0)
747                 goto out;
748         ret = setup_temp_chunk_tree(fd, cfg, sys_chunk_start, meta_chunk_start,
749                                     chunk_bytenr);
750         if (ret < 0)
751                 goto out;
752         ret = setup_temp_dev_tree(fd, cfg, sys_chunk_start, meta_chunk_start,
753                                   dev_bytenr);
754 out:
755         return ret;
756 }
757
758 /*
759  * @fs_uuid - if NULL, generates a UUID, returns back the new filesystem UUID
760  */
761 int make_btrfs(int fd, struct btrfs_mkfs_config *cfg,
762                 struct btrfs_convert_context *cctx)
763 {
764         struct btrfs_super_block super;
765         struct extent_buffer *buf;
766         struct btrfs_root_item root_item;
767         struct btrfs_disk_key disk_key;
768         struct btrfs_extent_item *extent_item;
769         struct btrfs_inode_item *inode_item;
770         struct btrfs_chunk *chunk;
771         struct btrfs_dev_item *dev_item;
772         struct btrfs_dev_extent *dev_extent;
773         u8 chunk_tree_uuid[BTRFS_UUID_SIZE];
774         u8 *ptr;
775         int i;
776         int ret;
777         u32 itemoff;
778         u32 nritems = 0;
779         u64 first_free;
780         u64 ref_root;
781         u32 array_size;
782         u32 item_size;
783         int skinny_metadata = !!(cfg->features &
784                                  BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA);
785         u64 num_bytes;
786
787         if (cctx)
788                 return make_convert_btrfs(fd, cfg, cctx);
789         buf = malloc(sizeof(*buf) + max(cfg->sectorsize, cfg->nodesize));
790         if (!buf)
791                 return -ENOMEM;
792
793         first_free = BTRFS_SUPER_INFO_OFFSET + cfg->sectorsize * 2 - 1;
794         first_free &= ~((u64)cfg->sectorsize - 1);
795
796         memset(&super, 0, sizeof(super));
797
798         num_bytes = (cfg->num_bytes / cfg->sectorsize) * cfg->sectorsize;
799         if (cfg->fs_uuid && *cfg->fs_uuid) {
800                 if (uuid_parse(cfg->fs_uuid, super.fsid) != 0) {
801                         error("cannot not parse UUID: %s", cfg->fs_uuid);
802                         ret = -EINVAL;
803                         goto out;
804                 }
805                 if (!test_uuid_unique(cfg->fs_uuid)) {
806                         error("non-unique UUID: %s", cfg->fs_uuid);
807                         ret = -EBUSY;
808                         goto out;
809                 }
810         } else {
811                 uuid_generate(super.fsid);
812                 if (cfg->fs_uuid)
813                         uuid_unparse(super.fsid, cfg->fs_uuid);
814         }
815         uuid_generate(super.dev_item.uuid);
816         uuid_generate(chunk_tree_uuid);
817
818         btrfs_set_super_bytenr(&super, cfg->blocks[0]);
819         btrfs_set_super_num_devices(&super, 1);
820         btrfs_set_super_magic(&super, BTRFS_MAGIC);
821         btrfs_set_super_generation(&super, 1);
822         btrfs_set_super_root(&super, cfg->blocks[1]);
823         btrfs_set_super_chunk_root(&super, cfg->blocks[3]);
824         btrfs_set_super_total_bytes(&super, num_bytes);
825         btrfs_set_super_bytes_used(&super, 6 * cfg->nodesize);
826         btrfs_set_super_sectorsize(&super, cfg->sectorsize);
827         btrfs_set_super_leafsize(&super, cfg->nodesize);
828         btrfs_set_super_nodesize(&super, cfg->nodesize);
829         btrfs_set_super_stripesize(&super, cfg->stripesize);
830         btrfs_set_super_csum_type(&super, BTRFS_CSUM_TYPE_CRC32);
831         btrfs_set_super_chunk_root_generation(&super, 1);
832         btrfs_set_super_cache_generation(&super, -1);
833         btrfs_set_super_incompat_flags(&super, cfg->features);
834         if (cfg->label)
835                 __strncpy_null(super.label, cfg->label, BTRFS_LABEL_SIZE - 1);
836
837         /* create the tree of root objects */
838         memset(buf->data, 0, cfg->nodesize);
839         buf->len = cfg->nodesize;
840         btrfs_set_header_bytenr(buf, cfg->blocks[1]);
841         btrfs_set_header_nritems(buf, 4);
842         btrfs_set_header_generation(buf, 1);
843         btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
844         btrfs_set_header_owner(buf, BTRFS_ROOT_TREE_OBJECTID);
845         write_extent_buffer(buf, super.fsid, btrfs_header_fsid(),
846                             BTRFS_FSID_SIZE);
847
848         write_extent_buffer(buf, chunk_tree_uuid,
849                             btrfs_header_chunk_tree_uuid(buf),
850                             BTRFS_UUID_SIZE);
851
852         /* create the items for the root tree */
853         memset(&root_item, 0, sizeof(root_item));
854         inode_item = &root_item.inode;
855         btrfs_set_stack_inode_generation(inode_item, 1);
856         btrfs_set_stack_inode_size(inode_item, 3);
857         btrfs_set_stack_inode_nlink(inode_item, 1);
858         btrfs_set_stack_inode_nbytes(inode_item, cfg->nodesize);
859         btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
860         btrfs_set_root_refs(&root_item, 1);
861         btrfs_set_root_used(&root_item, cfg->nodesize);
862         btrfs_set_root_generation(&root_item, 1);
863
864         memset(&disk_key, 0, sizeof(disk_key));
865         btrfs_set_disk_key_type(&disk_key, BTRFS_ROOT_ITEM_KEY);
866         btrfs_set_disk_key_offset(&disk_key, 0);
867         nritems = 0;
868
869         itemoff = __BTRFS_LEAF_DATA_SIZE(cfg->nodesize) - sizeof(root_item);
870         btrfs_set_root_bytenr(&root_item, cfg->blocks[2]);
871         btrfs_set_disk_key_objectid(&disk_key, BTRFS_EXTENT_TREE_OBJECTID);
872         btrfs_set_item_key(buf, &disk_key, nritems);
873         btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
874         btrfs_set_item_size(buf, btrfs_item_nr(nritems),
875                             sizeof(root_item));
876         write_extent_buffer(buf, &root_item, btrfs_item_ptr_offset(buf,
877                             nritems), sizeof(root_item));
878         nritems++;
879
880         itemoff = itemoff - sizeof(root_item);
881         btrfs_set_root_bytenr(&root_item, cfg->blocks[4]);
882         btrfs_set_disk_key_objectid(&disk_key, BTRFS_DEV_TREE_OBJECTID);
883         btrfs_set_item_key(buf, &disk_key, nritems);
884         btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
885         btrfs_set_item_size(buf, btrfs_item_nr(nritems),
886                             sizeof(root_item));
887         write_extent_buffer(buf, &root_item,
888                             btrfs_item_ptr_offset(buf, nritems),
889                             sizeof(root_item));
890         nritems++;
891
892         itemoff = itemoff - sizeof(root_item);
893         btrfs_set_root_bytenr(&root_item, cfg->blocks[5]);
894         btrfs_set_disk_key_objectid(&disk_key, BTRFS_FS_TREE_OBJECTID);
895         btrfs_set_item_key(buf, &disk_key, nritems);
896         btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
897         btrfs_set_item_size(buf, btrfs_item_nr(nritems),
898                             sizeof(root_item));
899         write_extent_buffer(buf, &root_item,
900                             btrfs_item_ptr_offset(buf, nritems),
901                             sizeof(root_item));
902         nritems++;
903
904         itemoff = itemoff - sizeof(root_item);
905         btrfs_set_root_bytenr(&root_item, cfg->blocks[6]);
906         btrfs_set_disk_key_objectid(&disk_key, BTRFS_CSUM_TREE_OBJECTID);
907         btrfs_set_item_key(buf, &disk_key, nritems);
908         btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
909         btrfs_set_item_size(buf, btrfs_item_nr(nritems),
910                             sizeof(root_item));
911         write_extent_buffer(buf, &root_item,
912                             btrfs_item_ptr_offset(buf, nritems),
913                             sizeof(root_item));
914         nritems++;
915
916
917         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
918         ret = pwrite(fd, buf->data, cfg->nodesize, cfg->blocks[1]);
919         if (ret != cfg->nodesize) {
920                 ret = (ret < 0 ? -errno : -EIO);
921                 goto out;
922         }
923
924         /* create the items for the extent tree */
925         memset(buf->data + sizeof(struct btrfs_header), 0,
926                 cfg->nodesize - sizeof(struct btrfs_header));
927         nritems = 0;
928         itemoff = __BTRFS_LEAF_DATA_SIZE(cfg->nodesize);
929         for (i = 1; i < 7; i++) {
930                 item_size = sizeof(struct btrfs_extent_item);
931                 if (!skinny_metadata)
932                         item_size += sizeof(struct btrfs_tree_block_info);
933
934                 BUG_ON(cfg->blocks[i] < first_free);
935                 BUG_ON(cfg->blocks[i] < cfg->blocks[i - 1]);
936
937                 /* create extent item */
938                 itemoff -= item_size;
939                 btrfs_set_disk_key_objectid(&disk_key, cfg->blocks[i]);
940                 if (skinny_metadata) {
941                         btrfs_set_disk_key_type(&disk_key,
942                                                 BTRFS_METADATA_ITEM_KEY);
943                         btrfs_set_disk_key_offset(&disk_key, 0);
944                 } else {
945                         btrfs_set_disk_key_type(&disk_key,
946                                                 BTRFS_EXTENT_ITEM_KEY);
947                         btrfs_set_disk_key_offset(&disk_key, cfg->nodesize);
948                 }
949                 btrfs_set_item_key(buf, &disk_key, nritems);
950                 btrfs_set_item_offset(buf, btrfs_item_nr(nritems),
951                                       itemoff);
952                 btrfs_set_item_size(buf, btrfs_item_nr(nritems),
953                                     item_size);
954                 extent_item = btrfs_item_ptr(buf, nritems,
955                                              struct btrfs_extent_item);
956                 btrfs_set_extent_refs(buf, extent_item, 1);
957                 btrfs_set_extent_generation(buf, extent_item, 1);
958                 btrfs_set_extent_flags(buf, extent_item,
959                                        BTRFS_EXTENT_FLAG_TREE_BLOCK);
960                 nritems++;
961
962                 /* create extent ref */
963                 ref_root = reference_root_table[i];
964                 btrfs_set_disk_key_objectid(&disk_key, cfg->blocks[i]);
965                 btrfs_set_disk_key_offset(&disk_key, ref_root);
966                 btrfs_set_disk_key_type(&disk_key, BTRFS_TREE_BLOCK_REF_KEY);
967                 btrfs_set_item_key(buf, &disk_key, nritems);
968                 btrfs_set_item_offset(buf, btrfs_item_nr(nritems),
969                                       itemoff);
970                 btrfs_set_item_size(buf, btrfs_item_nr(nritems), 0);
971                 nritems++;
972         }
973         btrfs_set_header_bytenr(buf, cfg->blocks[2]);
974         btrfs_set_header_owner(buf, BTRFS_EXTENT_TREE_OBJECTID);
975         btrfs_set_header_nritems(buf, nritems);
976         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
977         ret = pwrite(fd, buf->data, cfg->nodesize, cfg->blocks[2]);
978         if (ret != cfg->nodesize) {
979                 ret = (ret < 0 ? -errno : -EIO);
980                 goto out;
981         }
982
983         /* create the chunk tree */
984         memset(buf->data + sizeof(struct btrfs_header), 0,
985                 cfg->nodesize - sizeof(struct btrfs_header));
986         nritems = 0;
987         item_size = sizeof(*dev_item);
988         itemoff = __BTRFS_LEAF_DATA_SIZE(cfg->nodesize) - item_size;
989
990         /* first device 1 (there is no device 0) */
991         btrfs_set_disk_key_objectid(&disk_key, BTRFS_DEV_ITEMS_OBJECTID);
992         btrfs_set_disk_key_offset(&disk_key, 1);
993         btrfs_set_disk_key_type(&disk_key, BTRFS_DEV_ITEM_KEY);
994         btrfs_set_item_key(buf, &disk_key, nritems);
995         btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
996         btrfs_set_item_size(buf, btrfs_item_nr(nritems), item_size);
997
998         dev_item = btrfs_item_ptr(buf, nritems, struct btrfs_dev_item);
999         btrfs_set_device_id(buf, dev_item, 1);
1000         btrfs_set_device_generation(buf, dev_item, 0);
1001         btrfs_set_device_total_bytes(buf, dev_item, num_bytes);
1002         btrfs_set_device_bytes_used(buf, dev_item,
1003                                     BTRFS_MKFS_SYSTEM_GROUP_SIZE);
1004         btrfs_set_device_io_align(buf, dev_item, cfg->sectorsize);
1005         btrfs_set_device_io_width(buf, dev_item, cfg->sectorsize);
1006         btrfs_set_device_sector_size(buf, dev_item, cfg->sectorsize);
1007         btrfs_set_device_type(buf, dev_item, 0);
1008
1009         write_extent_buffer(buf, super.dev_item.uuid,
1010                             (unsigned long)btrfs_device_uuid(dev_item),
1011                             BTRFS_UUID_SIZE);
1012         write_extent_buffer(buf, super.fsid,
1013                             (unsigned long)btrfs_device_fsid(dev_item),
1014                             BTRFS_UUID_SIZE);
1015         read_extent_buffer(buf, &super.dev_item, (unsigned long)dev_item,
1016                            sizeof(*dev_item));
1017
1018         nritems++;
1019         item_size = btrfs_chunk_item_size(1);
1020         itemoff = itemoff - item_size;
1021
1022         /* then we have chunk 0 */
1023         btrfs_set_disk_key_objectid(&disk_key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1024         btrfs_set_disk_key_offset(&disk_key, 0);
1025         btrfs_set_disk_key_type(&disk_key, BTRFS_CHUNK_ITEM_KEY);
1026         btrfs_set_item_key(buf, &disk_key, nritems);
1027         btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
1028         btrfs_set_item_size(buf, btrfs_item_nr(nritems), item_size);
1029
1030         chunk = btrfs_item_ptr(buf, nritems, struct btrfs_chunk);
1031         btrfs_set_chunk_length(buf, chunk, BTRFS_MKFS_SYSTEM_GROUP_SIZE);
1032         btrfs_set_chunk_owner(buf, chunk, BTRFS_EXTENT_TREE_OBJECTID);
1033         btrfs_set_chunk_stripe_len(buf, chunk, 64 * 1024);
1034         btrfs_set_chunk_type(buf, chunk, BTRFS_BLOCK_GROUP_SYSTEM);
1035         btrfs_set_chunk_io_align(buf, chunk, cfg->sectorsize);
1036         btrfs_set_chunk_io_width(buf, chunk, cfg->sectorsize);
1037         btrfs_set_chunk_sector_size(buf, chunk, cfg->sectorsize);
1038         btrfs_set_chunk_num_stripes(buf, chunk, 1);
1039         btrfs_set_stripe_devid_nr(buf, chunk, 0, 1);
1040         btrfs_set_stripe_offset_nr(buf, chunk, 0, 0);
1041         nritems++;
1042
1043         write_extent_buffer(buf, super.dev_item.uuid,
1044                             (unsigned long)btrfs_stripe_dev_uuid(&chunk->stripe),
1045                             BTRFS_UUID_SIZE);
1046
1047         /* copy the key for the chunk to the system array */
1048         ptr = super.sys_chunk_array;
1049         array_size = sizeof(disk_key);
1050
1051         memcpy(ptr, &disk_key, sizeof(disk_key));
1052         ptr += sizeof(disk_key);
1053
1054         /* copy the chunk to the system array */
1055         read_extent_buffer(buf, ptr, (unsigned long)chunk, item_size);
1056         array_size += item_size;
1057         ptr += item_size;
1058         btrfs_set_super_sys_array_size(&super, array_size);
1059
1060         btrfs_set_header_bytenr(buf, cfg->blocks[3]);
1061         btrfs_set_header_owner(buf, BTRFS_CHUNK_TREE_OBJECTID);
1062         btrfs_set_header_nritems(buf, nritems);
1063         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
1064         ret = pwrite(fd, buf->data, cfg->nodesize, cfg->blocks[3]);
1065         if (ret != cfg->nodesize) {
1066                 ret = (ret < 0 ? -errno : -EIO);
1067                 goto out;
1068         }
1069
1070         /* create the device tree */
1071         memset(buf->data + sizeof(struct btrfs_header), 0,
1072                 cfg->nodesize - sizeof(struct btrfs_header));
1073         nritems = 0;
1074         itemoff = __BTRFS_LEAF_DATA_SIZE(cfg->nodesize) -
1075                 sizeof(struct btrfs_dev_extent);
1076
1077         btrfs_set_disk_key_objectid(&disk_key, 1);
1078         btrfs_set_disk_key_offset(&disk_key, 0);
1079         btrfs_set_disk_key_type(&disk_key, BTRFS_DEV_EXTENT_KEY);
1080         btrfs_set_item_key(buf, &disk_key, nritems);
1081         btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
1082         btrfs_set_item_size(buf, btrfs_item_nr(nritems),
1083                             sizeof(struct btrfs_dev_extent));
1084         dev_extent = btrfs_item_ptr(buf, nritems, struct btrfs_dev_extent);
1085         btrfs_set_dev_extent_chunk_tree(buf, dev_extent,
1086                                         BTRFS_CHUNK_TREE_OBJECTID);
1087         btrfs_set_dev_extent_chunk_objectid(buf, dev_extent,
1088                                         BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1089         btrfs_set_dev_extent_chunk_offset(buf, dev_extent, 0);
1090
1091         write_extent_buffer(buf, chunk_tree_uuid,
1092                     (unsigned long)btrfs_dev_extent_chunk_tree_uuid(dev_extent),
1093                     BTRFS_UUID_SIZE);
1094
1095         btrfs_set_dev_extent_length(buf, dev_extent,
1096                                     BTRFS_MKFS_SYSTEM_GROUP_SIZE);
1097         nritems++;
1098
1099         btrfs_set_header_bytenr(buf, cfg->blocks[4]);
1100         btrfs_set_header_owner(buf, BTRFS_DEV_TREE_OBJECTID);
1101         btrfs_set_header_nritems(buf, nritems);
1102         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
1103         ret = pwrite(fd, buf->data, cfg->nodesize, cfg->blocks[4]);
1104         if (ret != cfg->nodesize) {
1105                 ret = (ret < 0 ? -errno : -EIO);
1106                 goto out;
1107         }
1108
1109         /* create the FS root */
1110         memset(buf->data + sizeof(struct btrfs_header), 0,
1111                 cfg->nodesize - sizeof(struct btrfs_header));
1112         btrfs_set_header_bytenr(buf, cfg->blocks[5]);
1113         btrfs_set_header_owner(buf, BTRFS_FS_TREE_OBJECTID);
1114         btrfs_set_header_nritems(buf, 0);
1115         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
1116         ret = pwrite(fd, buf->data, cfg->nodesize, cfg->blocks[5]);
1117         if (ret != cfg->nodesize) {
1118                 ret = (ret < 0 ? -errno : -EIO);
1119                 goto out;
1120         }
1121         /* finally create the csum root */
1122         memset(buf->data + sizeof(struct btrfs_header), 0,
1123                 cfg->nodesize - sizeof(struct btrfs_header));
1124         btrfs_set_header_bytenr(buf, cfg->blocks[6]);
1125         btrfs_set_header_owner(buf, BTRFS_CSUM_TREE_OBJECTID);
1126         btrfs_set_header_nritems(buf, 0);
1127         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
1128         ret = pwrite(fd, buf->data, cfg->nodesize, cfg->blocks[6]);
1129         if (ret != cfg->nodesize) {
1130                 ret = (ret < 0 ? -errno : -EIO);
1131                 goto out;
1132         }
1133
1134         /* and write out the super block */
1135         BUG_ON(sizeof(super) > cfg->sectorsize);
1136         memset(buf->data, 0, BTRFS_SUPER_INFO_SIZE);
1137         memcpy(buf->data, &super, sizeof(super));
1138         buf->len = BTRFS_SUPER_INFO_SIZE;
1139         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
1140         ret = pwrite(fd, buf->data, BTRFS_SUPER_INFO_SIZE, cfg->blocks[0]);
1141         if (ret != BTRFS_SUPER_INFO_SIZE) {
1142                 ret = (ret < 0 ? -errno : -EIO);
1143                 goto out;
1144         }
1145
1146         ret = 0;
1147
1148 out:
1149         free(buf);
1150         return ret;
1151 }
1152
1153 static const struct btrfs_fs_feature {
1154         const char *name;
1155         u64 flag;
1156         const char *desc;
1157 } mkfs_features[] = {
1158         { "mixed-bg", BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS,
1159                 "mixed data and metadata block groups" },
1160         { "extref", BTRFS_FEATURE_INCOMPAT_EXTENDED_IREF,
1161                 "increased hardlink limit per file to 65536" },
1162         { "raid56", BTRFS_FEATURE_INCOMPAT_RAID56,
1163                 "raid56 extended format" },
1164         { "skinny-metadata", BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA,
1165                 "reduced-size metadata extent refs" },
1166         { "no-holes", BTRFS_FEATURE_INCOMPAT_NO_HOLES,
1167                 "no explicit hole extents for files" },
1168         /* Keep this one last */
1169         { "list-all", BTRFS_FEATURE_LIST_ALL, NULL }
1170 };
1171
1172 static int parse_one_fs_feature(const char *name, u64 *flags)
1173 {
1174         int i;
1175         int found = 0;
1176
1177         for (i = 0; i < ARRAY_SIZE(mkfs_features); i++) {
1178                 if (name[0] == '^' &&
1179                         !strcmp(mkfs_features[i].name, name + 1)) {
1180                         *flags &= ~ mkfs_features[i].flag;
1181                         found = 1;
1182                 } else if (!strcmp(mkfs_features[i].name, name)) {
1183                         *flags |= mkfs_features[i].flag;
1184                         found = 1;
1185                 }
1186         }
1187
1188         return !found;
1189 }
1190
1191 void btrfs_parse_features_to_string(char *buf, u64 flags)
1192 {
1193         int i;
1194
1195         buf[0] = 0;
1196
1197         for (i = 0; i < ARRAY_SIZE(mkfs_features); i++) {
1198                 if (flags & mkfs_features[i].flag) {
1199                         if (*buf)
1200                                 strcat(buf, ", ");
1201                         strcat(buf, mkfs_features[i].name);
1202                 }
1203         }
1204 }
1205
1206 void btrfs_process_fs_features(u64 flags)
1207 {
1208         int i;
1209
1210         for (i = 0; i < ARRAY_SIZE(mkfs_features); i++) {
1211                 if (flags & mkfs_features[i].flag) {
1212                         printf("Turning ON incompat feature '%s': %s\n",
1213                                 mkfs_features[i].name,
1214                                 mkfs_features[i].desc);
1215                 }
1216         }
1217 }
1218
1219 void btrfs_list_all_fs_features(u64 mask_disallowed)
1220 {
1221         int i;
1222
1223         fprintf(stderr, "Filesystem features available:\n");
1224         for (i = 0; i < ARRAY_SIZE(mkfs_features) - 1; i++) {
1225                 char *is_default = "";
1226
1227                 if (mkfs_features[i].flag & mask_disallowed)
1228                         continue;
1229                 if (mkfs_features[i].flag & BTRFS_MKFS_DEFAULT_FEATURES)
1230                         is_default = ", default";
1231                 fprintf(stderr, "%-20s- %s (0x%llx%s)\n",
1232                                 mkfs_features[i].name,
1233                                 mkfs_features[i].desc,
1234                                 mkfs_features[i].flag,
1235                                 is_default);
1236         }
1237 }
1238
1239 /*
1240  * Return NULL if all features were parsed fine, otherwise return the name of
1241  * the first unparsed.
1242  */
1243 char* btrfs_parse_fs_features(char *namelist, u64 *flags)
1244 {
1245         char *this_char;
1246         char *save_ptr = NULL; /* Satisfy static checkers */
1247
1248         for (this_char = strtok_r(namelist, ",", &save_ptr);
1249              this_char != NULL;
1250              this_char = strtok_r(NULL, ",", &save_ptr)) {
1251                 if (parse_one_fs_feature(this_char, flags))
1252                         return this_char;
1253         }
1254
1255         return NULL;
1256 }
1257
1258 u64 btrfs_device_size(int fd, struct stat *st)
1259 {
1260         u64 size;
1261         if (S_ISREG(st->st_mode)) {
1262                 return st->st_size;
1263         }
1264         if (!S_ISBLK(st->st_mode)) {
1265                 return 0;
1266         }
1267         if (ioctl(fd, BLKGETSIZE64, &size) >= 0) {
1268                 return size;
1269         }
1270         return 0;
1271 }
1272
1273 static int zero_blocks(int fd, off_t start, size_t len)
1274 {
1275         char *buf = malloc(len);
1276         int ret = 0;
1277         ssize_t written;
1278
1279         if (!buf)
1280                 return -ENOMEM;
1281         memset(buf, 0, len);
1282         written = pwrite(fd, buf, len, start);
1283         if (written != len)
1284                 ret = -EIO;
1285         free(buf);
1286         return ret;
1287 }
1288
1289 #define ZERO_DEV_BYTES (2 * 1024 * 1024)
1290
1291 /* don't write outside the device by clamping the region to the device size */
1292 static int zero_dev_clamped(int fd, off_t start, ssize_t len, u64 dev_size)
1293 {
1294         off_t end = max(start, start + len);
1295
1296 #ifdef __sparc__
1297         /* and don't overwrite the disk labels on sparc */
1298         start = max(start, 1024);
1299         end = max(end, 1024);
1300 #endif
1301
1302         start = min_t(u64, start, dev_size);
1303         end = min_t(u64, end, dev_size);
1304
1305         return zero_blocks(fd, start, end - start);
1306 }
1307
1308 int btrfs_add_to_fsid(struct btrfs_trans_handle *trans,
1309                       struct btrfs_root *root, int fd, char *path,
1310                       u64 device_total_bytes, u32 io_width, u32 io_align,
1311                       u32 sectorsize)
1312 {
1313         struct btrfs_super_block *disk_super;
1314         struct btrfs_super_block *super = root->fs_info->super_copy;
1315         struct btrfs_device *device;
1316         struct btrfs_dev_item *dev_item;
1317         char *buf = NULL;
1318         u64 fs_total_bytes;
1319         u64 num_devs;
1320         int ret;
1321
1322         device_total_bytes = (device_total_bytes / sectorsize) * sectorsize;
1323
1324         device = kzalloc(sizeof(*device), GFP_NOFS);
1325         if (!device)
1326                 goto err_nomem;
1327         buf = kzalloc(sectorsize, GFP_NOFS);
1328         if (!buf)
1329                 goto err_nomem;
1330         BUG_ON(sizeof(*disk_super) > sectorsize);
1331
1332         disk_super = (struct btrfs_super_block *)buf;
1333         dev_item = &disk_super->dev_item;
1334
1335         uuid_generate(device->uuid);
1336         device->devid = 0;
1337         device->type = 0;
1338         device->io_width = io_width;
1339         device->io_align = io_align;
1340         device->sector_size = sectorsize;
1341         device->fd = fd;
1342         device->writeable = 1;
1343         device->total_bytes = device_total_bytes;
1344         device->bytes_used = 0;
1345         device->total_ios = 0;
1346         device->dev_root = root->fs_info->dev_root;
1347         device->name = strdup(path);
1348         if (!device->name)
1349                 goto err_nomem;
1350
1351         INIT_LIST_HEAD(&device->dev_list);
1352         ret = btrfs_add_device(trans, root, device);
1353         BUG_ON(ret);
1354
1355         fs_total_bytes = btrfs_super_total_bytes(super) + device_total_bytes;
1356         btrfs_set_super_total_bytes(super, fs_total_bytes);
1357
1358         num_devs = btrfs_super_num_devices(super) + 1;
1359         btrfs_set_super_num_devices(super, num_devs);
1360
1361         memcpy(disk_super, super, sizeof(*disk_super));
1362
1363         btrfs_set_super_bytenr(disk_super, BTRFS_SUPER_INFO_OFFSET);
1364         btrfs_set_stack_device_id(dev_item, device->devid);
1365         btrfs_set_stack_device_type(dev_item, device->type);
1366         btrfs_set_stack_device_io_align(dev_item, device->io_align);
1367         btrfs_set_stack_device_io_width(dev_item, device->io_width);
1368         btrfs_set_stack_device_sector_size(dev_item, device->sector_size);
1369         btrfs_set_stack_device_total_bytes(dev_item, device->total_bytes);
1370         btrfs_set_stack_device_bytes_used(dev_item, device->bytes_used);
1371         memcpy(&dev_item->uuid, device->uuid, BTRFS_UUID_SIZE);
1372
1373         ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
1374         BUG_ON(ret != sectorsize);
1375
1376         kfree(buf);
1377         list_add(&device->dev_list, &root->fs_info->fs_devices->devices);
1378         device->fs_devices = root->fs_info->fs_devices;
1379         return 0;
1380
1381 err_nomem:
1382         kfree(device);
1383         kfree(buf);
1384         return -ENOMEM;
1385 }
1386
1387 static int btrfs_wipe_existing_sb(int fd)
1388 {
1389         const char *off = NULL;
1390         size_t len = 0;
1391         loff_t offset;
1392         char buf[BUFSIZ];
1393         int ret = 0;
1394         blkid_probe pr = NULL;
1395
1396         pr = blkid_new_probe();
1397         if (!pr)
1398                 return -1;
1399
1400         if (blkid_probe_set_device(pr, fd, 0, 0)) {
1401                 ret = -1;
1402                 goto out;
1403         }
1404
1405         ret = blkid_probe_lookup_value(pr, "SBMAGIC_OFFSET", &off, NULL);
1406         if (!ret)
1407                 ret = blkid_probe_lookup_value(pr, "SBMAGIC", NULL, &len);
1408
1409         if (ret || len == 0 || off == NULL) {
1410                 /*
1411                  * If lookup fails, the probe did not find any values, eg. for
1412                  * a file image or a loop device. Soft error.
1413                  */
1414                 ret = 1;
1415                 goto out;
1416         }
1417
1418         offset = strtoll(off, NULL, 10);
1419         if (len > sizeof(buf))
1420                 len = sizeof(buf);
1421
1422         memset(buf, 0, len);
1423         ret = pwrite(fd, buf, len, offset);
1424         if (ret < 0) {
1425                 error("cannot wipe existing superblock: %s", strerror(errno));
1426                 ret = -1;
1427         } else if (ret != len) {
1428                 error("cannot wipe existing superblock: wrote %d of %zd", ret, len);
1429                 ret = -1;
1430         }
1431         fsync(fd);
1432
1433 out:
1434         blkid_free_probe(pr);
1435         return ret;
1436 }
1437
1438 int btrfs_prepare_device(int fd, const char *file, int zero_end,
1439                 u64 *block_count_ret, u64 max_block_count, int discard)
1440 {
1441         u64 block_count;
1442         struct stat st;
1443         int i, ret;
1444
1445         ret = fstat(fd, &st);
1446         if (ret < 0) {
1447                 error("unable to stat %s: %s", file, strerror(errno));
1448                 return 1;
1449         }
1450
1451         block_count = btrfs_device_size(fd, &st);
1452         if (block_count == 0) {
1453                 error("unable to determine size of %s", file);
1454                 return 1;
1455         }
1456         if (max_block_count)
1457                 block_count = min(block_count, max_block_count);
1458
1459         if (discard) {
1460                 /*
1461                  * We intentionally ignore errors from the discard ioctl.  It
1462                  * is not necessary for the mkfs functionality but just an
1463                  * optimization.
1464                  */
1465                 if (discard_range(fd, 0, 0) == 0) {
1466                         printf("Performing full device TRIM (%s) ...\n",
1467                                 pretty_size(block_count));
1468                         discard_blocks(fd, 0, block_count);
1469                 }
1470         }
1471
1472         ret = zero_dev_clamped(fd, 0, ZERO_DEV_BYTES, block_count);
1473         for (i = 0 ; !ret && i < BTRFS_SUPER_MIRROR_MAX; i++)
1474                 ret = zero_dev_clamped(fd, btrfs_sb_offset(i),
1475                                        BTRFS_SUPER_INFO_SIZE, block_count);
1476         if (!ret && zero_end)
1477                 ret = zero_dev_clamped(fd, block_count - ZERO_DEV_BYTES,
1478                                        ZERO_DEV_BYTES, block_count);
1479
1480         if (ret < 0) {
1481                 error("failed to zero device '%s': %s", file, strerror(-ret));
1482                 return 1;
1483         }
1484
1485         ret = btrfs_wipe_existing_sb(fd);
1486         if (ret < 0) {
1487                 error("cannot wipe superblocks on %s", file);
1488                 return 1;
1489         }
1490
1491         *block_count_ret = block_count;
1492         return 0;
1493 }
1494
1495 int btrfs_make_root_dir(struct btrfs_trans_handle *trans,
1496                         struct btrfs_root *root, u64 objectid)
1497 {
1498         int ret;
1499         struct btrfs_inode_item inode_item;
1500         time_t now = time(NULL);
1501
1502         memset(&inode_item, 0, sizeof(inode_item));
1503         btrfs_set_stack_inode_generation(&inode_item, trans->transid);
1504         btrfs_set_stack_inode_size(&inode_item, 0);
1505         btrfs_set_stack_inode_nlink(&inode_item, 1);
1506         btrfs_set_stack_inode_nbytes(&inode_item, root->nodesize);
1507         btrfs_set_stack_inode_mode(&inode_item, S_IFDIR | 0755);
1508         btrfs_set_stack_timespec_sec(&inode_item.atime, now);
1509         btrfs_set_stack_timespec_nsec(&inode_item.atime, 0);
1510         btrfs_set_stack_timespec_sec(&inode_item.ctime, now);
1511         btrfs_set_stack_timespec_nsec(&inode_item.ctime, 0);
1512         btrfs_set_stack_timespec_sec(&inode_item.mtime, now);
1513         btrfs_set_stack_timespec_nsec(&inode_item.mtime, 0);
1514         btrfs_set_stack_timespec_sec(&inode_item.otime, 0);
1515         btrfs_set_stack_timespec_nsec(&inode_item.otime, 0);
1516
1517         if (root->fs_info->tree_root == root)
1518                 btrfs_set_super_root_dir(root->fs_info->super_copy, objectid);
1519
1520         ret = btrfs_insert_inode(trans, root, objectid, &inode_item);
1521         if (ret)
1522                 goto error;
1523
1524         ret = btrfs_insert_inode_ref(trans, root, "..", 2, objectid, objectid, 0);
1525         if (ret)
1526                 goto error;
1527
1528         btrfs_set_root_dirid(&root->root_item, objectid);
1529         ret = 0;
1530 error:
1531         return ret;
1532 }
1533
1534 /*
1535  * checks if a path is a block device node
1536  * Returns negative errno on failure, otherwise
1537  * returns 1 for blockdev, 0 for not-blockdev
1538  */
1539 int is_block_device(const char *path)
1540 {
1541         struct stat statbuf;
1542
1543         if (stat(path, &statbuf) < 0)
1544                 return -errno;
1545
1546         return !!S_ISBLK(statbuf.st_mode);
1547 }
1548
1549 /*
1550  * check if given path is a mount point
1551  * return 1 if yes. 0 if no. -1 for error
1552  */
1553 int is_mount_point(const char *path)
1554 {
1555         FILE *f;
1556         struct mntent *mnt;
1557         int ret = 0;
1558
1559         f = setmntent("/proc/self/mounts", "r");
1560         if (f == NULL)
1561                 return -1;
1562
1563         while ((mnt = getmntent(f)) != NULL) {
1564                 if (strcmp(mnt->mnt_dir, path))
1565                         continue;
1566                 ret = 1;
1567                 break;
1568         }
1569         endmntent(f);
1570         return ret;
1571 }
1572
1573 static int is_reg_file(const char *path)
1574 {
1575         struct stat statbuf;
1576
1577         if (stat(path, &statbuf) < 0)
1578                 return -errno;
1579         return S_ISREG(statbuf.st_mode);
1580 }
1581
1582 /*
1583  * This function checks if the given input parameter is
1584  * an uuid or a path
1585  * return <0 : some error in the given input
1586  * return BTRFS_ARG_UNKNOWN:    unknown input
1587  * return BTRFS_ARG_UUID:       given input is uuid
1588  * return BTRFS_ARG_MNTPOINT:   given input is path
1589  * return BTRFS_ARG_REG:        given input is regular file
1590  * return BTRFS_ARG_BLKDEV:     given input is block device
1591  */
1592 int check_arg_type(const char *input)
1593 {
1594         uuid_t uuid;
1595         char path[PATH_MAX];
1596
1597         if (!input)
1598                 return -EINVAL;
1599
1600         if (realpath(input, path)) {
1601                 if (is_block_device(path) == 1)
1602                         return BTRFS_ARG_BLKDEV;
1603
1604                 if (is_mount_point(path) == 1)
1605                         return BTRFS_ARG_MNTPOINT;
1606
1607                 if (is_reg_file(path))
1608                         return BTRFS_ARG_REG;
1609
1610                 return BTRFS_ARG_UNKNOWN;
1611         }
1612
1613         if (strlen(input) == (BTRFS_UUID_UNPARSED_SIZE - 1) &&
1614                 !uuid_parse(input, uuid))
1615                 return BTRFS_ARG_UUID;
1616
1617         return BTRFS_ARG_UNKNOWN;
1618 }
1619
1620 /*
1621  * Find the mount point for a mounted device.
1622  * On success, returns 0 with mountpoint in *mp.
1623  * On failure, returns -errno (not mounted yields -EINVAL)
1624  * Is noisy on failures, expects to be given a mounted device.
1625  */
1626 int get_btrfs_mount(const char *dev, char *mp, size_t mp_size)
1627 {
1628         int ret;
1629         int fd = -1;
1630
1631         ret = is_block_device(dev);
1632         if (ret <= 0) {
1633                 if (!ret) {
1634                         error("not a block device: %s", dev);
1635                         ret = -EINVAL;
1636                 } else {
1637                         error("cannot check %s: %s", dev, strerror(-ret));
1638                 }
1639                 goto out;
1640         }
1641
1642         fd = open(dev, O_RDONLY);
1643         if (fd < 0) {
1644                 ret = -errno;
1645                 error("cannot open %s: %s", dev, strerror(errno));
1646                 goto out;
1647         }
1648
1649         ret = check_mounted_where(fd, dev, mp, mp_size, NULL);
1650         if (!ret) {
1651                 ret = -EINVAL;
1652         } else { /* mounted, all good */
1653                 ret = 0;
1654         }
1655 out:
1656         if (fd != -1)
1657                 close(fd);
1658         return ret;
1659 }
1660
1661 /*
1662  * Given a pathname, return a filehandle to:
1663  *      the original pathname or,
1664  *      if the pathname is a mounted btrfs device, to its mountpoint.
1665  *
1666  * On error, return -1, errno should be set.
1667  */
1668 int open_path_or_dev_mnt(const char *path, DIR **dirstream, int verbose)
1669 {
1670         char mp[PATH_MAX];
1671         int ret;
1672
1673         if (is_block_device(path)) {
1674                 ret = get_btrfs_mount(path, mp, sizeof(mp));
1675                 if (ret < 0) {
1676                         /* not a mounted btrfs dev */
1677                         error_on(verbose, "'%s' is not a mounted btrfs device",
1678                                  path);
1679                         errno = EINVAL;
1680                         return -1;
1681                 }
1682                 ret = open_file_or_dir(mp, dirstream);
1683                 error_on(verbose && ret < 0, "can't access '%s': %s",
1684                          path, strerror(errno));
1685         } else {
1686                 ret = btrfs_open_dir(path, dirstream, 1);
1687         }
1688
1689         return ret;
1690 }
1691
1692 /*
1693  * Do the following checks before calling open_file_or_dir():
1694  * 1: path is in a btrfs filesystem
1695  * 2: path is a directory
1696  */
1697 int btrfs_open_dir(const char *path, DIR **dirstream, int verbose)
1698 {
1699         struct statfs stfs;
1700         struct stat st;
1701         int ret;
1702
1703         if (statfs(path, &stfs) != 0) {
1704                 error_on(verbose, "cannot access '%s': %s", path,
1705                                 strerror(errno));
1706                 return -1;
1707         }
1708
1709         if (stfs.f_type != BTRFS_SUPER_MAGIC) {
1710                 error_on(verbose, "not a btrfs filesystem: %s", path);
1711                 return -2;
1712         }
1713
1714         if (stat(path, &st) != 0) {
1715                 error_on(verbose, "cannot access '%s': %s", path,
1716                                 strerror(errno));
1717                 return -1;
1718         }
1719
1720         if (!S_ISDIR(st.st_mode)) {
1721                 error_on(verbose, "not a directory: %s", path);
1722                 return -3;
1723         }
1724
1725         ret = open_file_or_dir(path, dirstream);
1726         if (ret < 0) {
1727                 error_on(verbose, "cannot access '%s': %s", path,
1728                                 strerror(errno));
1729         }
1730
1731         return ret;
1732 }
1733
1734 /* checks if a device is a loop device */
1735 static int is_loop_device (const char* device) {
1736         struct stat statbuf;
1737
1738         if(stat(device, &statbuf) < 0)
1739                 return -errno;
1740
1741         return (S_ISBLK(statbuf.st_mode) &&
1742                 MAJOR(statbuf.st_rdev) == LOOP_MAJOR);
1743 }
1744
1745 /*
1746  * Takes a loop device path (e.g. /dev/loop0) and returns
1747  * the associated file (e.g. /images/my_btrfs.img) using
1748  * loopdev API
1749  */
1750 static int resolve_loop_device_with_loopdev(const char* loop_dev, char* loop_file)
1751 {
1752         int fd;
1753         int ret;
1754         struct loop_info64 lo64;
1755
1756         fd = open(loop_dev, O_RDONLY | O_NONBLOCK);
1757         if (fd < 0)
1758                 return -errno;
1759         ret = ioctl(fd, LOOP_GET_STATUS64, &lo64);
1760         if (ret < 0) {
1761                 ret = -errno;
1762                 goto out;
1763         }
1764
1765         memcpy(loop_file, lo64.lo_file_name, sizeof(lo64.lo_file_name));
1766         loop_file[sizeof(lo64.lo_file_name)] = 0;
1767
1768 out:
1769         close(fd);
1770
1771         return ret;
1772 }
1773
1774 /* Takes a loop device path (e.g. /dev/loop0) and returns
1775  * the associated file (e.g. /images/my_btrfs.img) */
1776 static int resolve_loop_device(const char* loop_dev, char* loop_file,
1777                 int max_len)
1778 {
1779         int ret;
1780         FILE *f;
1781         char fmt[20];
1782         char p[PATH_MAX];
1783         char real_loop_dev[PATH_MAX];
1784
1785         if (!realpath(loop_dev, real_loop_dev))
1786                 return -errno;
1787         snprintf(p, PATH_MAX, "/sys/block/%s/loop/backing_file", strrchr(real_loop_dev, '/'));
1788         if (!(f = fopen(p, "r"))) {
1789                 if (errno == ENOENT)
1790                         /*
1791                          * It's possibly a partitioned loop device, which is
1792                          * resolvable with loopdev API.
1793                          */
1794                         return resolve_loop_device_with_loopdev(loop_dev, loop_file);
1795                 return -errno;
1796         }
1797
1798         snprintf(fmt, 20, "%%%i[^\n]", max_len-1);
1799         ret = fscanf(f, fmt, loop_file);
1800         fclose(f);
1801         if (ret == EOF)
1802                 return -errno;
1803
1804         return 0;
1805 }
1806
1807 /*
1808  * Checks whether a and b are identical or device
1809  * files associated with the same block device
1810  */
1811 static int is_same_blk_file(const char* a, const char* b)
1812 {
1813         struct stat st_buf_a, st_buf_b;
1814         char real_a[PATH_MAX];
1815         char real_b[PATH_MAX];
1816
1817         if (!realpath(a, real_a))
1818                 strncpy_null(real_a, a);
1819
1820         if (!realpath(b, real_b))
1821                 strncpy_null(real_b, b);
1822
1823         /* Identical path? */
1824         if (strcmp(real_a, real_b) == 0)
1825                 return 1;
1826
1827         if (stat(a, &st_buf_a) < 0 || stat(b, &st_buf_b) < 0) {
1828                 if (errno == ENOENT)
1829                         return 0;
1830                 return -errno;
1831         }
1832
1833         /* Same blockdevice? */
1834         if (S_ISBLK(st_buf_a.st_mode) && S_ISBLK(st_buf_b.st_mode) &&
1835             st_buf_a.st_rdev == st_buf_b.st_rdev) {
1836                 return 1;
1837         }
1838
1839         /* Hardlink? */
1840         if (st_buf_a.st_dev == st_buf_b.st_dev &&
1841             st_buf_a.st_ino == st_buf_b.st_ino) {
1842                 return 1;
1843         }
1844
1845         return 0;
1846 }
1847
1848 /* checks if a and b are identical or device
1849  * files associated with the same block device or
1850  * if one file is a loop device that uses the other
1851  * file.
1852  */
1853 static int is_same_loop_file(const char* a, const char* b)
1854 {
1855         char res_a[PATH_MAX];
1856         char res_b[PATH_MAX];
1857         const char* final_a = NULL;
1858         const char* final_b = NULL;
1859         int ret;
1860
1861         /* Resolve a if it is a loop device */
1862         if((ret = is_loop_device(a)) < 0) {
1863                 if (ret == -ENOENT)
1864                         return 0;
1865                 return ret;
1866         } else if (ret) {
1867                 ret = resolve_loop_device(a, res_a, sizeof(res_a));
1868                 if (ret < 0) {
1869                         if (errno != EPERM)
1870                                 return ret;
1871                 } else {
1872                         final_a = res_a;
1873                 }
1874         } else {
1875                 final_a = a;
1876         }
1877
1878         /* Resolve b if it is a loop device */
1879         if ((ret = is_loop_device(b)) < 0) {
1880                 if (ret == -ENOENT)
1881                         return 0;
1882                 return ret;
1883         } else if (ret) {
1884                 ret = resolve_loop_device(b, res_b, sizeof(res_b));
1885                 if (ret < 0) {
1886                         if (errno != EPERM)
1887                                 return ret;
1888                 } else {
1889                         final_b = res_b;
1890                 }
1891         } else {
1892                 final_b = b;
1893         }
1894
1895         return is_same_blk_file(final_a, final_b);
1896 }
1897
1898 /* Checks if a file exists and is a block or regular file*/
1899 static int is_existing_blk_or_reg_file(const char* filename)
1900 {
1901         struct stat st_buf;
1902
1903         if(stat(filename, &st_buf) < 0) {
1904                 if(errno == ENOENT)
1905                         return 0;
1906                 else
1907                         return -errno;
1908         }
1909
1910         return (S_ISBLK(st_buf.st_mode) || S_ISREG(st_buf.st_mode));
1911 }
1912
1913 /* Checks if a file is used (directly or indirectly via a loop device)
1914  * by a device in fs_devices
1915  */
1916 static int blk_file_in_dev_list(struct btrfs_fs_devices* fs_devices,
1917                 const char* file)
1918 {
1919         int ret;
1920         struct list_head *head;
1921         struct list_head *cur;
1922         struct btrfs_device *device;
1923
1924         head = &fs_devices->devices;
1925         list_for_each(cur, head) {
1926                 device = list_entry(cur, struct btrfs_device, dev_list);
1927
1928                 if((ret = is_same_loop_file(device->name, file)))
1929                         return ret;
1930         }
1931
1932         return 0;
1933 }
1934
1935 /*
1936  * Resolve a pathname to a device mapper node to /dev/mapper/<name>
1937  * Returns NULL on invalid input or malloc failure; Other failures
1938  * will be handled by the caller using the input pathame.
1939  */
1940 char *canonicalize_dm_name(const char *ptname)
1941 {
1942         FILE    *f;
1943         size_t  sz;
1944         char    path[PATH_MAX], name[PATH_MAX], *res = NULL;
1945
1946         if (!ptname || !*ptname)
1947                 return NULL;
1948
1949         snprintf(path, sizeof(path), "/sys/block/%s/dm/name", ptname);
1950         if (!(f = fopen(path, "r")))
1951                 return NULL;
1952
1953         /* read <name>\n from sysfs */
1954         if (fgets(name, sizeof(name), f) && (sz = strlen(name)) > 1) {
1955                 name[sz - 1] = '\0';
1956                 snprintf(path, sizeof(path), "/dev/mapper/%s", name);
1957
1958                 if (access(path, F_OK) == 0)
1959                         res = strdup(path);
1960         }
1961         fclose(f);
1962         return res;
1963 }
1964
1965 /*
1966  * Resolve a pathname to a canonical device node, e.g. /dev/sda1 or
1967  * to a device mapper pathname.
1968  * Returns NULL on invalid input or malloc failure; Other failures
1969  * will be handled by the caller using the input pathame.
1970  */
1971 char *canonicalize_path(const char *path)
1972 {
1973         char *canonical, *p;
1974
1975         if (!path || !*path)
1976                 return NULL;
1977
1978         canonical = realpath(path, NULL);
1979         if (!canonical)
1980                 return strdup(path);
1981         p = strrchr(canonical, '/');
1982         if (p && strncmp(p, "/dm-", 4) == 0 && isdigit(*(p + 4))) {
1983                 char *dm = canonicalize_dm_name(p + 1);
1984
1985                 if (dm) {
1986                         free(canonical);
1987                         return dm;
1988                 }
1989         }
1990         return canonical;
1991 }
1992
1993 /*
1994  * returns 1 if the device was mounted, < 0 on error or 0 if everything
1995  * is safe to continue.
1996  */
1997 int check_mounted(const char* file)
1998 {
1999         int fd;
2000         int ret;
2001
2002         fd = open(file, O_RDONLY);
2003         if (fd < 0) {
2004                 error("mount check: cannot open %s: %s", file,
2005                                 strerror(errno));
2006                 return -errno;
2007         }
2008
2009         ret =  check_mounted_where(fd, file, NULL, 0, NULL);
2010         close(fd);
2011
2012         return ret;
2013 }
2014
2015 int check_mounted_where(int fd, const char *file, char *where, int size,
2016                         struct btrfs_fs_devices **fs_dev_ret)
2017 {
2018         int ret;
2019         u64 total_devs = 1;
2020         int is_btrfs;
2021         struct btrfs_fs_devices *fs_devices_mnt = NULL;
2022         FILE *f;
2023         struct mntent *mnt;
2024
2025         /* scan the initial device */
2026         ret = btrfs_scan_one_device(fd, file, &fs_devices_mnt,
2027                                     &total_devs, BTRFS_SUPER_INFO_OFFSET, 0);
2028         is_btrfs = (ret >= 0);
2029
2030         /* scan other devices */
2031         if (is_btrfs && total_devs > 1) {
2032                 ret = btrfs_scan_lblkid();
2033                 if (ret)
2034                         return ret;
2035         }
2036
2037         /* iterate over the list of currently mounted filesystems */
2038         if ((f = setmntent ("/proc/self/mounts", "r")) == NULL)
2039                 return -errno;
2040
2041         while ((mnt = getmntent (f)) != NULL) {
2042                 if(is_btrfs) {
2043                         if(strcmp(mnt->mnt_type, "btrfs") != 0)
2044                                 continue;
2045
2046                         ret = blk_file_in_dev_list(fs_devices_mnt, mnt->mnt_fsname);
2047                 } else {
2048                         /* ignore entries in the mount table that are not
2049                            associated with a file*/
2050                         if((ret = is_existing_blk_or_reg_file(mnt->mnt_fsname)) < 0)
2051                                 goto out_mntloop_err;
2052                         else if(!ret)
2053                                 continue;
2054
2055                         ret = is_same_loop_file(file, mnt->mnt_fsname);
2056                 }
2057
2058                 if(ret < 0)
2059                         goto out_mntloop_err;
2060                 else if(ret)
2061                         break;
2062         }
2063
2064         /* Did we find an entry in mnt table? */
2065         if (mnt && size && where) {
2066                 strncpy(where, mnt->mnt_dir, size);
2067                 where[size-1] = 0;
2068         }
2069         if (fs_dev_ret)
2070                 *fs_dev_ret = fs_devices_mnt;
2071
2072         ret = (mnt != NULL);
2073
2074 out_mntloop_err:
2075         endmntent (f);
2076
2077         return ret;
2078 }
2079
2080 struct pending_dir {
2081         struct list_head list;
2082         char name[PATH_MAX];
2083 };
2084
2085 int btrfs_register_one_device(const char *fname)
2086 {
2087         struct btrfs_ioctl_vol_args args;
2088         int fd;
2089         int ret;
2090
2091         fd = open("/dev/btrfs-control", O_RDWR);
2092         if (fd < 0) {
2093                 warning(
2094         "failed to open /dev/btrfs-control, skipping device registration: %s",
2095                         strerror(errno));
2096                 return -errno;
2097         }
2098         memset(&args, 0, sizeof(args));
2099         strncpy_null(args.name, fname);
2100         ret = ioctl(fd, BTRFS_IOC_SCAN_DEV, &args);
2101         if (ret < 0) {
2102                 error("device scan failed on '%s': %s", fname,
2103                                 strerror(errno));
2104                 ret = -errno;
2105         }
2106         close(fd);
2107         return ret;
2108 }
2109
2110 /*
2111  * Register all devices in the fs_uuid list created in the user
2112  * space. Ensure btrfs_scan_lblkid() is called before this func.
2113  */
2114 int btrfs_register_all_devices(void)
2115 {
2116         int err = 0;
2117         int ret = 0;
2118         struct btrfs_fs_devices *fs_devices;
2119         struct btrfs_device *device;
2120         struct list_head *all_uuids;
2121
2122         all_uuids = btrfs_scanned_uuids();
2123
2124         list_for_each_entry(fs_devices, all_uuids, list) {
2125                 list_for_each_entry(device, &fs_devices->devices, dev_list) {
2126                         if (*device->name)
2127                                 err = btrfs_register_one_device(device->name);
2128
2129                         if (err)
2130                                 ret++;
2131                 }
2132         }
2133
2134         return ret;
2135 }
2136
2137 int btrfs_device_already_in_root(struct btrfs_root *root, int fd,
2138                                  int super_offset)
2139 {
2140         struct btrfs_super_block *disk_super;
2141         char *buf;
2142         int ret = 0;
2143
2144         buf = malloc(BTRFS_SUPER_INFO_SIZE);
2145         if (!buf) {
2146                 ret = -ENOMEM;
2147                 goto out;
2148         }
2149         ret = pread(fd, buf, BTRFS_SUPER_INFO_SIZE, super_offset);
2150         if (ret != BTRFS_SUPER_INFO_SIZE)
2151                 goto brelse;
2152
2153         ret = 0;
2154         disk_super = (struct btrfs_super_block *)buf;
2155         if (btrfs_super_magic(disk_super) != BTRFS_MAGIC)
2156                 goto brelse;
2157
2158         if (!memcmp(disk_super->fsid, root->fs_info->super_copy->fsid,
2159                     BTRFS_FSID_SIZE))
2160                 ret = 1;
2161 brelse:
2162         free(buf);
2163 out:
2164         return ret;
2165 }
2166
2167 /*
2168  * Note: this function uses a static per-thread buffer. Do not call this
2169  * function more than 10 times within one argument list!
2170  */
2171 const char *pretty_size_mode(u64 size, unsigned mode)
2172 {
2173         static __thread int ps_index = 0;
2174         static __thread char ps_array[10][32];
2175         char *ret;
2176
2177         ret = ps_array[ps_index];
2178         ps_index++;
2179         ps_index %= 10;
2180         (void)pretty_size_snprintf(size, ret, 32, mode);
2181
2182         return ret;
2183 }
2184
2185 static const char* unit_suffix_binary[] =
2186         { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"};
2187 static const char* unit_suffix_decimal[] =
2188         { "B", "kB", "MB", "GB", "TB", "PB", "EB"};
2189
2190 int pretty_size_snprintf(u64 size, char *str, size_t str_size, unsigned unit_mode)
2191 {
2192         int num_divs;
2193         float fraction;
2194         u64 base = 0;
2195         int mult = 0;
2196         const char** suffix = NULL;
2197         u64 last_size;
2198
2199         if (str_size == 0)
2200                 return 0;
2201
2202         if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_RAW) {
2203                 snprintf(str, str_size, "%llu", size);
2204                 return 0;
2205         }
2206
2207         if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_BINARY) {
2208                 base = 1024;
2209                 mult = 1024;
2210                 suffix = unit_suffix_binary;
2211         } else if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_DECIMAL) {
2212                 base = 1000;
2213                 mult = 1000;
2214                 suffix = unit_suffix_decimal;
2215         }
2216
2217         /* Unknown mode */
2218         if (!base) {
2219                 fprintf(stderr, "INTERNAL ERROR: unknown unit base, mode %d\n",
2220                                 unit_mode);
2221                 assert(0);
2222                 return -1;
2223         }
2224
2225         num_divs = 0;
2226         last_size = size;
2227         switch (unit_mode & UNITS_MODE_MASK) {
2228         case UNITS_TBYTES: base *= mult; num_divs++;
2229         case UNITS_GBYTES: base *= mult; num_divs++;
2230         case UNITS_MBYTES: base *= mult; num_divs++;
2231         case UNITS_KBYTES: num_divs++;
2232                            break;
2233         case UNITS_BYTES:
2234                            base = 1;
2235                            num_divs = 0;
2236                            break;
2237         default:
2238                 while (size >= mult) {
2239                         last_size = size;
2240                         size /= mult;
2241                         num_divs++;
2242                 }
2243                 /*
2244                  * If the value is smaller than base, we didn't do any
2245                  * division, in that case, base should be 1, not original
2246                  * base, or the unit will be wrong
2247                  */
2248                 if (num_divs == 0)
2249                         base = 1;
2250         }
2251
2252         if (num_divs >= ARRAY_SIZE(unit_suffix_binary)) {
2253                 str[0] = '\0';
2254                 printf("INTERNAL ERROR: unsupported unit suffix, index %d\n",
2255                                 num_divs);
2256                 assert(0);
2257                 return -1;
2258         }
2259         fraction = (float)last_size / base;
2260
2261         return snprintf(str, str_size, "%.2f%s", fraction, suffix[num_divs]);
2262 }
2263
2264 /*
2265  * __strncpy_null - strncpy with null termination
2266  * @dest:       the target array
2267  * @src:        the source string
2268  * @n:          maximum bytes to copy (size of *dest)
2269  *
2270  * Like strncpy, but ensures destination is null-terminated.
2271  *
2272  * Copies the string pointed to by src, including the terminating null
2273  * byte ('\0'), to the buffer pointed to by dest, up to a maximum
2274  * of n bytes.  Then ensure that dest is null-terminated.
2275  */
2276 char *__strncpy_null(char *dest, const char *src, size_t n)
2277 {
2278         strncpy(dest, src, n);
2279         if (n > 0)
2280                 dest[n - 1] = '\0';
2281         return dest;
2282 }
2283
2284 /*
2285  * Checks to make sure that the label matches our requirements.
2286  * Returns:
2287        0    if everything is safe and usable
2288       -1    if the label is too long
2289  */
2290 static int check_label(const char *input)
2291 {
2292        int len = strlen(input);
2293
2294        if (len > BTRFS_LABEL_SIZE - 1) {
2295                 error("label %s is too long (max %d)", input,
2296                                 BTRFS_LABEL_SIZE - 1);
2297                return -1;
2298        }
2299
2300        return 0;
2301 }
2302
2303 static int set_label_unmounted(const char *dev, const char *label)
2304 {
2305         struct btrfs_trans_handle *trans;
2306         struct btrfs_root *root;
2307         int ret;
2308
2309         ret = check_mounted(dev);
2310         if (ret < 0) {
2311                error("checking mount status of %s failed: %d", dev, ret);
2312                return -1;
2313         }
2314         if (ret > 0) {
2315                 error("device %s is mounted, use mount point", dev);
2316                 return -1;
2317         }
2318
2319         /* Open the super_block at the default location
2320          * and as read-write.
2321          */
2322         root = open_ctree(dev, 0, OPEN_CTREE_WRITES);
2323         if (!root) /* errors are printed by open_ctree() */
2324                 return -1;
2325
2326         trans = btrfs_start_transaction(root, 1);
2327         __strncpy_null(root->fs_info->super_copy->label, label, BTRFS_LABEL_SIZE - 1);
2328
2329         btrfs_commit_transaction(trans, root);
2330
2331         /* Now we close it since we are done. */
2332         close_ctree(root);
2333         return 0;
2334 }
2335
2336 static int set_label_mounted(const char *mount_path, const char *labelp)
2337 {
2338         int fd;
2339         char label[BTRFS_LABEL_SIZE];
2340
2341         fd = open(mount_path, O_RDONLY | O_NOATIME);
2342         if (fd < 0) {
2343                 error("unable to access %s: %s", mount_path, strerror(errno));
2344                 return -1;
2345         }
2346
2347         memset(label, 0, sizeof(label));
2348         __strncpy_null(label, labelp, BTRFS_LABEL_SIZE - 1);
2349         if (ioctl(fd, BTRFS_IOC_SET_FSLABEL, label) < 0) {
2350                 error("unable to set label of %s: %s", mount_path,
2351                                 strerror(errno));
2352                 close(fd);
2353                 return -1;
2354         }
2355
2356         close(fd);
2357         return 0;
2358 }
2359
2360 int get_label_unmounted(const char *dev, char *label)
2361 {
2362         struct btrfs_root *root;
2363         int ret;
2364
2365         ret = check_mounted(dev);
2366         if (ret < 0) {
2367                error("checking mount status of %s failed: %d", dev, ret);
2368                return -1;
2369         }
2370
2371         /* Open the super_block at the default location
2372          * and as read-only.
2373          */
2374         root = open_ctree(dev, 0, 0);
2375         if(!root)
2376                 return -1;
2377
2378         __strncpy_null(label, root->fs_info->super_copy->label,
2379                         BTRFS_LABEL_SIZE - 1);
2380
2381         /* Now we close it since we are done. */
2382         close_ctree(root);
2383         return 0;
2384 }
2385
2386 /*
2387  * If a partition is mounted, try to get the filesystem label via its
2388  * mounted path rather than device.  Return the corresponding error
2389  * the user specified the device path.
2390  */
2391 int get_label_mounted(const char *mount_path, char *labelp)
2392 {
2393         char label[BTRFS_LABEL_SIZE];
2394         int fd;
2395         int ret;
2396
2397         fd = open(mount_path, O_RDONLY | O_NOATIME);
2398         if (fd < 0) {
2399                 error("unable to access %s: %s", mount_path, strerror(errno));
2400                 return -1;
2401         }
2402
2403         memset(label, '\0', sizeof(label));
2404         ret = ioctl(fd, BTRFS_IOC_GET_FSLABEL, label);
2405         if (ret < 0) {
2406                 if (errno != ENOTTY)
2407                         error("unable to get label of %s: %s", mount_path,
2408                                         strerror(errno));
2409                 ret = -errno;
2410                 close(fd);
2411                 return ret;
2412         }
2413
2414         __strncpy_null(labelp, label, BTRFS_LABEL_SIZE - 1);
2415         close(fd);
2416         return 0;
2417 }
2418
2419 int get_label(const char *btrfs_dev, char *label)
2420 {
2421         int ret;
2422
2423         ret = is_existing_blk_or_reg_file(btrfs_dev);
2424         if (!ret)
2425                 ret = get_label_mounted(btrfs_dev, label);
2426         else if (ret > 0)
2427                 ret = get_label_unmounted(btrfs_dev, label);
2428
2429         return ret;
2430 }
2431
2432 int set_label(const char *btrfs_dev, const char *label)
2433 {
2434         int ret;
2435
2436         if (check_label(label))
2437                 return -1;
2438
2439         ret = is_existing_blk_or_reg_file(btrfs_dev);
2440         if (!ret)
2441                 ret = set_label_mounted(btrfs_dev, label);
2442         else if (ret > 0)
2443                 ret = set_label_unmounted(btrfs_dev, label);
2444
2445         return ret;
2446 }
2447
2448 /*
2449  * A not-so-good version fls64. No fascinating optimization since
2450  * no one except parse_size use it
2451  */
2452 static int fls64(u64 x)
2453 {
2454         int i;
2455
2456         for (i = 0; i <64; i++)
2457                 if (x << i & (1ULL << 63))
2458                         return 64 - i;
2459         return 64 - i;
2460 }
2461
2462 u64 parse_size(char *s)
2463 {
2464         char c;
2465         char *endptr;
2466         u64 mult = 1;
2467         u64 ret;
2468
2469         if (!s) {
2470                 error("size value is empty");
2471                 exit(1);
2472         }
2473         if (s[0] == '-') {
2474                 error("size value '%s' is less equal than 0", s);
2475                 exit(1);
2476         }
2477         ret = strtoull(s, &endptr, 10);
2478         if (endptr == s) {
2479                 error("size value '%s' is invalid", s);
2480                 exit(1);
2481         }
2482         if (endptr[0] && endptr[1]) {
2483                 error("illegal suffix contains character '%c' in wrong position",
2484                         endptr[1]);
2485                 exit(1);
2486         }
2487         /*
2488          * strtoll returns LLONG_MAX when overflow, if this happens,
2489          * need to call strtoull to get the real size
2490          */
2491         if (errno == ERANGE && ret == ULLONG_MAX) {
2492                 error("size value '%s' is too large for u64", s);
2493                 exit(1);
2494         }
2495         if (endptr[0]) {
2496                 c = tolower(endptr[0]);
2497                 switch (c) {
2498                 case 'e':
2499                         mult *= 1024;
2500                         /* fallthrough */
2501                 case 'p':
2502                         mult *= 1024;
2503                         /* fallthrough */
2504                 case 't':
2505                         mult *= 1024;
2506                         /* fallthrough */
2507                 case 'g':
2508                         mult *= 1024;
2509                         /* fallthrough */
2510                 case 'm':
2511                         mult *= 1024;
2512                         /* fallthrough */
2513                 case 'k':
2514                         mult *= 1024;
2515                         /* fallthrough */
2516                 case 'b':
2517                         break;
2518                 default:
2519                         error("unknown size descriptor '%c'", c);
2520                         exit(1);
2521                 }
2522         }
2523         /* Check whether ret * mult overflow */
2524         if (fls64(ret) + fls64(mult) - 1 > 64) {
2525                 error("size value '%s' is too large for u64", s);
2526                 exit(1);
2527         }
2528         ret *= mult;
2529         return ret;
2530 }
2531
2532 u64 parse_qgroupid(const char *p)
2533 {
2534         char *s = strchr(p, '/');
2535         const char *ptr_src_end = p + strlen(p);
2536         char *ptr_parse_end = NULL;
2537         u64 level;
2538         u64 id;
2539         int fd;
2540         int ret = 0;
2541
2542         if (p[0] == '/')
2543                 goto path;
2544
2545         /* Numeric format like '0/257' is the primary case */
2546         if (!s) {
2547                 id = strtoull(p, &ptr_parse_end, 10);
2548                 if (ptr_parse_end != ptr_src_end)
2549                         goto path;
2550                 return id;
2551         }
2552         level = strtoull(p, &ptr_parse_end, 10);
2553         if (ptr_parse_end != s)
2554                 goto path;
2555
2556         id = strtoull(s + 1, &ptr_parse_end, 10);
2557         if (ptr_parse_end != ptr_src_end)
2558                 goto  path;
2559
2560         return (level << BTRFS_QGROUP_LEVEL_SHIFT) | id;
2561
2562 path:
2563         /* Path format like subv at 'my_subvol' is the fallback case */
2564         ret = test_issubvolume(p);
2565         if (ret < 0 || !ret)
2566                 goto err;
2567         fd = open(p, O_RDONLY);
2568         if (fd < 0)
2569                 goto err;
2570         ret = lookup_ino_rootid(fd, &id);
2571         close(fd);
2572         if (ret < 0)
2573                 goto err;
2574         return id;
2575
2576 err:
2577         error("invalid qgroupid or subvolume path: %s", p);
2578         exit(-1);
2579 }
2580
2581 int open_file_or_dir3(const char *fname, DIR **dirstream, int open_flags)
2582 {
2583         int ret;
2584         struct stat st;
2585         int fd;
2586
2587         ret = stat(fname, &st);
2588         if (ret < 0) {
2589                 return -1;
2590         }
2591         if (S_ISDIR(st.st_mode)) {
2592                 *dirstream = opendir(fname);
2593                 if (!*dirstream)
2594                         return -1;
2595                 fd = dirfd(*dirstream);
2596         } else if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
2597                 fd = open(fname, open_flags);
2598         } else {
2599                 /*
2600                  * we set this on purpose, in case the caller output
2601                  * strerror(errno) as success
2602                  */
2603                 errno = EINVAL;
2604                 return -1;
2605         }
2606         if (fd < 0) {
2607                 fd = -1;
2608                 if (*dirstream) {
2609                         closedir(*dirstream);
2610                         *dirstream = NULL;
2611                 }
2612         }
2613         return fd;
2614 }
2615
2616 int open_file_or_dir(const char *fname, DIR **dirstream)
2617 {
2618         return open_file_or_dir3(fname, dirstream, O_RDWR);
2619 }
2620
2621 void close_file_or_dir(int fd, DIR *dirstream)
2622 {
2623         if (dirstream)
2624                 closedir(dirstream);
2625         else if (fd >= 0)
2626                 close(fd);
2627 }
2628
2629 int get_device_info(int fd, u64 devid,
2630                 struct btrfs_ioctl_dev_info_args *di_args)
2631 {
2632         int ret;
2633
2634         di_args->devid = devid;
2635         memset(&di_args->uuid, '\0', sizeof(di_args->uuid));
2636
2637         ret = ioctl(fd, BTRFS_IOC_DEV_INFO, di_args);
2638         return ret < 0 ? -errno : 0;
2639 }
2640
2641 static u64 find_max_device_id(struct btrfs_ioctl_search_args *search_args,
2642                               int nr_items)
2643 {
2644         struct btrfs_dev_item *dev_item;
2645         char *buf = search_args->buf;
2646
2647         buf += (nr_items - 1) * (sizeof(struct btrfs_ioctl_search_header)
2648                                        + sizeof(struct btrfs_dev_item));
2649         buf += sizeof(struct btrfs_ioctl_search_header);
2650
2651         dev_item = (struct btrfs_dev_item *)buf;
2652
2653         return btrfs_stack_device_id(dev_item);
2654 }
2655
2656 static int search_chunk_tree_for_fs_info(int fd,
2657                                 struct btrfs_ioctl_fs_info_args *fi_args)
2658 {
2659         int ret;
2660         int max_items;
2661         u64 start_devid = 1;
2662         struct btrfs_ioctl_search_args search_args;
2663         struct btrfs_ioctl_search_key *search_key = &search_args.key;
2664
2665         fi_args->num_devices = 0;
2666
2667         max_items = BTRFS_SEARCH_ARGS_BUFSIZE
2668                / (sizeof(struct btrfs_ioctl_search_header)
2669                                + sizeof(struct btrfs_dev_item));
2670
2671         search_key->tree_id = BTRFS_CHUNK_TREE_OBJECTID;
2672         search_key->min_objectid = BTRFS_DEV_ITEMS_OBJECTID;
2673         search_key->max_objectid = BTRFS_DEV_ITEMS_OBJECTID;
2674         search_key->min_type = BTRFS_DEV_ITEM_KEY;
2675         search_key->max_type = BTRFS_DEV_ITEM_KEY;
2676         search_key->min_transid = 0;
2677         search_key->max_transid = (u64)-1;
2678         search_key->nr_items = max_items;
2679         search_key->max_offset = (u64)-1;
2680
2681 again:
2682         search_key->min_offset = start_devid;
2683
2684         ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH, &search_args);
2685         if (ret < 0)
2686                 return -errno;
2687
2688         fi_args->num_devices += (u64)search_key->nr_items;
2689
2690         if (search_key->nr_items == max_items) {
2691                 start_devid = find_max_device_id(&search_args,
2692                                         search_key->nr_items) + 1;
2693                 goto again;
2694         }
2695
2696         /* get the lastest max_id to stay consistent with the num_devices */
2697         if (search_key->nr_items == 0)
2698                 /*
2699                  * last tree_search returns an empty buf, use the devid of
2700                  * the last dev_item of the previous tree_search
2701                  */
2702                 fi_args->max_id = start_devid - 1;
2703         else
2704                 fi_args->max_id = find_max_device_id(&search_args,
2705                                                 search_key->nr_items);
2706
2707         return 0;
2708 }
2709
2710 /*
2711  * For a given path, fill in the ioctl fs_ and info_ args.
2712  * If the path is a btrfs mountpoint, fill info for all devices.
2713  * If the path is a btrfs device, fill in only that device.
2714  *
2715  * The path provided must be either on a mounted btrfs fs,
2716  * or be a mounted btrfs device.
2717  *
2718  * Returns 0 on success, or a negative errno.
2719  */
2720 int get_fs_info(char *path, struct btrfs_ioctl_fs_info_args *fi_args,
2721                 struct btrfs_ioctl_dev_info_args **di_ret)
2722 {
2723         int fd = -1;
2724         int ret = 0;
2725         int ndevs = 0;
2726         int i = 0;
2727         int replacing = 0;
2728         struct btrfs_fs_devices *fs_devices_mnt = NULL;
2729         struct btrfs_ioctl_dev_info_args *di_args;
2730         struct btrfs_ioctl_dev_info_args tmp;
2731         char mp[PATH_MAX];
2732         DIR *dirstream = NULL;
2733
2734         memset(fi_args, 0, sizeof(*fi_args));
2735
2736         if (is_block_device(path) == 1) {
2737                 struct btrfs_super_block *disk_super;
2738                 char buf[BTRFS_SUPER_INFO_SIZE];
2739                 u64 devid;
2740
2741                 /* Ensure it's mounted, then set path to the mountpoint */
2742                 fd = open(path, O_RDONLY);
2743                 if (fd < 0) {
2744                         ret = -errno;
2745                         error("cannot open %s: %s", path, strerror(errno));
2746                         goto out;
2747                 }
2748                 ret = check_mounted_where(fd, path, mp, sizeof(mp),
2749                                           &fs_devices_mnt);
2750                 if (!ret) {
2751                         ret = -EINVAL;
2752                         goto out;
2753                 }
2754                 if (ret < 0)
2755                         goto out;
2756                 path = mp;
2757                 /* Only fill in this one device */
2758                 fi_args->num_devices = 1;
2759
2760                 disk_super = (struct btrfs_super_block *)buf;
2761                 ret = btrfs_read_dev_super(fd, disk_super,
2762                                            BTRFS_SUPER_INFO_OFFSET, 0);
2763                 if (ret < 0) {
2764                         ret = -EIO;
2765                         goto out;
2766                 }
2767                 devid = btrfs_stack_device_id(&disk_super->dev_item);
2768
2769                 fi_args->max_id = devid;
2770                 i = devid;
2771
2772                 memcpy(fi_args->fsid, fs_devices_mnt->fsid, BTRFS_FSID_SIZE);
2773                 close(fd);
2774         }
2775
2776         /* at this point path must not be for a block device */
2777         fd = open_file_or_dir(path, &dirstream);
2778         if (fd < 0) {
2779                 ret = -errno;
2780                 goto out;
2781         }
2782
2783         /* fill in fi_args if not just a single device */
2784         if (fi_args->num_devices != 1) {
2785                 ret = ioctl(fd, BTRFS_IOC_FS_INFO, fi_args);
2786                 if (ret < 0) {
2787                         ret = -errno;
2788                         goto out;
2789                 }
2790
2791                 /*
2792                  * The fs_args->num_devices does not include seed devices
2793                  */
2794                 ret = search_chunk_tree_for_fs_info(fd, fi_args);
2795                 if (ret)
2796                         goto out;
2797
2798                 /*
2799                  * search_chunk_tree_for_fs_info() will lacks the devid 0
2800                  * so manual probe for it here.
2801                  */
2802                 ret = get_device_info(fd, 0, &tmp);
2803                 if (!ret) {
2804                         fi_args->num_devices++;
2805                         ndevs++;
2806                         replacing = 1;
2807                         if (i == 0)
2808                                 i++;
2809                 }
2810         }
2811
2812         if (!fi_args->num_devices)
2813                 goto out;
2814
2815         di_args = *di_ret = malloc((fi_args->num_devices) * sizeof(*di_args));
2816         if (!di_args) {
2817                 ret = -errno;
2818                 goto out;
2819         }
2820
2821         if (replacing)
2822                 memcpy(di_args, &tmp, sizeof(tmp));
2823         for (; i <= fi_args->max_id; ++i) {
2824                 ret = get_device_info(fd, i, &di_args[ndevs]);
2825                 if (ret == -ENODEV)
2826                         continue;
2827                 if (ret)
2828                         goto out;
2829                 ndevs++;
2830         }
2831
2832         /*
2833         * only when the only dev we wanted to find is not there then
2834         * let any error be returned
2835         */
2836         if (fi_args->num_devices != 1) {
2837                 BUG_ON(ndevs == 0);
2838                 ret = 0;
2839         }
2840
2841 out:
2842         close_file_or_dir(fd, dirstream);
2843         return ret;
2844 }
2845
2846 #define isoctal(c)      (((c) & ~7) == '0')
2847
2848 static inline void translate(char *f, char *t)
2849 {
2850         while (*f != '\0') {
2851                 if (*f == '\\' &&
2852                     isoctal(f[1]) && isoctal(f[2]) && isoctal(f[3])) {
2853                         *t++ = 64*(f[1] & 7) + 8*(f[2] & 7) + (f[3] & 7);
2854                         f += 4;
2855                 } else
2856                         *t++ = *f++;
2857         }
2858         *t = '\0';
2859         return;
2860 }
2861
2862 /*
2863  * Checks if the swap device.
2864  * Returns 1 if swap device, < 0 on error or 0 if not swap device.
2865  */
2866 static int is_swap_device(const char *file)
2867 {
2868         FILE    *f;
2869         struct stat     st_buf;
2870         dev_t   dev;
2871         ino_t   ino = 0;
2872         char    tmp[PATH_MAX];
2873         char    buf[PATH_MAX];
2874         char    *cp;
2875         int     ret = 0;
2876
2877         if (stat(file, &st_buf) < 0)
2878                 return -errno;
2879         if (S_ISBLK(st_buf.st_mode))
2880                 dev = st_buf.st_rdev;
2881         else if (S_ISREG(st_buf.st_mode)) {
2882                 dev = st_buf.st_dev;
2883                 ino = st_buf.st_ino;
2884         } else
2885                 return 0;
2886
2887         if ((f = fopen("/proc/swaps", "r")) == NULL)
2888                 return 0;
2889
2890         /* skip the first line */
2891         if (fgets(tmp, sizeof(tmp), f) == NULL)
2892                 goto out;
2893
2894         while (fgets(tmp, sizeof(tmp), f) != NULL) {
2895                 if ((cp = strchr(tmp, ' ')) != NULL)
2896                         *cp = '\0';
2897                 if ((cp = strchr(tmp, '\t')) != NULL)
2898                         *cp = '\0';
2899                 translate(tmp, buf);
2900                 if (stat(buf, &st_buf) != 0)
2901                         continue;
2902                 if (S_ISBLK(st_buf.st_mode)) {
2903                         if (dev == st_buf.st_rdev) {
2904                                 ret = 1;
2905                                 break;
2906                         }
2907                 } else if (S_ISREG(st_buf.st_mode)) {
2908                         if (dev == st_buf.st_dev && ino == st_buf.st_ino) {
2909                                 ret = 1;
2910                                 break;
2911                         }
2912                 }
2913         }
2914
2915 out:
2916         fclose(f);
2917
2918         return ret;
2919 }
2920
2921 /*
2922  * Check for existing filesystem or partition table on device.
2923  * Returns:
2924  *       1 for existing fs or partition
2925  *       0 for nothing found
2926  *      -1 for internal error
2927  */
2928 static int check_overwrite(const char *device)
2929 {
2930         const char      *type;
2931         blkid_probe     pr = NULL;
2932         int             ret;
2933         blkid_loff_t    size;
2934
2935         if (!device || !*device)
2936                 return 0;
2937
2938         ret = -1; /* will reset on success of all setup calls */
2939
2940         pr = blkid_new_probe_from_filename(device);
2941         if (!pr)
2942                 goto out;
2943
2944         size = blkid_probe_get_size(pr);
2945         if (size < 0)
2946                 goto out;
2947
2948         /* nothing to overwrite on a 0-length device */
2949         if (size == 0) {
2950                 ret = 0;
2951                 goto out;
2952         }
2953
2954         ret = blkid_probe_enable_partitions(pr, 1);
2955         if (ret < 0)
2956                 goto out;
2957
2958         ret = blkid_do_fullprobe(pr);
2959         if (ret < 0)
2960                 goto out;
2961
2962         /*
2963          * Blkid returns 1 for nothing found and 0 when it finds a signature,
2964          * but we want the exact opposite, so reverse the return value here.
2965          *
2966          * In addition print some useful diagnostics about what actually is
2967          * on the device.
2968          */
2969         if (ret) {
2970                 ret = 0;
2971                 goto out;
2972         }
2973
2974         if (!blkid_probe_lookup_value(pr, "TYPE", &type, NULL)) {
2975                 fprintf(stderr,
2976                         "%s appears to contain an existing "
2977                         "filesystem (%s).\n", device, type);
2978         } else if (!blkid_probe_lookup_value(pr, "PTTYPE", &type, NULL)) {
2979                 fprintf(stderr,
2980                         "%s appears to contain a partition "
2981                         "table (%s).\n", device, type);
2982         } else {
2983                 fprintf(stderr,
2984                         "%s appears to contain something weird "
2985                         "according to blkid\n", device);
2986         }
2987         ret = 1;
2988
2989 out:
2990         if (pr)
2991                 blkid_free_probe(pr);
2992         if (ret == -1)
2993                 fprintf(stderr,
2994                         "probe of %s failed, cannot detect "
2995                           "existing filesystem.\n", device);
2996         return ret;
2997 }
2998
2999 static int group_profile_devs_min(u64 flag)
3000 {
3001         switch (flag & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
3002         case 0: /* single */
3003         case BTRFS_BLOCK_GROUP_DUP:
3004                 return 1;
3005         case BTRFS_BLOCK_GROUP_RAID0:
3006         case BTRFS_BLOCK_GROUP_RAID1:
3007         case BTRFS_BLOCK_GROUP_RAID5:
3008                 return 2;
3009         case BTRFS_BLOCK_GROUP_RAID6:
3010                 return 3;
3011         case BTRFS_BLOCK_GROUP_RAID10:
3012                 return 4;
3013         default:
3014                 return -1;
3015         }
3016 }
3017
3018 int test_num_disk_vs_raid(u64 metadata_profile, u64 data_profile,
3019         u64 dev_cnt, int mixed, int ssd)
3020 {
3021         u64 allowed = 0;
3022
3023         switch (dev_cnt) {
3024         default:
3025         case 4:
3026                 allowed |= BTRFS_BLOCK_GROUP_RAID10;
3027         case 3:
3028                 allowed |= BTRFS_BLOCK_GROUP_RAID6;
3029         case 2:
3030                 allowed |= BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
3031                         BTRFS_BLOCK_GROUP_RAID5;
3032         case 1:
3033                 allowed |= BTRFS_BLOCK_GROUP_DUP;
3034         }
3035
3036         if (dev_cnt > 1 &&
3037             ((metadata_profile | data_profile) & BTRFS_BLOCK_GROUP_DUP)) {
3038                 warning("DUP is not recommended on filesystem with multiple devices");
3039         }
3040         if (metadata_profile & ~allowed) {
3041                 fprintf(stderr,
3042                         "ERROR: unable to create FS with metadata profile %s "
3043                         "(have %llu devices but %d devices are required)\n",
3044                         btrfs_group_profile_str(metadata_profile), dev_cnt,
3045                         group_profile_devs_min(metadata_profile));
3046                 return 1;
3047         }
3048         if (data_profile & ~allowed) {
3049                 fprintf(stderr,
3050                         "ERROR: unable to create FS with data profile %s "
3051                         "(have %llu devices but %d devices are required)\n",
3052                         btrfs_group_profile_str(data_profile), dev_cnt,
3053                         group_profile_devs_min(data_profile));
3054                 return 1;
3055         }
3056
3057         warning_on(!mixed && (data_profile & BTRFS_BLOCK_GROUP_DUP) && ssd,
3058                    "DUP may not actually lead to 2 copies on the device, see manual page");
3059
3060         return 0;
3061 }
3062
3063 int group_profile_max_safe_loss(u64 flags)
3064 {
3065         switch (flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
3066         case 0: /* single */
3067         case BTRFS_BLOCK_GROUP_DUP:
3068         case BTRFS_BLOCK_GROUP_RAID0:
3069                 return 0;
3070         case BTRFS_BLOCK_GROUP_RAID1:
3071         case BTRFS_BLOCK_GROUP_RAID5:
3072         case BTRFS_BLOCK_GROUP_RAID10:
3073                 return 1;
3074         case BTRFS_BLOCK_GROUP_RAID6:
3075                 return 2;
3076         default:
3077                 return -1;
3078         }
3079 }
3080
3081 /*
3082  * Check if a device is suitable for btrfs
3083  * returns:
3084  *  1: something is wrong, an error is printed
3085  *  0: all is fine
3086  */
3087 int test_dev_for_mkfs(const char *file, int force_overwrite)
3088 {
3089         int ret, fd;
3090         struct stat st;
3091
3092         ret = is_swap_device(file);
3093         if (ret < 0) {
3094                 error("checking status of %s: %s", file, strerror(-ret));
3095                 return 1;
3096         }
3097         if (ret == 1) {
3098                 error("%s is a swap device", file);
3099                 return 1;
3100         }
3101         if (!force_overwrite) {
3102                 if (check_overwrite(file)) {
3103                         error("use the -f option to force overwrite of %s",
3104                                         file);
3105                         return 1;
3106                 }
3107         }
3108         ret = check_mounted(file);
3109         if (ret < 0) {
3110                 error("cannot check mount status of %s: %s", file,
3111                                 strerror(-ret));
3112                 return 1;
3113         }
3114         if (ret == 1) {
3115                 error("%s is mounted", file);
3116                 return 1;
3117         }
3118         /* check if the device is busy */
3119         fd = open(file, O_RDWR|O_EXCL);
3120         if (fd < 0) {
3121                 error("unable to open %s: %s", file, strerror(errno));
3122                 return 1;
3123         }
3124         if (fstat(fd, &st)) {
3125                 error("unable to stat %s: %s", file, strerror(errno));
3126                 close(fd);
3127                 return 1;
3128         }
3129         if (!S_ISBLK(st.st_mode)) {
3130                 error("%s is not a block device", file);
3131                 close(fd);
3132                 return 1;
3133         }
3134         close(fd);
3135         return 0;
3136 }
3137
3138 int btrfs_scan_lblkid(void)
3139 {
3140         int fd = -1;
3141         int ret;
3142         u64 num_devices;
3143         struct btrfs_fs_devices *tmp_devices;
3144         blkid_dev_iterate iter = NULL;
3145         blkid_dev dev = NULL;
3146         blkid_cache cache = NULL;
3147         char path[PATH_MAX];
3148
3149         if (btrfs_scan_done)
3150                 return 0;
3151
3152         if (blkid_get_cache(&cache, NULL) < 0) {
3153                 error("blkid cache get failed");
3154                 return 1;
3155         }
3156         blkid_probe_all(cache);
3157         iter = blkid_dev_iterate_begin(cache);
3158         blkid_dev_set_search(iter, "TYPE", "btrfs");
3159         while (blkid_dev_next(iter, &dev) == 0) {
3160                 dev = blkid_verify(cache, dev);
3161                 if (!dev)
3162                         continue;
3163                 /* if we are here its definitely a btrfs disk*/
3164                 strncpy_null(path, blkid_dev_devname(dev));
3165
3166                 fd = open(path, O_RDONLY);
3167                 if (fd < 0) {
3168                         error("cannot open %s: %s", path, strerror(errno));
3169                         continue;
3170                 }
3171                 ret = btrfs_scan_one_device(fd, path, &tmp_devices,
3172                                 &num_devices, BTRFS_SUPER_INFO_OFFSET, 0);
3173                 if (ret) {
3174                         error("cannot scan %s: %s", path, strerror(-ret));
3175                         close (fd);
3176                         continue;
3177                 }
3178
3179                 close(fd);
3180         }
3181         blkid_dev_iterate_end(iter);
3182         blkid_put_cache(cache);
3183
3184         btrfs_scan_done = 1;
3185
3186         return 0;
3187 }
3188
3189 int is_vol_small(const char *file)
3190 {
3191         int fd = -1;
3192         int e;
3193         struct stat st;
3194         u64 size;
3195
3196         fd = open(file, O_RDONLY);
3197         if (fd < 0)
3198                 return -errno;
3199         if (fstat(fd, &st) < 0) {
3200                 e = -errno;
3201                 close(fd);
3202                 return e;
3203         }
3204         size = btrfs_device_size(fd, &st);
3205         if (size == 0) {
3206                 close(fd);
3207                 return -1;
3208         }
3209         if (size < BTRFS_MKFS_SMALL_VOLUME_SIZE) {
3210                 close(fd);
3211                 return 1;
3212         } else {
3213                 close(fd);
3214                 return 0;
3215         }
3216 }
3217
3218 /*
3219  * This reads a line from the stdin and only returns non-zero if the
3220  * first whitespace delimited token is a case insensitive match with yes
3221  * or y.
3222  */
3223 int ask_user(const char *question)
3224 {
3225         char buf[30] = {0,};
3226         char *saveptr = NULL;
3227         char *answer;
3228
3229         printf("%s [y/N]: ", question);
3230
3231         return fgets(buf, sizeof(buf) - 1, stdin) &&
3232                (answer = strtok_r(buf, " \t\n\r", &saveptr)) &&
3233                (!strcasecmp(answer, "yes") || !strcasecmp(answer, "y"));
3234 }
3235
3236 /*
3237  * For a given:
3238  * - file or directory return the containing tree root id
3239  * - subvolume return its own tree id
3240  * - BTRFS_EMPTY_SUBVOL_DIR_OBJECTID (directory with ino == 2) the result is
3241  *   undefined and function returns -1
3242  */
3243 int lookup_ino_rootid(int fd, u64 *rootid)
3244 {
3245         struct btrfs_ioctl_ino_lookup_args args;
3246         int ret;
3247
3248         memset(&args, 0, sizeof(args));
3249         args.treeid = 0;
3250         args.objectid = BTRFS_FIRST_FREE_OBJECTID;
3251
3252         ret = ioctl(fd, BTRFS_IOC_INO_LOOKUP, &args);
3253         if (ret < 0) {
3254                 error("failed to lookup root id: %s", strerror(errno));
3255                 return ret;
3256         }
3257
3258         *rootid = args.treeid;
3259
3260         return 0;
3261 }
3262
3263 /*
3264  * return 0 if a btrfs mount point is found
3265  * return 1 if a mount point is found but not btrfs
3266  * return <0 if something goes wrong
3267  */
3268 int find_mount_root(const char *path, char **mount_root)
3269 {
3270         FILE *mnttab;
3271         int fd;
3272         struct mntent *ent;
3273         int len;
3274         int ret;
3275         int not_btrfs = 1;
3276         int longest_matchlen = 0;
3277         char *longest_match = NULL;
3278
3279         fd = open(path, O_RDONLY | O_NOATIME);
3280         if (fd < 0)
3281                 return -errno;
3282         close(fd);
3283
3284         mnttab = setmntent("/proc/self/mounts", "r");
3285         if (!mnttab)
3286                 return -errno;
3287
3288         while ((ent = getmntent(mnttab))) {
3289                 len = strlen(ent->mnt_dir);
3290                 if (strncmp(ent->mnt_dir, path, len) == 0) {
3291                         /* match found and use the latest match */
3292                         if (longest_matchlen <= len) {
3293                                 free(longest_match);
3294                                 longest_matchlen = len;
3295                                 longest_match = strdup(ent->mnt_dir);
3296                                 not_btrfs = strcmp(ent->mnt_type, "btrfs");
3297                         }
3298                 }
3299         }
3300         endmntent(mnttab);
3301
3302         if (!longest_match)
3303                 return -ENOENT;
3304         if (not_btrfs) {
3305                 free(longest_match);
3306                 return 1;
3307         }
3308
3309         ret = 0;
3310         *mount_root = realpath(longest_match, NULL);
3311         if (!*mount_root)
3312                 ret = -errno;
3313
3314         free(longest_match);
3315         return ret;
3316 }
3317
3318 int test_minimum_size(const char *file, u32 nodesize)
3319 {
3320         int fd;
3321         struct stat statbuf;
3322
3323         fd = open(file, O_RDONLY);
3324         if (fd < 0)
3325                 return -errno;
3326         if (stat(file, &statbuf) < 0) {
3327                 close(fd);
3328                 return -errno;
3329         }
3330         if (btrfs_device_size(fd, &statbuf) < btrfs_min_dev_size(nodesize)) {
3331                 close(fd);
3332                 return 1;
3333         }
3334         close(fd);
3335         return 0;
3336 }
3337
3338
3339 /*
3340  * Test if path is a directory
3341  * Returns:
3342  *   0 - path exists but it is not a directory
3343  *   1 - path exists and it is a directory
3344  * < 0 - error
3345  */
3346 int test_isdir(const char *path)
3347 {
3348         struct stat st;
3349         int ret;
3350
3351         ret = stat(path, &st);
3352         if (ret < 0)
3353                 return -errno;
3354
3355         return !!S_ISDIR(st.st_mode);
3356 }
3357
3358 void units_set_mode(unsigned *units, unsigned mode)
3359 {
3360         unsigned base = *units & UNITS_MODE_MASK;
3361
3362         *units = base | mode;
3363 }
3364
3365 void units_set_base(unsigned *units, unsigned base)
3366 {
3367         unsigned mode = *units & ~UNITS_MODE_MASK;
3368
3369         *units = base | mode;
3370 }
3371
3372 int find_next_key(struct btrfs_path *path, struct btrfs_key *key)
3373 {
3374         int level;
3375
3376         for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
3377                 if (!path->nodes[level])
3378                         break;
3379                 if (path->slots[level] + 1 >=
3380                     btrfs_header_nritems(path->nodes[level]))
3381                         continue;
3382                 if (level == 0)
3383                         btrfs_item_key_to_cpu(path->nodes[level], key,
3384                                               path->slots[level] + 1);
3385                 else
3386                         btrfs_node_key_to_cpu(path->nodes[level], key,
3387                                               path->slots[level] + 1);
3388                 return 0;
3389         }
3390         return 1;
3391 }
3392
3393 const char* btrfs_group_type_str(u64 flag)
3394 {
3395         u64 mask = BTRFS_BLOCK_GROUP_TYPE_MASK |
3396                 BTRFS_SPACE_INFO_GLOBAL_RSV;
3397
3398         switch (flag & mask) {
3399         case BTRFS_BLOCK_GROUP_DATA:
3400                 return "Data";
3401         case BTRFS_BLOCK_GROUP_SYSTEM:
3402                 return "System";
3403         case BTRFS_BLOCK_GROUP_METADATA:
3404                 return "Metadata";
3405         case BTRFS_BLOCK_GROUP_DATA|BTRFS_BLOCK_GROUP_METADATA:
3406                 return "Data+Metadata";
3407         case BTRFS_SPACE_INFO_GLOBAL_RSV:
3408                 return "GlobalReserve";
3409         default:
3410                 return "unknown";
3411         }
3412 }
3413
3414 const char* btrfs_group_profile_str(u64 flag)
3415 {
3416         switch (flag & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
3417         case 0:
3418                 return "single";
3419         case BTRFS_BLOCK_GROUP_RAID0:
3420                 return "RAID0";
3421         case BTRFS_BLOCK_GROUP_RAID1:
3422                 return "RAID1";
3423         case BTRFS_BLOCK_GROUP_RAID5:
3424                 return "RAID5";
3425         case BTRFS_BLOCK_GROUP_RAID6:
3426                 return "RAID6";
3427         case BTRFS_BLOCK_GROUP_DUP:
3428                 return "DUP";
3429         case BTRFS_BLOCK_GROUP_RAID10:
3430                 return "RAID10";
3431         default:
3432                 return "unknown";
3433         }
3434 }
3435
3436 u64 disk_size(const char *path)
3437 {
3438         struct statfs sfs;
3439
3440         if (statfs(path, &sfs) < 0)
3441                 return 0;
3442         else
3443                 return sfs.f_bsize * sfs.f_blocks;
3444 }
3445
3446 u64 get_partition_size(const char *dev)
3447 {
3448         u64 result;
3449         int fd = open(dev, O_RDONLY);
3450
3451         if (fd < 0)
3452                 return 0;
3453         if (ioctl(fd, BLKGETSIZE64, &result) < 0) {
3454                 close(fd);
3455                 return 0;
3456         }
3457         close(fd);
3458
3459         return result;
3460 }
3461
3462 int btrfs_tree_search2_ioctl_supported(int fd)
3463 {
3464         struct btrfs_ioctl_search_args_v2 *args2;
3465         struct btrfs_ioctl_search_key *sk;
3466         int args2_size = 1024;
3467         char args2_buf[args2_size];
3468         int ret;
3469         static int v2_supported = -1;
3470
3471         if (v2_supported != -1)
3472                 return v2_supported;
3473
3474         args2 = (struct btrfs_ioctl_search_args_v2 *)args2_buf;
3475         sk = &(args2->key);
3476
3477         /*
3478          * Search for the extent tree item in the root tree.
3479          */
3480         sk->tree_id = BTRFS_ROOT_TREE_OBJECTID;
3481         sk->min_objectid = BTRFS_EXTENT_TREE_OBJECTID;
3482         sk->max_objectid = BTRFS_EXTENT_TREE_OBJECTID;
3483         sk->min_type = BTRFS_ROOT_ITEM_KEY;
3484         sk->max_type = BTRFS_ROOT_ITEM_KEY;
3485         sk->min_offset = 0;
3486         sk->max_offset = (u64)-1;
3487         sk->min_transid = 0;
3488         sk->max_transid = (u64)-1;
3489         sk->nr_items = 1;
3490         args2->buf_size = args2_size - sizeof(struct btrfs_ioctl_search_args_v2);
3491         ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH_V2, args2);
3492         if (ret == -EOPNOTSUPP)
3493                 v2_supported = 0;
3494         else if (ret == 0)
3495                 v2_supported = 1;
3496         else
3497                 return ret;
3498
3499         return v2_supported;
3500 }
3501
3502 int btrfs_check_nodesize(u32 nodesize, u32 sectorsize, u64 features)
3503 {
3504         if (nodesize < sectorsize) {
3505                 error("illegal nodesize %u (smaller than %u)",
3506                                 nodesize, sectorsize);
3507                 return -1;
3508         } else if (nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
3509                 error("illegal nodesize %u (larger than %u)",
3510                         nodesize, BTRFS_MAX_METADATA_BLOCKSIZE);
3511                 return -1;
3512         } else if (nodesize & (sectorsize - 1)) {
3513                 error("illegal nodesize %u (not aligned to %u)",
3514                         nodesize, sectorsize);
3515                 return -1;
3516         } else if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS &&
3517                    nodesize != sectorsize) {
3518                 error("illegal nodesize %u (not equal to %u for mixed block group)",
3519                         nodesize, sectorsize);
3520                 return -1;
3521         }
3522         return 0;
3523 }
3524
3525 /*
3526  * Copy a path argument from SRC to DEST and check the SRC length if it's at
3527  * most PATH_MAX and fits into DEST. DESTLEN is supposed to be exact size of
3528  * the buffer.
3529  * The destination buffer is zero terminated.
3530  * Return < 0 for error, 0 otherwise.
3531  */
3532 int arg_copy_path(char *dest, const char *src, int destlen)
3533 {
3534         size_t len = strlen(src);
3535
3536         if (len >= PATH_MAX || len >= destlen)
3537                 return -ENAMETOOLONG;
3538
3539         __strncpy_null(dest, src, destlen);
3540
3541         return 0;
3542 }
3543
3544 unsigned int get_unit_mode_from_arg(int *argc, char *argv[], int df_mode)
3545 {
3546         unsigned int unit_mode = UNITS_DEFAULT;
3547         int arg_i;
3548         int arg_end;
3549
3550         for (arg_i = 0; arg_i < *argc; arg_i++) {
3551                 if (!strcmp(argv[arg_i], "--"))
3552                         break;
3553
3554                 if (!strcmp(argv[arg_i], "--raw")) {
3555                         unit_mode = UNITS_RAW;
3556                         argv[arg_i] = NULL;
3557                         continue;
3558                 }
3559                 if (!strcmp(argv[arg_i], "--human-readable")) {
3560                         unit_mode = UNITS_HUMAN_BINARY;
3561                         argv[arg_i] = NULL;
3562                         continue;
3563                 }
3564
3565                 if (!strcmp(argv[arg_i], "--iec")) {
3566                         units_set_mode(&unit_mode, UNITS_BINARY);
3567                         argv[arg_i] = NULL;
3568                         continue;
3569                 }
3570                 if (!strcmp(argv[arg_i], "--si")) {
3571                         units_set_mode(&unit_mode, UNITS_DECIMAL);
3572                         argv[arg_i] = NULL;
3573                         continue;
3574                 }
3575
3576                 if (!strcmp(argv[arg_i], "--kbytes")) {
3577                         units_set_base(&unit_mode, UNITS_KBYTES);
3578                         argv[arg_i] = NULL;
3579                         continue;
3580                 }
3581                 if (!strcmp(argv[arg_i], "--mbytes")) {
3582                         units_set_base(&unit_mode, UNITS_MBYTES);
3583                         argv[arg_i] = NULL;
3584                         continue;
3585                 }
3586                 if (!strcmp(argv[arg_i], "--gbytes")) {
3587                         units_set_base(&unit_mode, UNITS_GBYTES);
3588                         argv[arg_i] = NULL;
3589                         continue;
3590                 }
3591                 if (!strcmp(argv[arg_i], "--tbytes")) {
3592                         units_set_base(&unit_mode, UNITS_TBYTES);
3593                         argv[arg_i] = NULL;
3594                         continue;
3595                 }
3596
3597                 if (!df_mode)
3598                         continue;
3599
3600                 if (!strcmp(argv[arg_i], "-b")) {
3601                         unit_mode = UNITS_RAW;
3602                         argv[arg_i] = NULL;
3603                         continue;
3604                 }
3605                 if (!strcmp(argv[arg_i], "-h")) {
3606                         unit_mode = UNITS_HUMAN_BINARY;
3607                         argv[arg_i] = NULL;
3608                         continue;
3609                 }
3610                 if (!strcmp(argv[arg_i], "-H")) {
3611                         unit_mode = UNITS_HUMAN_DECIMAL;
3612                         argv[arg_i] = NULL;
3613                         continue;
3614                 }
3615                 if (!strcmp(argv[arg_i], "-k")) {
3616                         units_set_base(&unit_mode, UNITS_KBYTES);
3617                         argv[arg_i] = NULL;
3618                         continue;
3619                 }
3620                 if (!strcmp(argv[arg_i], "-m")) {
3621                         units_set_base(&unit_mode, UNITS_MBYTES);
3622                         argv[arg_i] = NULL;
3623                         continue;
3624                 }
3625                 if (!strcmp(argv[arg_i], "-g")) {
3626                         units_set_base(&unit_mode, UNITS_GBYTES);
3627                         argv[arg_i] = NULL;
3628                         continue;
3629                 }
3630                 if (!strcmp(argv[arg_i], "-t")) {
3631                         units_set_base(&unit_mode, UNITS_TBYTES);
3632                         argv[arg_i] = NULL;
3633                         continue;
3634                 }
3635         }
3636
3637         for (arg_i = 0, arg_end = 0; arg_i < *argc; arg_i++) {
3638                 if (!argv[arg_i])
3639                         continue;
3640                 argv[arg_end] = argv[arg_i];
3641                 arg_end++;
3642         }
3643
3644         *argc = arg_end;
3645
3646         return unit_mode;
3647 }
3648
3649 int string_is_numerical(const char *str)
3650 {
3651         if (!(*str >= '0' && *str <= '9'))
3652                 return 0;
3653         while (*str >= '0' && *str <= '9')
3654                 str++;
3655         if (*str != '\0')
3656                 return 0;
3657         return 1;
3658 }
3659
3660 /*
3661  * Preprocess @argv with getopt_long to reorder options and consume the "--"
3662  * option separator.
3663  * Unknown short and long options are reported, optionally the @usage is printed
3664  * before exit.
3665  */
3666 void clean_args_no_options(int argc, char *argv[], const char * const *usagestr)
3667 {
3668         static const struct option long_options[] = {
3669                 {NULL, 0, NULL, 0}
3670         };
3671
3672         while (1) {
3673                 int c = getopt_long(argc, argv, "", long_options, NULL);
3674
3675                 if (c < 0)
3676                         break;
3677
3678                 switch (c) {
3679                 default:
3680                         if (usagestr)
3681                                 usage(usagestr);
3682                 }
3683         }
3684 }
3685
3686 /* Subvolume helper functions */
3687 /*
3688  * test if name is a correct subvolume name
3689  * this function return
3690  * 0-> name is not a correct subvolume name
3691  * 1-> name is a correct subvolume name
3692  */
3693 int test_issubvolname(const char *name)
3694 {
3695         return name[0] != '\0' && !strchr(name, '/') &&
3696                 strcmp(name, ".") && strcmp(name, "..");
3697 }
3698
3699 /*
3700  * Test if path is a subvolume
3701  * Returns:
3702  *   0 - path exists but it is not a subvolume
3703  *   1 - path exists and it is  a subvolume
3704  * < 0 - error
3705  */
3706 int test_issubvolume(const char *path)
3707 {
3708         struct stat     st;
3709         struct statfs stfs;
3710         int             res;
3711
3712         res = stat(path, &st);
3713         if (res < 0)
3714                 return -errno;
3715
3716         if (st.st_ino != BTRFS_FIRST_FREE_OBJECTID || !S_ISDIR(st.st_mode))
3717                 return 0;
3718
3719         res = statfs(path, &stfs);
3720         if (res < 0)
3721                 return -errno;
3722
3723         return (int)stfs.f_type == BTRFS_SUPER_MAGIC;
3724 }
3725
3726 const char *subvol_strip_mountpoint(const char *mnt, const char *full_path)
3727 {
3728         int len = strlen(mnt);
3729         if (!len)
3730                 return full_path;
3731
3732         if (mnt[len - 1] != '/')
3733                 len += 1;
3734
3735         return full_path + len;
3736 }
3737
3738 /*
3739  * Returns
3740  * <0: Std error
3741  * 0: All fine
3742  * 1: Error; and error info printed to the terminal. Fixme.
3743  * 2: If the fullpath is root tree instead of subvol tree
3744  */
3745 int get_subvol_info(const char *fullpath, struct root_info *get_ri)
3746 {
3747         u64 sv_id;
3748         int ret = 1;
3749         int fd = -1;
3750         int mntfd = -1;
3751         char *mnt = NULL;
3752         const char *svpath = NULL;
3753         DIR *dirstream1 = NULL;
3754         DIR *dirstream2 = NULL;
3755
3756         ret = test_issubvolume(fullpath);
3757         if (ret < 0)
3758                 return ret;
3759         if (!ret) {
3760                 error("not a subvolume: %s", fullpath);
3761                 return 1;
3762         }
3763
3764         ret = find_mount_root(fullpath, &mnt);
3765         if (ret < 0)
3766                 return ret;
3767         if (ret > 0) {
3768                 error("%s doesn't belong to btrfs mount point", fullpath);
3769                 return 1;
3770         }
3771         ret = 1;
3772         svpath = subvol_strip_mountpoint(mnt, fullpath);
3773
3774         fd = btrfs_open_dir(fullpath, &dirstream1, 1);
3775         if (fd < 0)
3776                 goto out;
3777
3778         ret = btrfs_list_get_path_rootid(fd, &sv_id);
3779         if (ret) {
3780                 error("can't get rootid for '%s'", fullpath);
3781                 goto out;
3782         }
3783
3784         mntfd = btrfs_open_dir(mnt, &dirstream2, 1);
3785         if (mntfd < 0)
3786                 goto out;
3787
3788         if (sv_id == BTRFS_FS_TREE_OBJECTID) {
3789                 ret = 2;
3790                 /*
3791                  * So that caller may decide if thats an error or just fine.
3792                  */
3793                 goto out;
3794         }
3795
3796         memset(get_ri, 0, sizeof(*get_ri));
3797         get_ri->root_id = sv_id;
3798
3799         ret = btrfs_get_subvol(mntfd, get_ri);
3800         if (ret)
3801                 error("can't find '%s': %d", svpath, ret);
3802
3803 out:
3804         close_file_or_dir(mntfd, dirstream2);
3805         close_file_or_dir(fd, dirstream1);
3806         free(mnt);
3807
3808         return ret;
3809 }
3810
3811 void init_rand_seed(u64 seed)
3812 {
3813         int i;
3814
3815         /* only use the last 48 bits */
3816         for (i = 0; i < 3; i++) {
3817                 rand_seed[i] = (unsigned short)(seed ^ (unsigned short)(-1));
3818                 seed >>= 16;
3819         }
3820         rand_seed_initlized = 1;
3821 }
3822
3823 static void __init_seed(void)
3824 {
3825         struct timeval tv;
3826         int ret;
3827         int fd;
3828
3829         if(rand_seed_initlized)
3830                 return;
3831         /* Use urandom as primary seed source. */
3832         fd = open("/dev/urandom", O_RDONLY);
3833         if (fd >= 0) {
3834                 ret = read(fd, rand_seed, sizeof(rand_seed));
3835                 close(fd);
3836                 if (ret < sizeof(rand_seed))
3837                         goto fallback;
3838         } else {
3839 fallback:
3840                 /* Use time and pid as fallback seed */
3841                 warning("failed to read /dev/urandom, use time and pid as random seed");
3842                 gettimeofday(&tv, 0);
3843                 rand_seed[0] = getpid() ^ (tv.tv_sec & 0xFFFF);
3844                 rand_seed[1] = getppid() ^ (tv.tv_usec & 0xFFFF);
3845                 rand_seed[2] = (tv.tv_sec ^ tv.tv_usec) >> 16;
3846         }
3847         rand_seed_initlized = 1;
3848 }
3849
3850 u32 rand_u32(void)
3851 {
3852         __init_seed();
3853         /*
3854          * Don't use nrand48, its range is [0,2^31) The highest bit will alwasy
3855          * be 0.  Use jrand48 to include the highest bit.
3856          */
3857         return (u32)jrand48(rand_seed);
3858 }
3859
3860 unsigned int rand_range(unsigned int upper)
3861 {
3862         __init_seed();
3863         /*
3864          * Use the full 48bits to mod, which would be more uniformly
3865          * distributed
3866          */
3867         return (unsigned int)(jrand48(rand_seed) % upper);
3868 }