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