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