btrfs-progs: Fix over-sized limit on buffer
[platform/upstream/btrfs-progs.git] / mkfs.c
1 /*
2  * Copyright (C) 2007 Oracle.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18
19 #define _XOPEN_SOURCE 500
20 #define _GNU_SOURCE
21
22 #ifndef __CHECKER__
23 #include <sys/ioctl.h>
24 #include <sys/mount.h>
25 #include "ioctl.h"
26 #endif
27
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <sys/dir.h>
33 #include <fcntl.h>
34 #include <unistd.h>
35 #include <getopt.h>
36 #include <uuid/uuid.h>
37 #include <linux/fs.h>
38 #include <ctype.h>
39 #include <attr/xattr.h>
40 #include "kerncompat.h"
41 #include "ctree.h"
42 #include "disk-io.h"
43 #include "volumes.h"
44 #include "transaction.h"
45 #include "utils.h"
46 #include "version.h"
47
48 static u64 index_cnt = 2;
49
50 struct directory_name_entry {
51         char *dir_name;
52         char *path;
53         ino_t inum;
54         struct list_head list;
55 };
56
57 static u64 parse_size(char *s)
58 {
59         int len = strlen(s);
60         char c;
61         u64 mult = 1;
62
63         if (!isdigit(s[len - 1])) {
64                 c = tolower(s[len - 1]);
65                 switch (c) {
66                 case 'g':
67                         mult *= 1024;
68                 case 'm':
69                         mult *= 1024;
70                 case 'k':
71                         mult *= 1024;
72                 case 'b':
73                         break;
74                 default:
75                         fprintf(stderr, "Unknown size descriptor %c\n", c);
76                         exit(1);
77                 }
78                 s[len - 1] = '\0';
79         }
80         return atol(s) * mult;
81 }
82
83 static int make_root_dir(struct btrfs_root *root, int mixed)
84 {
85         struct btrfs_trans_handle *trans;
86         struct btrfs_key location;
87         u64 bytes_used;
88         u64 chunk_start = 0;
89         u64 chunk_size = 0;
90         int ret;
91
92         trans = btrfs_start_transaction(root, 1);
93         bytes_used = btrfs_super_bytes_used(&root->fs_info->super_copy);
94
95         root->fs_info->system_allocs = 1;
96         ret = btrfs_make_block_group(trans, root, bytes_used,
97                                      BTRFS_BLOCK_GROUP_SYSTEM,
98                                      BTRFS_FIRST_CHUNK_TREE_OBJECTID,
99                                      0, BTRFS_MKFS_SYSTEM_GROUP_SIZE);
100         BUG_ON(ret);
101
102         if (mixed) {
103                 ret = btrfs_alloc_chunk(trans, root->fs_info->extent_root,
104                                         &chunk_start, &chunk_size,
105                                         BTRFS_BLOCK_GROUP_METADATA |
106                                         BTRFS_BLOCK_GROUP_DATA);
107                 BUG_ON(ret);
108                 ret = btrfs_make_block_group(trans, root, 0,
109                                              BTRFS_BLOCK_GROUP_METADATA |
110                                              BTRFS_BLOCK_GROUP_DATA,
111                                              BTRFS_FIRST_CHUNK_TREE_OBJECTID,
112                                              chunk_start, chunk_size);
113                 BUG_ON(ret);
114                 printf("Created a data/metadata chunk of size %llu\n", chunk_size);
115         } else {
116                 ret = btrfs_alloc_chunk(trans, root->fs_info->extent_root,
117                                         &chunk_start, &chunk_size,
118                                         BTRFS_BLOCK_GROUP_METADATA);
119                 BUG_ON(ret);
120                 ret = btrfs_make_block_group(trans, root, 0,
121                                              BTRFS_BLOCK_GROUP_METADATA,
122                                              BTRFS_FIRST_CHUNK_TREE_OBJECTID,
123                                              chunk_start, chunk_size);
124                 BUG_ON(ret);
125         }
126
127         root->fs_info->system_allocs = 0;
128         btrfs_commit_transaction(trans, root);
129         trans = btrfs_start_transaction(root, 1);
130         BUG_ON(!trans);
131
132         if (!mixed) {
133                 ret = btrfs_alloc_chunk(trans, root->fs_info->extent_root,
134                                         &chunk_start, &chunk_size,
135                                         BTRFS_BLOCK_GROUP_DATA);
136                 BUG_ON(ret);
137                 ret = btrfs_make_block_group(trans, root, 0,
138                                              BTRFS_BLOCK_GROUP_DATA,
139                                              BTRFS_FIRST_CHUNK_TREE_OBJECTID,
140                                              chunk_start, chunk_size);
141                 BUG_ON(ret);
142         }
143
144         ret = btrfs_make_root_dir(trans, root->fs_info->tree_root,
145                               BTRFS_ROOT_TREE_DIR_OBJECTID);
146         if (ret)
147                 goto err;
148         ret = btrfs_make_root_dir(trans, root, BTRFS_FIRST_FREE_OBJECTID);
149         if (ret)
150                 goto err;
151         memcpy(&location, &root->fs_info->fs_root->root_key, sizeof(location));
152         location.offset = (u64)-1;
153         ret = btrfs_insert_dir_item(trans, root->fs_info->tree_root,
154                         "default", 7,
155                         btrfs_super_root_dir(&root->fs_info->super_copy),
156                         &location, BTRFS_FT_DIR, 0);
157         if (ret)
158                 goto err;
159
160         ret = btrfs_insert_inode_ref(trans, root->fs_info->tree_root,
161                              "default", 7, location.objectid,
162                              BTRFS_ROOT_TREE_DIR_OBJECTID, 0);
163         if (ret)
164                 goto err;
165
166         btrfs_commit_transaction(trans, root);
167 err:
168         return ret;
169 }
170
171 static int recow_roots(struct btrfs_trans_handle *trans,
172                        struct btrfs_root *root)
173 {
174         int ret;
175         struct extent_buffer *tmp;
176         struct btrfs_fs_info *info = root->fs_info;
177
178         ret = __btrfs_cow_block(trans, info->fs_root, info->fs_root->node,
179                                 NULL, 0, &tmp, 0, 0);
180         BUG_ON(ret);
181         free_extent_buffer(tmp);
182
183         ret = __btrfs_cow_block(trans, info->tree_root, info->tree_root->node,
184                                 NULL, 0, &tmp, 0, 0);
185         BUG_ON(ret);
186         free_extent_buffer(tmp);
187
188         ret = __btrfs_cow_block(trans, info->extent_root,
189                                 info->extent_root->node, NULL, 0, &tmp, 0, 0);
190         BUG_ON(ret);
191         free_extent_buffer(tmp);
192
193         ret = __btrfs_cow_block(trans, info->chunk_root, info->chunk_root->node,
194                                 NULL, 0, &tmp, 0, 0);
195         BUG_ON(ret);
196         free_extent_buffer(tmp);
197
198
199         ret = __btrfs_cow_block(trans, info->dev_root, info->dev_root->node,
200                                 NULL, 0, &tmp, 0, 0);
201         BUG_ON(ret);
202         free_extent_buffer(tmp);
203
204         ret = __btrfs_cow_block(trans, info->csum_root, info->csum_root->node,
205                                 NULL, 0, &tmp, 0, 0);
206         BUG_ON(ret);
207         free_extent_buffer(tmp);
208
209         return 0;
210 }
211
212 static int create_one_raid_group(struct btrfs_trans_handle *trans,
213                               struct btrfs_root *root, u64 type)
214 {
215         u64 chunk_start;
216         u64 chunk_size;
217         int ret;
218
219         ret = btrfs_alloc_chunk(trans, root->fs_info->extent_root,
220                                 &chunk_start, &chunk_size, type);
221         BUG_ON(ret);
222         ret = btrfs_make_block_group(trans, root->fs_info->extent_root, 0,
223                                      type, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
224                                      chunk_start, chunk_size);
225         BUG_ON(ret);
226         return ret;
227 }
228
229 static int create_raid_groups(struct btrfs_trans_handle *trans,
230                               struct btrfs_root *root, u64 data_profile,
231                               u64 metadata_profile, int mixed)
232 {
233         u64 num_devices = btrfs_super_num_devices(&root->fs_info->super_copy);
234         u64 allowed;
235         int ret;
236
237         if (num_devices == 1)
238                 allowed = BTRFS_BLOCK_GROUP_DUP;
239         else if (num_devices >= 4) {
240                 allowed = BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
241                         BTRFS_BLOCK_GROUP_RAID10;
242         } else
243                 allowed = BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1;
244
245         if (allowed & metadata_profile) {
246                 u64 meta_flags = BTRFS_BLOCK_GROUP_METADATA;
247
248                 ret = create_one_raid_group(trans, root,
249                                             BTRFS_BLOCK_GROUP_SYSTEM |
250                                             (allowed & metadata_profile));
251                 BUG_ON(ret);
252
253                 if (mixed)
254                         meta_flags |= BTRFS_BLOCK_GROUP_DATA;
255
256                 ret = create_one_raid_group(trans, root, meta_flags |
257                                             (allowed & metadata_profile));
258                 BUG_ON(ret);
259
260                 ret = recow_roots(trans, root);
261                 BUG_ON(ret);
262         }
263         if (!mixed && num_devices > 1 && (allowed & data_profile)) {
264                 ret = create_one_raid_group(trans, root,
265                                             BTRFS_BLOCK_GROUP_DATA |
266                                             (allowed & data_profile));
267                 BUG_ON(ret);
268         }
269         return 0;
270 }
271
272 static int create_data_reloc_tree(struct btrfs_trans_handle *trans,
273                                   struct btrfs_root *root)
274 {
275         struct btrfs_key location;
276         struct btrfs_root_item root_item;
277         struct extent_buffer *tmp;
278         u64 objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
279         int ret;
280
281         ret = btrfs_copy_root(trans, root, root->node, &tmp, objectid);
282         BUG_ON(ret);
283
284         memcpy(&root_item, &root->root_item, sizeof(root_item));
285         btrfs_set_root_bytenr(&root_item, tmp->start);
286         btrfs_set_root_level(&root_item, btrfs_header_level(tmp));
287         btrfs_set_root_generation(&root_item, trans->transid);
288         free_extent_buffer(tmp);
289
290         location.objectid = objectid;
291         location.type = BTRFS_ROOT_ITEM_KEY;
292         location.offset = 0;
293         ret = btrfs_insert_root(trans, root->fs_info->tree_root,
294                                 &location, &root_item);
295         BUG_ON(ret);
296         return 0;
297 }
298
299 static void print_usage(void)
300 {
301         fprintf(stderr, "usage: mkfs.btrfs [options] dev [ dev ... ]\n");
302         fprintf(stderr, "options:\n");
303         fprintf(stderr, "\t -A --alloc-start the offset to start the FS\n");
304         fprintf(stderr, "\t -b --byte-count total number of bytes in the FS\n");
305         fprintf(stderr, "\t -d --data data profile, raid0, raid1, raid10 or single\n");
306         fprintf(stderr, "\t -l --leafsize size of btree leaves\n");
307         fprintf(stderr, "\t -L --label set a label\n");
308         fprintf(stderr, "\t -m --metadata metadata profile, values like data profile\n");
309         fprintf(stderr, "\t -M --mixed mix metadata and data together\n");
310         fprintf(stderr, "\t -n --nodesize size of btree nodes\n");
311         fprintf(stderr, "\t -s --sectorsize min block allocation\n");
312         fprintf(stderr, "\t -r --rootdir the source directory\n");
313         fprintf(stderr, "%s\n", BTRFS_BUILD_VERSION);
314         exit(1);
315 }
316
317 static void print_version(void)
318 {
319         fprintf(stderr, "mkfs.btrfs, part of %s\n", BTRFS_BUILD_VERSION);
320         exit(0);
321 }
322
323 static u64 parse_profile(char *s)
324 {
325         if (strcmp(s, "raid0") == 0) {
326                 return BTRFS_BLOCK_GROUP_RAID0;
327         } else if (strcmp(s, "raid1") == 0) {
328                 return BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_DUP;
329         } else if (strcmp(s, "raid10") == 0) {
330                 return BTRFS_BLOCK_GROUP_RAID10 | BTRFS_BLOCK_GROUP_DUP;
331         } else if (strcmp(s, "single") == 0) {
332                 return 0;
333         } else {
334                 fprintf(stderr, "Unknown option %s\n", s);
335                 print_usage();
336         }
337         return 0;
338 }
339
340 static char *parse_label(char *input)
341 {
342         int i;
343         int len = strlen(input);
344
345         if (len > BTRFS_LABEL_SIZE) {
346                 fprintf(stderr, "Label %s is too long (max %d)\n", input,
347                         BTRFS_LABEL_SIZE);
348                 exit(1);
349         }
350         for (i = 0; i < len; i++) {
351                 if (input[i] == '/' || input[i] == '\\') {
352                         fprintf(stderr, "invalid label %s\n", input);
353                         exit(1);
354                 }
355         }
356         return strdup(input);
357 }
358
359 static struct option long_options[] = {
360         { "alloc-start", 1, NULL, 'A'},
361         { "byte-count", 1, NULL, 'b' },
362         { "leafsize", 1, NULL, 'l' },
363         { "label", 1, NULL, 'L'},
364         { "metadata", 1, NULL, 'm' },
365         { "mixed", 0, NULL, 'M' },
366         { "nodesize", 1, NULL, 'n' },
367         { "sectorsize", 1, NULL, 's' },
368         { "data", 1, NULL, 'd' },
369         { "version", 0, NULL, 'V' },
370         { "rootdir", 1, NULL, 'r' },
371         { 0, 0, 0, 0}
372 };
373
374 static int add_directory_items(struct btrfs_trans_handle *trans,
375                                struct btrfs_root *root, u64 objectid,
376                                ino_t parent_inum, const char *name,
377                                struct stat *st, int *dir_index_cnt)
378 {
379         int ret;
380         int name_len;
381         struct btrfs_key location;
382         u8 filetype = 0;
383
384         name_len = strlen(name);
385
386         location.objectid = objectid;
387         location.offset = 0;
388         btrfs_set_key_type(&location, BTRFS_INODE_ITEM_KEY);
389
390         if (S_ISDIR(st->st_mode))
391                 filetype = BTRFS_FT_DIR;
392         if (S_ISREG(st->st_mode))
393                 filetype = BTRFS_FT_REG_FILE;
394         if (S_ISLNK(st->st_mode))
395                 filetype = BTRFS_FT_SYMLINK;
396
397         ret = btrfs_insert_dir_item(trans, root, name, name_len,
398                                     parent_inum, &location,
399                                     filetype, index_cnt);
400
401         *dir_index_cnt = index_cnt;
402         index_cnt++;
403
404         return ret;
405 }
406
407 static int fill_inode_item(struct btrfs_trans_handle *trans,
408                            struct btrfs_root *root,
409                            struct btrfs_inode_item *dst, struct stat *src)
410 {
411         u64 blocks = 0;
412         u64 sectorsize = root->sectorsize;
413
414         btrfs_set_stack_inode_generation(dst, trans->transid);
415         btrfs_set_stack_inode_size(dst, src->st_size);
416         btrfs_set_stack_inode_nbytes(dst, 0);
417         btrfs_set_stack_inode_block_group(dst, 0);
418         btrfs_set_stack_inode_nlink(dst, src->st_nlink);
419         btrfs_set_stack_inode_uid(dst, src->st_uid);
420         btrfs_set_stack_inode_gid(dst, src->st_gid);
421         btrfs_set_stack_inode_mode(dst, src->st_mode);
422         btrfs_set_stack_inode_rdev(dst, 0);
423         btrfs_set_stack_inode_flags(dst, 0);
424         btrfs_set_stack_timespec_sec(&dst->atime, src->st_atime);
425         btrfs_set_stack_timespec_nsec(&dst->atime, 0);
426         btrfs_set_stack_timespec_sec(&dst->ctime, src->st_ctime);
427         btrfs_set_stack_timespec_nsec(&dst->ctime, 0);
428         btrfs_set_stack_timespec_sec(&dst->mtime, src->st_mtime);
429         btrfs_set_stack_timespec_nsec(&dst->mtime, 0);
430         btrfs_set_stack_timespec_sec(&dst->otime, 0);
431         btrfs_set_stack_timespec_nsec(&dst->otime, 0);
432
433         if (S_ISDIR(src->st_mode)) {
434                 btrfs_set_stack_inode_size(dst, 0);
435                 btrfs_set_stack_inode_nlink(dst, 1);
436         }
437         if (S_ISREG(src->st_mode)) {
438                 btrfs_set_stack_inode_size(dst, (u64)src->st_size);
439                 if (src->st_size <= BTRFS_MAX_INLINE_DATA_SIZE(root))
440                         btrfs_set_stack_inode_nbytes(dst, src->st_size);
441                 else {
442                         blocks = src->st_size / sectorsize;
443                         if (src->st_size % sectorsize)
444                                 blocks += 1;
445                         blocks *= sectorsize;
446                         btrfs_set_stack_inode_nbytes(dst, blocks);
447                 }
448         }
449         if (S_ISLNK(src->st_mode))
450                 btrfs_set_stack_inode_nbytes(dst, src->st_size + 1);
451
452         return 0;
453 }
454
455 static int directory_select(const struct direct *entry)
456 {
457         if ((strncmp(entry->d_name, ".", entry->d_reclen) == 0) ||
458                 (strncmp(entry->d_name, "..", entry->d_reclen) == 0))
459                 return 0;
460         else
461                 return 1;
462 }
463
464 static u64 calculate_dir_inode_size(char *dirname)
465 {
466         int count, i;
467         struct direct **files, *cur_file;
468         u64 dir_inode_size = 0;
469
470         count = scandir(dirname, &files, directory_select, NULL);
471
472         for (i = 0; i < count; i++) {
473                 cur_file = files[i];
474                 dir_inode_size += strlen(cur_file->d_name);
475         }
476
477         dir_inode_size *= 2;
478         return dir_inode_size;
479 }
480
481 static int add_inode_items(struct btrfs_trans_handle *trans,
482                            struct btrfs_root *root,
483                            struct stat *st, char *name,
484                            u64 self_objectid, ino_t parent_inum,
485                            int dir_index_cnt, struct btrfs_inode_item *inode_ret)
486 {
487         int ret;
488         struct btrfs_key inode_key;
489         struct btrfs_inode_item btrfs_inode;
490         u64 objectid;
491         u64 inode_size = 0;
492         int name_len;
493
494         name_len = strlen(name);
495         fill_inode_item(trans, root, &btrfs_inode, st);
496         objectid = self_objectid;
497
498         if (S_ISDIR(st->st_mode)) {
499                 inode_size = calculate_dir_inode_size(name);
500                 btrfs_set_stack_inode_size(&btrfs_inode, inode_size);
501         }
502
503         inode_key.objectid = objectid;
504         inode_key.offset = 0;
505         btrfs_set_key_type(&inode_key, BTRFS_INODE_ITEM_KEY);
506
507         ret = btrfs_insert_inode(trans, root, objectid, &btrfs_inode);
508         if (ret)
509                 goto fail;
510
511         ret = btrfs_insert_inode_ref(trans, root, name, name_len,
512                                      objectid, parent_inum, dir_index_cnt);
513         if (ret)
514                 goto fail;
515
516         *inode_ret = btrfs_inode;
517 fail:
518         return ret;
519 }
520
521 static int add_xattr_item(struct btrfs_trans_handle *trans,
522                           struct btrfs_root *root, u64 objectid,
523                           const char *file_name)
524 {
525         int ret;
526         int cur_name_len;
527         char xattr_list[XATTR_LIST_MAX];
528         char *cur_name;
529         char cur_value[XATTR_SIZE_MAX];
530         char delimiter = '\0';
531         char *next_location = xattr_list;
532
533         ret = llistxattr(file_name, xattr_list, XATTR_LIST_MAX);
534         if (ret < 0) {
535                 fprintf(stderr, "get a list of xattr failed for %s\n",
536                         file_name);
537                 return ret;
538         }
539         if (ret == 0)
540                 return ret;
541
542         cur_name = strtok(xattr_list, &delimiter);
543         while (cur_name != NULL) {
544                 cur_name_len = strlen(cur_name);
545                 next_location += cur_name_len + 1;
546
547                 ret = getxattr(file_name, cur_name, cur_value, XATTR_SIZE_MAX);
548                 if (ret < 0) {
549                         fprintf(stderr, "get a xattr value failed for %s\n",
550                                 cur_name);
551                 }
552
553                 ret = btrfs_insert_xattr_item(trans, root, cur_name,
554                                               cur_name_len, cur_value,
555                                               ret, objectid);
556                 if (ret) {
557                         fprintf(stderr, "insert a xattr item failed for %s\n",
558                                 file_name);
559                 }
560
561                 cur_name = strtok(next_location, &delimiter);
562         }
563
564         return ret;
565 }
566
567 static int custom_alloc_extent(struct btrfs_root *root, u64 num_bytes,
568                                u64 hint_byte, struct btrfs_key *ins)
569 {
570         u64 start;
571         u64 end;
572         u64 last = hint_byte;
573         int ret;
574         int wrapped = 0;
575         struct btrfs_block_group_cache *cache;
576
577         while (1) {
578                 ret = find_first_extent_bit(&root->fs_info->free_space_cache,
579                                             last, &start, &end, EXTENT_DIRTY);
580                 if (ret) {
581                         if (wrapped++ == 0) {
582                                 last = 0;
583                                 continue;
584                         } else {
585                                 goto fail;
586                         }
587                 }
588
589                 start = max(last, start);
590                 last = end + 1;
591                 if (last - start < num_bytes)
592                         continue;
593
594                 last = start + num_bytes;
595                 if (test_range_bit(&root->fs_info->pinned_extents,
596                                    start, last - 1, EXTENT_DIRTY, 0))
597                         continue;
598
599                 cache = btrfs_lookup_block_group(root->fs_info, start);
600                 BUG_ON(!cache);
601                 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM ||
602                     last > cache->key.objectid + cache->key.offset) {
603                         last = cache->key.objectid + cache->key.offset;
604                         continue;
605                 }
606
607                 if (cache->flags & (BTRFS_BLOCK_GROUP_SYSTEM |
608                             BTRFS_BLOCK_GROUP_METADATA)) {
609                         last = cache->key.objectid + cache->key.offset;
610                         continue;
611                 }
612
613                 clear_extent_dirty(&root->fs_info->free_space_cache,
614                                    start, start + num_bytes - 1, 0);
615
616                 ins->objectid = start;
617                 ins->offset = num_bytes;
618                 ins->type = BTRFS_EXTENT_ITEM_KEY;
619                 return 0;
620         }
621 fail:
622         fprintf(stderr, "not enough free space\n");
623         return -ENOSPC;
624 }
625
626 static int record_file_extent(struct btrfs_trans_handle *trans,
627                               struct btrfs_root *root, u64 objectid,
628                               struct btrfs_inode_item *inode,
629                               u64 file_pos, u64 disk_bytenr,
630                               u64 num_bytes)
631 {
632         int ret;
633         struct btrfs_fs_info *info = root->fs_info;
634         struct btrfs_root *extent_root = info->extent_root;
635         struct extent_buffer *leaf;
636         struct btrfs_file_extent_item *fi;
637         struct btrfs_key ins_key;
638         struct btrfs_path path;
639         struct btrfs_extent_item *ei;
640
641         btrfs_init_path(&path);
642
643         ins_key.objectid = objectid;
644         ins_key.offset = 0;
645         btrfs_set_key_type(&ins_key, BTRFS_EXTENT_DATA_KEY);
646         ret = btrfs_insert_empty_item(trans, root, &path, &ins_key,
647                                       sizeof(*fi));
648         if (ret)
649                 goto fail;
650         leaf = path.nodes[0];
651         fi = btrfs_item_ptr(leaf, path.slots[0],
652                             struct btrfs_file_extent_item);
653         btrfs_set_file_extent_generation(leaf, fi, trans->transid);
654         btrfs_set_file_extent_type(leaf, fi, BTRFS_FILE_EXTENT_REG);
655         btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
656         btrfs_set_file_extent_disk_num_bytes(leaf, fi, num_bytes);
657         btrfs_set_file_extent_offset(leaf, fi, 0);
658         btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
659         btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
660         btrfs_set_file_extent_compression(leaf, fi, 0);
661         btrfs_set_file_extent_encryption(leaf, fi, 0);
662         btrfs_set_file_extent_other_encoding(leaf, fi, 0);
663         btrfs_mark_buffer_dirty(leaf);
664
665         btrfs_release_path(root, &path);
666
667         ins_key.objectid = disk_bytenr;
668         ins_key.offset = num_bytes;
669         ins_key.type = BTRFS_EXTENT_ITEM_KEY;
670
671         ret = btrfs_insert_empty_item(trans, extent_root, &path,
672                                 &ins_key, sizeof(*ei));
673         if (ret == 0) {
674                 leaf = path.nodes[0];
675                 ei = btrfs_item_ptr(leaf, path.slots[0],
676                                     struct btrfs_extent_item);
677
678                 btrfs_set_extent_refs(leaf, ei, 0);
679                 btrfs_set_extent_generation(leaf, ei, trans->transid);
680                 btrfs_set_extent_flags(leaf, ei, BTRFS_EXTENT_FLAG_DATA);
681
682                 btrfs_mark_buffer_dirty(leaf);
683                 ret = btrfs_update_block_group(trans, root, disk_bytenr,
684                                                num_bytes, 1, 0);
685                 if (ret)
686                         goto fail;
687         } else if (ret != -EEXIST) {
688                 goto fail;
689         }
690
691         ret = btrfs_inc_extent_ref(trans, root, disk_bytenr, num_bytes, 0,
692                                    root->root_key.objectid,
693                                    objectid, 0);
694 fail:
695         btrfs_release_path(root, &path);
696         return ret;
697 }
698
699 static int add_symbolic_link(struct btrfs_trans_handle *trans,
700                              struct btrfs_root *root,
701                              u64 objectid, const char *path_name)
702 {
703         int ret;
704         u64 sectorsize = root->sectorsize;
705         char *buf = malloc(sectorsize);
706
707         ret = readlink(path_name, buf, sectorsize);
708         if (ret <= 0) {
709                 fprintf(stderr, "readlink failed for %s\n", path_name);
710                 goto fail;
711         }
712         if (ret > sectorsize) {
713                 fprintf(stderr, "symlink too long for %s", path_name);
714                 ret = -1;
715                 goto fail;
716         }
717         ret = btrfs_insert_inline_extent(trans, root, objectid, 0,
718                                          buf, ret + 1);
719 fail:
720         free(buf);
721         return ret;
722 }
723
724 static int add_file_items(struct btrfs_trans_handle *trans,
725                           struct btrfs_root *root,
726                           struct btrfs_inode_item *btrfs_inode, u64 objectid,
727                           ino_t parent_inum, struct stat *st,
728                           const char *path_name, int out_fd)
729 {
730         int ret;
731         ssize_t ret_read;
732         u64 bytes_read = 0;
733         char *buffer = NULL;
734         struct btrfs_key key;
735         int blocks;
736         u32 sectorsize = root->sectorsize;
737         u64 first_block = 0;
738         u64 num_blocks = 0;
739         int fd;
740
741         fd = open(path_name, O_RDONLY);
742         if (fd == -1) {
743                 fprintf(stderr, "%s open failed\n", path_name);
744                 goto end;
745         }
746
747         blocks = st->st_size / sectorsize;
748         if (st->st_size % sectorsize)
749                 blocks += 1;
750
751         if (st->st_size <= BTRFS_MAX_INLINE_DATA_SIZE(root)) {
752                 buffer = malloc(st->st_size);
753                 ret_read = pread64(fd, buffer, st->st_size, bytes_read);
754                 if (ret_read == -1) {
755                         fprintf(stderr, "%s read failed\n", path_name);
756                         goto end;
757                 }
758
759                 ret = btrfs_insert_inline_extent(trans, root, objectid, 0,
760                                                  buffer, st->st_size);
761                 goto end;
762         }
763
764         ret = custom_alloc_extent(root, blocks * sectorsize, 0, &key);
765         if (ret)
766                 goto end;
767
768         first_block = key.objectid;
769         bytes_read = 0;
770         buffer = malloc(sectorsize);
771
772         do {
773                 memset(buffer, 0, sectorsize);
774                 ret_read = pread64(fd, buffer, sectorsize, bytes_read);
775                 if (ret_read == -1) {
776                         fprintf(stderr, "%s read failed\n", path_name);
777                         goto end;
778                 }
779
780                 ret = pwrite64(out_fd, buffer, sectorsize,
781                                first_block + bytes_read);
782                 if (ret != sectorsize) {
783                         fprintf(stderr, "output file write failed\n");
784                         goto end;
785                 }
786
787                 /* checksum for file data */
788                 ret = btrfs_csum_file_block(trans, root->fs_info->csum_root,
789                                 first_block + (blocks * sectorsize),
790                                 first_block + bytes_read,
791                                 buffer, sectorsize);
792                 if (ret) {
793                         fprintf(stderr, "%s checksum failed\n", path_name);
794                         goto end;
795                 }
796
797                 bytes_read += ret_read;
798                 num_blocks++;
799         } while (ret_read == sectorsize);
800
801         if (num_blocks > 0) {
802                 ret = record_file_extent(trans, root, objectid, btrfs_inode,
803                                          first_block, first_block,
804                                          blocks * sectorsize);
805                 if (ret)
806                         goto end;
807         }
808
809 end:
810         if (buffer)
811                 free(buffer);
812         close(fd);
813         return ret;
814 }
815
816 static char *make_path(char *dir, char *name)
817 {
818         char *path;
819
820         path = malloc(strlen(dir) + strlen(name) + 2);
821         if (!path)
822                 return NULL;
823         strcpy(path, dir);
824         if (dir[strlen(dir) - 1] != '/')
825                 strcat(path, "/");
826         strcat(path, name);
827         return path;
828 }
829
830 static int traverse_directory(struct btrfs_trans_handle *trans,
831                               struct btrfs_root *root, char *dir_name,
832                               struct directory_name_entry *dir_head, int out_fd)
833 {
834         int ret = 0;
835
836         struct btrfs_inode_item cur_inode;
837         struct btrfs_inode_item *inode_item;
838         int count, i, dir_index_cnt;
839         struct direct **files;
840         struct stat st;
841         struct directory_name_entry *dir_entry, *parent_dir_entry;
842         struct direct *cur_file;
843         ino_t parent_inum, cur_inum;
844         ino_t highest_inum = 0;
845         char *parent_dir_name;
846         struct btrfs_path path;
847         struct extent_buffer *leaf;
848         struct btrfs_key root_dir_key;
849         u64 root_dir_inode_size = 0;
850
851         /* Add list for source directory */
852         dir_entry = malloc(sizeof(struct directory_name_entry));
853         dir_entry->dir_name = dir_name;
854         dir_entry->path = malloc(strlen(dir_name) + 1);
855         strcpy(dir_entry->path, dir_name);
856
857         parent_inum = highest_inum + BTRFS_FIRST_FREE_OBJECTID;
858         dir_entry->inum = parent_inum;
859         list_add_tail(&dir_entry->list, &dir_head->list);
860
861         btrfs_init_path(&path);
862
863         root_dir_key.objectid = btrfs_root_dirid(&root->root_item);
864         root_dir_key.offset = 0;
865         btrfs_set_key_type(&root_dir_key, BTRFS_INODE_ITEM_KEY);
866         ret = btrfs_lookup_inode(trans, root, &path, &root_dir_key, 1);
867         if (ret) {
868                 fprintf(stderr, "root dir lookup error\n");
869                 goto fail;
870         }
871
872         leaf = path.nodes[0];
873         inode_item = btrfs_item_ptr(leaf, path.slots[0],
874                                     struct btrfs_inode_item);
875
876         root_dir_inode_size = calculate_dir_inode_size(dir_name);
877         btrfs_set_inode_size(leaf, inode_item, root_dir_inode_size);
878         btrfs_mark_buffer_dirty(leaf);
879
880         btrfs_release_path(root, &path);
881
882         do {
883                 parent_dir_entry = list_entry(dir_head->list.next,
884                                               struct directory_name_entry,
885                                               list);
886                 list_del(&parent_dir_entry->list);
887
888                 parent_inum = parent_dir_entry->inum;
889                 parent_dir_name = parent_dir_entry->dir_name;
890                 if (chdir(parent_dir_entry->path)) {
891                         fprintf(stderr, "chdir error for %s\n",
892                                 parent_dir_name);
893                         goto fail;
894                 }
895
896                 count = scandir(parent_dir_entry->path, &files,
897                                 directory_select, NULL);
898
899                 for (i = 0; i < count; i++) {
900                         cur_file = files[i];
901
902                         if (lstat(cur_file->d_name, &st) == -1) {
903                                 fprintf(stderr, "lstat failed for file %s\n",
904                                         cur_file->d_name);
905                                 goto fail;
906                         }
907
908                         cur_inum = ++highest_inum + BTRFS_FIRST_FREE_OBJECTID;
909                         ret = add_directory_items(trans, root,
910                                                   cur_inum, parent_inum,
911                                                   cur_file->d_name,
912                                                   &st, &dir_index_cnt);
913                         if (ret) {
914                                 fprintf(stderr, "add_directory_items failed\n");
915                                 goto fail;
916                         }
917
918                         ret = add_inode_items(trans, root, &st,
919                                               cur_file->d_name, cur_inum,
920                                               parent_inum, dir_index_cnt,
921                                               &cur_inode);
922                         if (ret) {
923                                 fprintf(stderr, "add_inode_items failed\n");
924                                 goto fail;
925                         }
926
927                         ret = add_xattr_item(trans, root,
928                                              cur_inum, cur_file->d_name);
929                         if (ret) {
930                                 fprintf(stderr, "add_xattr_item failed\n");
931                                 goto fail;
932                         }
933
934                         if (S_ISDIR(st.st_mode)) {
935                                 dir_entry = malloc(sizeof(struct directory_name_entry));
936                                 dir_entry->dir_name = cur_file->d_name;
937                                 dir_entry->path = make_path(parent_dir_entry->path,
938                                                             cur_file->d_name);
939                                 dir_entry->inum = cur_inum;
940                                 list_add_tail(&dir_entry->list, &dir_head->list);
941                         } else if (S_ISREG(st.st_mode)) {
942                                 ret = add_file_items(trans, root, &cur_inode,
943                                                      cur_inum, parent_inum, &st,
944                                                      cur_file->d_name, out_fd);
945                                 if (ret) {
946                                         fprintf(stderr, "add_file_items failed\n");
947                                         goto fail;
948                                 }
949                         } else if (S_ISLNK(st.st_mode)) {
950                                 ret = add_symbolic_link(trans, root,
951                                                         cur_inum, cur_file->d_name);
952                                 if (ret) {
953                                         fprintf(stderr, "add_symbolic_link failed\n");
954                                         goto fail;
955                                 }
956                         }
957                 }
958
959                 free(parent_dir_entry->path);
960                 free(parent_dir_entry);
961
962                 index_cnt = 2;
963
964         } while (!list_empty(&dir_head->list));
965
966         return 0;
967 fail:
968         free(parent_dir_entry->path);
969         free(parent_dir_entry);
970         return -1;
971 }
972
973 static int open_target(char *output_name)
974 {
975         int output_fd;
976         output_fd = open(output_name, O_CREAT | O_RDWR | O_TRUNC,
977                          S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
978
979         return output_fd;
980 }
981
982 static int create_chunks(struct btrfs_trans_handle *trans,
983                          struct btrfs_root *root, u64 num_of_meta_chunks,
984                          u64 size_of_data)
985 {
986         u64 chunk_start;
987         u64 chunk_size;
988         u64 meta_type = BTRFS_BLOCK_GROUP_METADATA;
989         u64 data_type = BTRFS_BLOCK_GROUP_DATA;
990         u64 minimum_data_chunk_size = 64 * 1024 * 1024;
991         u64 i;
992         int ret;
993
994         for (i = 0; i < num_of_meta_chunks; i++) {
995                 ret = btrfs_alloc_chunk(trans, root->fs_info->extent_root,
996                                         &chunk_start, &chunk_size, meta_type);
997                 BUG_ON(ret);
998                 ret = btrfs_make_block_group(trans, root->fs_info->extent_root, 0,
999                                              meta_type, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
1000                                              chunk_start, chunk_size);
1001                 BUG_ON(ret);
1002                 set_extent_dirty(&root->fs_info->free_space_cache,
1003                                  chunk_start, chunk_start + chunk_size - 1, 0);
1004         }
1005
1006         if (size_of_data < minimum_data_chunk_size)
1007                 size_of_data = minimum_data_chunk_size;
1008         ret = btrfs_alloc_data_chunk(trans, root->fs_info->extent_root,
1009                                      &chunk_start, size_of_data, data_type);
1010         BUG_ON(ret);
1011         ret = btrfs_make_block_group(trans, root->fs_info->extent_root, 0,
1012                                      data_type, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
1013                                      chunk_start, size_of_data);
1014         BUG_ON(ret);
1015         set_extent_dirty(&root->fs_info->free_space_cache,
1016                          chunk_start, chunk_start + size_of_data - 1, 0);
1017         return ret;
1018 }
1019
1020 static int make_image(char *source_dir, struct btrfs_root *root, int out_fd)
1021 {
1022         int ret;
1023         struct btrfs_trans_handle *trans;
1024
1025         struct stat root_st;
1026         int root_len;
1027
1028         struct directory_name_entry dir_head;
1029
1030         ret = lstat(source_dir, &root_st);
1031         if (ret) {
1032                 fprintf(stderr, "unable to lstat the %s\n", source_dir);
1033                 goto fail;
1034         }
1035
1036         root_len = strlen(source_dir);
1037
1038         INIT_LIST_HEAD(&dir_head.list);
1039
1040         trans = btrfs_start_transaction(root, 1);
1041         ret = traverse_directory(trans, root, source_dir, &dir_head, out_fd);
1042         if (ret) {
1043                 fprintf(stderr, "unable to traverse_directory\n");
1044                 goto fail;
1045         }
1046         btrfs_commit_transaction(trans, root);
1047
1048         printf("Making image is completed.\n");
1049         return 0;
1050 fail:
1051         fprintf(stderr, "Making image is aborted.\n");
1052         return -1;
1053 }
1054
1055 static u64 size_sourcedir(char *dir_name, u64 sectorsize,
1056                           u64 *num_of_meta_chunks_ret, u64 *size_of_data_ret)
1057 {
1058         u64 dir_size = 0;
1059         u64 total_size = 0;
1060         int ret;
1061         char command[1024];
1062         char path[512];
1063         char *file_name = "temp_file";
1064         FILE *file;
1065         u64 minimum_data_size = 256 * 1024 * 1024;      /* 256MB */
1066         u64 default_chunk_size = 8 * 1024 * 1024;       /* 8MB */
1067         u64 allocated_meta_size = 8 * 1024 * 1024;      /* 8MB */
1068         u64 allocated_total_size = 20 * 1024 * 1024;    /* 20MB */
1069         u64 num_of_meta_chunks = 0;
1070         u64 num_of_allocated_meta_chunks =
1071                         allocated_meta_size / default_chunk_size;
1072
1073         ret = sprintf(command, "du -B 4096 -s ");
1074         if (ret < 0) {
1075                 fprintf(stderr, "error executing sprintf for du command\n");
1076                 return -1;
1077         }
1078         strcat(command, dir_name);
1079         strcat(command, " > ");
1080         strcat(command, file_name);
1081         ret = system(command);
1082
1083         file = fopen(file_name, "r");
1084         ret = fscanf(file, "%lld %s\n", &dir_size, path);
1085         fclose(file);
1086         remove(file_name);
1087
1088         dir_size *= sectorsize;
1089         *size_of_data_ret = dir_size;
1090
1091         num_of_meta_chunks = (dir_size / 2) / default_chunk_size;
1092         if (((dir_size / 2) % default_chunk_size) != 0)
1093                 num_of_meta_chunks++;
1094         if (num_of_meta_chunks <= num_of_allocated_meta_chunks)
1095                 num_of_meta_chunks = 0;
1096         else
1097                 num_of_meta_chunks -= num_of_allocated_meta_chunks;
1098
1099         total_size = allocated_total_size + dir_size +
1100                      (num_of_meta_chunks * default_chunk_size);
1101
1102         *num_of_meta_chunks_ret = num_of_meta_chunks;
1103
1104         if (total_size < minimum_data_size)
1105                 total_size = minimum_data_size;
1106
1107         return total_size;
1108 }
1109
1110 static int zero_output_file(int out_fd, u64 size, u32 sectorsize)
1111 {
1112         int len = sectorsize;
1113         int loop_num = size / sectorsize;
1114         u64 location = 0;
1115         char *buf = malloc(len);
1116         int ret = 0, i;
1117         ssize_t written;
1118
1119         if (!buf)
1120                 return -ENOMEM;
1121         memset(buf, 0, len);
1122         for (i = 0; i < loop_num; i++) {
1123                 written = pwrite64(out_fd, buf, len, location);
1124                 if (written != len)
1125                         ret = -EIO;
1126                 location += sectorsize;
1127         }
1128         free(buf);
1129         return ret;
1130 }
1131
1132 int main(int ac, char **av)
1133 {
1134         char *file;
1135         struct btrfs_root *root;
1136         struct btrfs_trans_handle *trans;
1137         char *label = NULL;
1138         char *first_file;
1139         u64 block_count = 0;
1140         u64 dev_block_count = 0;
1141         u64 blocks[7];
1142         u64 alloc_start = 0;
1143         u64 metadata_profile = BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_DUP;
1144         u64 data_profile = BTRFS_BLOCK_GROUP_RAID0;
1145         u32 leafsize = getpagesize();
1146         u32 sectorsize = 4096;
1147         u32 nodesize = leafsize;
1148         u32 stripesize = 4096;
1149         int zero_end = 1;
1150         int option_index = 0;
1151         int fd;
1152         int ret;
1153         int i;
1154         int mixed = 0;
1155         int data_profile_opt = 0;
1156         int metadata_profile_opt = 0;
1157
1158         char *source_dir = NULL;
1159         int source_dir_set = 0;
1160         char *output = "output.img";
1161         u64 num_of_meta_chunks = 0;
1162         u64 size_of_data = 0;
1163
1164         while(1) {
1165                 int c;
1166                 c = getopt_long(ac, av, "A:b:l:n:s:m:d:L:r:VM", long_options,
1167                                 &option_index);
1168                 if (c < 0)
1169                         break;
1170                 switch(c) {
1171                         case 'A':
1172                                 alloc_start = parse_size(optarg);
1173                                 break;
1174                         case 'd':
1175                                 data_profile = parse_profile(optarg);
1176                                 data_profile_opt = 1;
1177                                 break;
1178                         case 'l':
1179                                 leafsize = parse_size(optarg);
1180                                 break;
1181                         case 'L':
1182                                 label = parse_label(optarg);
1183                                 break;
1184                         case 'm':
1185                                 metadata_profile = parse_profile(optarg);
1186                                 metadata_profile_opt = 1;
1187                                 break;
1188                         case 'M':
1189                                 mixed = 1;
1190                                 break;
1191                         case 'n':
1192                                 nodesize = parse_size(optarg);
1193                                 break;
1194                         case 's':
1195                                 sectorsize = parse_size(optarg);
1196                                 break;
1197                         case 'b':
1198                                 block_count = parse_size(optarg);
1199                                 if (block_count <= 1024*1024*1024) {
1200                                         printf("SMALL VOLUME: forcing mixed "
1201                                                "metadata/data groups\n");
1202                                         mixed = 1;
1203                                 }
1204                                 zero_end = 0;
1205                                 break;
1206                         case 'V':
1207                                 print_version();
1208                                 break;
1209                         case 'r':
1210                                 source_dir = optarg;
1211                                 source_dir_set = 1;
1212                                 break;
1213                         default:
1214                                 print_usage();
1215                 }
1216         }
1217         sectorsize = max(sectorsize, (u32)getpagesize());
1218         if (leafsize < sectorsize || (leafsize & (sectorsize - 1))) {
1219                 fprintf(stderr, "Illegal leafsize %u\n", leafsize);
1220                 exit(1);
1221         }
1222         if (nodesize < sectorsize || (nodesize & (sectorsize - 1))) {
1223                 fprintf(stderr, "Illegal nodesize %u\n", nodesize);
1224                 exit(1);
1225         }
1226         if (source_dir_set)
1227                 ac++;
1228         ac = ac - optind;
1229         if (ac == 0)
1230                 print_usage();
1231
1232         printf("\nWARNING! - %s IS EXPERIMENTAL\n", BTRFS_BUILD_VERSION);
1233         printf("WARNING! - see http://btrfs.wiki.kernel.org before using\n\n");
1234
1235         if (source_dir == 0) {
1236                 file = av[optind++];
1237                 ret = check_mounted(file);
1238                 if (ret < 0) {
1239                         fprintf(stderr, "error checking %s mount status\n", file);
1240                         exit(1);
1241                 }
1242                 if (ret == 1) {
1243                         fprintf(stderr, "%s is mounted\n", file);
1244                         exit(1);
1245                 }
1246                 ac--;
1247                 fd = open(file, O_RDWR);
1248                 if (fd < 0) {
1249                         fprintf(stderr, "unable to open %s\n", file);
1250                         exit(1);
1251                 }
1252                 first_file = file;
1253                 ret = btrfs_prepare_device(fd, file, zero_end, &dev_block_count, &mixed);
1254                 if (block_count == 0)
1255                         block_count = dev_block_count;
1256         } else {
1257                 ac = 0;
1258                 fd = open_target(output);
1259                 if (fd < 0) {
1260                         fprintf(stderr, "unable to open the %s\n", file);
1261                         exit(1);
1262                 }
1263
1264                 file = output;
1265                 first_file = file;
1266                 block_count = size_sourcedir(source_dir, sectorsize,
1267                                              &num_of_meta_chunks, &size_of_data);
1268                 ret = zero_output_file(fd, block_count, sectorsize);
1269                 if (ret) {
1270                         fprintf(stderr, "unable to zero the output file\n");
1271                         exit(1);
1272                 }
1273         }
1274         if (mixed) {
1275                 if (!metadata_profile_opt)
1276                         metadata_profile = 0;
1277                 if (!data_profile_opt)
1278                         data_profile = 0;
1279
1280                 if (metadata_profile != data_profile) {
1281                         fprintf(stderr, "With mixed block groups data and metadata "
1282                                 "profiles must be the same\n");
1283                         exit(1);
1284                 }
1285         }
1286
1287         blocks[0] = BTRFS_SUPER_INFO_OFFSET;
1288         for (i = 1; i < 7; i++) {
1289                 blocks[i] = BTRFS_SUPER_INFO_OFFSET + 1024 * 1024 +
1290                         leafsize * i;
1291         }
1292
1293         ret = make_btrfs(fd, file, label, blocks, block_count,
1294                          nodesize, leafsize,
1295                          sectorsize, stripesize);
1296         if (ret) {
1297                 fprintf(stderr, "error during mkfs %d\n", ret);
1298                 exit(1);
1299         }
1300         root = open_ctree(file, 0, O_RDWR);
1301         root->fs_info->alloc_start = alloc_start;
1302
1303         ret = make_root_dir(root, mixed);
1304         if (ret) {
1305                 fprintf(stderr, "failed to setup the root directory\n");
1306                 exit(1);
1307         }
1308
1309         trans = btrfs_start_transaction(root, 1);
1310
1311         if (ac == 0)
1312                 goto raid_groups;
1313
1314         btrfs_register_one_device(file);
1315         if (!root) {
1316                 fprintf(stderr, "ctree init failed\n");
1317                 return -1;
1318         }
1319
1320         zero_end = 1;
1321         while(ac-- > 0) {
1322                 int old_mixed = mixed;
1323
1324                 file = av[optind++];
1325                 ret = check_mounted(file);
1326                 if (ret < 0) {
1327                         fprintf(stderr, "error checking %s mount status\n",
1328                                 file);
1329                         exit(1);
1330                 }
1331                 if (ret == 1) {
1332                         fprintf(stderr, "%s is mounted\n", file);
1333                         exit(1);
1334                 }
1335                 fd = open(file, O_RDWR);
1336                 if (fd < 0) {
1337                         fprintf(stderr, "unable to open %s\n", file);
1338                         exit(1);
1339                 }
1340                 ret = btrfs_device_already_in_root(root, fd,
1341                                                    BTRFS_SUPER_INFO_OFFSET);
1342                 if (ret) {
1343                         fprintf(stderr, "skipping duplicate device %s in FS\n",
1344                                 file);
1345                         close(fd);
1346                         continue;
1347                 }
1348                 ret = btrfs_prepare_device(fd, file, zero_end,
1349                                            &dev_block_count, &mixed);
1350                 mixed = old_mixed;
1351                 BUG_ON(ret);
1352
1353                 ret = btrfs_add_to_fsid(trans, root, fd, file, dev_block_count,
1354                                         sectorsize, sectorsize, sectorsize);
1355                 BUG_ON(ret);
1356                 btrfs_register_one_device(file);
1357         }
1358
1359 raid_groups:
1360         if (!source_dir_set) {
1361                 ret = create_raid_groups(trans, root, data_profile,
1362                                  metadata_profile, mixed);
1363                 BUG_ON(ret);
1364         }
1365
1366         ret = create_data_reloc_tree(trans, root);
1367         BUG_ON(ret);
1368
1369         if (mixed) {
1370                 struct btrfs_super_block *super = &root->fs_info->super_copy;
1371                 u64 flags = btrfs_super_incompat_flags(super);
1372
1373                 flags |= BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS;
1374                 btrfs_set_super_incompat_flags(super, flags);
1375         }
1376
1377         printf("fs created label %s on %s\n\tnodesize %u leafsize %u "
1378             "sectorsize %u size %s\n",
1379             label, first_file, nodesize, leafsize, sectorsize,
1380             pretty_sizes(btrfs_super_total_bytes(&root->fs_info->super_copy)));
1381
1382         printf("%s\n", BTRFS_BUILD_VERSION);
1383         btrfs_commit_transaction(trans, root);
1384
1385         if (source_dir_set) {
1386                 trans = btrfs_start_transaction(root, 1);
1387                 ret = create_chunks(trans, root,
1388                                     num_of_meta_chunks, size_of_data);
1389                 BUG_ON(ret);
1390                 btrfs_commit_transaction(trans, root);
1391
1392                 ret = make_image(source_dir, root, fd);
1393                 BUG_ON(ret);
1394         }
1395
1396         ret = close_ctree(root);
1397         BUG_ON(ret);
1398
1399         free(label);
1400         return 0;
1401 }
1402