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