mkfs.btrfs: free buffers allocated by pretty_sizes
[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         /*
415          * btrfs_inode_item has some reserved fields
416          * and represents on-disk inode entry, so
417          * zero everything to prevent information leak
418          */
419         memset(dst, 0, sizeof (*dst));
420
421         btrfs_set_stack_inode_generation(dst, trans->transid);
422         btrfs_set_stack_inode_size(dst, src->st_size);
423         btrfs_set_stack_inode_nbytes(dst, 0);
424         btrfs_set_stack_inode_block_group(dst, 0);
425         btrfs_set_stack_inode_nlink(dst, src->st_nlink);
426         btrfs_set_stack_inode_uid(dst, src->st_uid);
427         btrfs_set_stack_inode_gid(dst, src->st_gid);
428         btrfs_set_stack_inode_mode(dst, src->st_mode);
429         btrfs_set_stack_inode_rdev(dst, 0);
430         btrfs_set_stack_inode_flags(dst, 0);
431         btrfs_set_stack_timespec_sec(&dst->atime, src->st_atime);
432         btrfs_set_stack_timespec_nsec(&dst->atime, 0);
433         btrfs_set_stack_timespec_sec(&dst->ctime, src->st_ctime);
434         btrfs_set_stack_timespec_nsec(&dst->ctime, 0);
435         btrfs_set_stack_timespec_sec(&dst->mtime, src->st_mtime);
436         btrfs_set_stack_timespec_nsec(&dst->mtime, 0);
437         btrfs_set_stack_timespec_sec(&dst->otime, 0);
438         btrfs_set_stack_timespec_nsec(&dst->otime, 0);
439
440         if (S_ISDIR(src->st_mode)) {
441                 btrfs_set_stack_inode_size(dst, 0);
442                 btrfs_set_stack_inode_nlink(dst, 1);
443         }
444         if (S_ISREG(src->st_mode)) {
445                 btrfs_set_stack_inode_size(dst, (u64)src->st_size);
446                 if (src->st_size <= BTRFS_MAX_INLINE_DATA_SIZE(root))
447                         btrfs_set_stack_inode_nbytes(dst, src->st_size);
448                 else {
449                         blocks = src->st_size / sectorsize;
450                         if (src->st_size % sectorsize)
451                                 blocks += 1;
452                         blocks *= sectorsize;
453                         btrfs_set_stack_inode_nbytes(dst, blocks);
454                 }
455         }
456         if (S_ISLNK(src->st_mode))
457                 btrfs_set_stack_inode_nbytes(dst, src->st_size + 1);
458
459         return 0;
460 }
461
462 static int directory_select(const struct direct *entry)
463 {
464         if ((strncmp(entry->d_name, ".", entry->d_reclen) == 0) ||
465                 (strncmp(entry->d_name, "..", entry->d_reclen) == 0))
466                 return 0;
467         else
468                 return 1;
469 }
470
471 static u64 calculate_dir_inode_size(char *dirname)
472 {
473         int count, i;
474         struct direct **files, *cur_file;
475         u64 dir_inode_size = 0;
476
477         count = scandir(dirname, &files, directory_select, NULL);
478
479         for (i = 0; i < count; i++) {
480                 cur_file = files[i];
481                 dir_inode_size += strlen(cur_file->d_name);
482         }
483
484         dir_inode_size *= 2;
485         return dir_inode_size;
486 }
487
488 static int add_inode_items(struct btrfs_trans_handle *trans,
489                            struct btrfs_root *root,
490                            struct stat *st, char *name,
491                            u64 self_objectid, ino_t parent_inum,
492                            int dir_index_cnt, struct btrfs_inode_item *inode_ret)
493 {
494         int ret;
495         struct btrfs_key inode_key;
496         struct btrfs_inode_item btrfs_inode;
497         u64 objectid;
498         u64 inode_size = 0;
499         int name_len;
500
501         name_len = strlen(name);
502         fill_inode_item(trans, root, &btrfs_inode, st);
503         objectid = self_objectid;
504
505         if (S_ISDIR(st->st_mode)) {
506                 inode_size = calculate_dir_inode_size(name);
507                 btrfs_set_stack_inode_size(&btrfs_inode, inode_size);
508         }
509
510         inode_key.objectid = objectid;
511         inode_key.offset = 0;
512         btrfs_set_key_type(&inode_key, BTRFS_INODE_ITEM_KEY);
513
514         ret = btrfs_insert_inode(trans, root, objectid, &btrfs_inode);
515         if (ret)
516                 goto fail;
517
518         ret = btrfs_insert_inode_ref(trans, root, name, name_len,
519                                      objectid, parent_inum, dir_index_cnt);
520         if (ret)
521                 goto fail;
522
523         *inode_ret = btrfs_inode;
524 fail:
525         return ret;
526 }
527
528 static int add_xattr_item(struct btrfs_trans_handle *trans,
529                           struct btrfs_root *root, u64 objectid,
530                           const char *file_name)
531 {
532         int ret;
533         int cur_name_len;
534         char xattr_list[XATTR_LIST_MAX];
535         char *cur_name;
536         char cur_value[XATTR_SIZE_MAX];
537         char delimiter = '\0';
538         char *next_location = xattr_list;
539
540         ret = llistxattr(file_name, xattr_list, XATTR_LIST_MAX);
541         if (ret < 0) {
542                 fprintf(stderr, "get a list of xattr failed for %s\n",
543                         file_name);
544                 return ret;
545         }
546         if (ret == 0)
547                 return ret;
548
549         cur_name = strtok(xattr_list, &delimiter);
550         while (cur_name != NULL) {
551                 cur_name_len = strlen(cur_name);
552                 next_location += cur_name_len + 1;
553
554                 ret = getxattr(file_name, cur_name, cur_value, XATTR_SIZE_MAX);
555                 if (ret < 0) {
556                         fprintf(stderr, "get a xattr value failed for %s\n",
557                                 cur_name);
558                 }
559
560                 ret = btrfs_insert_xattr_item(trans, root, cur_name,
561                                               cur_name_len, cur_value,
562                                               ret, objectid);
563                 if (ret) {
564                         fprintf(stderr, "insert a xattr item failed for %s\n",
565                                 file_name);
566                 }
567
568                 cur_name = strtok(next_location, &delimiter);
569         }
570
571         return ret;
572 }
573
574 static int custom_alloc_extent(struct btrfs_root *root, u64 num_bytes,
575                                u64 hint_byte, struct btrfs_key *ins)
576 {
577         u64 start;
578         u64 end;
579         u64 last = hint_byte;
580         int ret;
581         int wrapped = 0;
582         struct btrfs_block_group_cache *cache;
583
584         while (1) {
585                 ret = find_first_extent_bit(&root->fs_info->free_space_cache,
586                                             last, &start, &end, EXTENT_DIRTY);
587                 if (ret) {
588                         if (wrapped++ == 0) {
589                                 last = 0;
590                                 continue;
591                         } else {
592                                 goto fail;
593                         }
594                 }
595
596                 start = max(last, start);
597                 last = end + 1;
598                 if (last - start < num_bytes)
599                         continue;
600
601                 last = start + num_bytes;
602                 if (test_range_bit(&root->fs_info->pinned_extents,
603                                    start, last - 1, EXTENT_DIRTY, 0))
604                         continue;
605
606                 cache = btrfs_lookup_block_group(root->fs_info, start);
607                 BUG_ON(!cache);
608                 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM ||
609                     last > cache->key.objectid + cache->key.offset) {
610                         last = cache->key.objectid + cache->key.offset;
611                         continue;
612                 }
613
614                 if (cache->flags & (BTRFS_BLOCK_GROUP_SYSTEM |
615                             BTRFS_BLOCK_GROUP_METADATA)) {
616                         last = cache->key.objectid + cache->key.offset;
617                         continue;
618                 }
619
620                 clear_extent_dirty(&root->fs_info->free_space_cache,
621                                    start, start + num_bytes - 1, 0);
622
623                 ins->objectid = start;
624                 ins->offset = num_bytes;
625                 ins->type = BTRFS_EXTENT_ITEM_KEY;
626                 return 0;
627         }
628 fail:
629         fprintf(stderr, "not enough free space\n");
630         return -ENOSPC;
631 }
632
633 static int record_file_extent(struct btrfs_trans_handle *trans,
634                               struct btrfs_root *root, u64 objectid,
635                               struct btrfs_inode_item *inode,
636                               u64 file_pos, u64 disk_bytenr,
637                               u64 num_bytes)
638 {
639         int ret;
640         struct btrfs_fs_info *info = root->fs_info;
641         struct btrfs_root *extent_root = info->extent_root;
642         struct extent_buffer *leaf;
643         struct btrfs_file_extent_item *fi;
644         struct btrfs_key ins_key;
645         struct btrfs_path path;
646         struct btrfs_extent_item *ei;
647
648         btrfs_init_path(&path);
649
650         ins_key.objectid = objectid;
651         ins_key.offset = 0;
652         btrfs_set_key_type(&ins_key, BTRFS_EXTENT_DATA_KEY);
653         ret = btrfs_insert_empty_item(trans, root, &path, &ins_key,
654                                       sizeof(*fi));
655         if (ret)
656                 goto fail;
657         leaf = path.nodes[0];
658         fi = btrfs_item_ptr(leaf, path.slots[0],
659                             struct btrfs_file_extent_item);
660         btrfs_set_file_extent_generation(leaf, fi, trans->transid);
661         btrfs_set_file_extent_type(leaf, fi, BTRFS_FILE_EXTENT_REG);
662         btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
663         btrfs_set_file_extent_disk_num_bytes(leaf, fi, num_bytes);
664         btrfs_set_file_extent_offset(leaf, fi, 0);
665         btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
666         btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
667         btrfs_set_file_extent_compression(leaf, fi, 0);
668         btrfs_set_file_extent_encryption(leaf, fi, 0);
669         btrfs_set_file_extent_other_encoding(leaf, fi, 0);
670         btrfs_mark_buffer_dirty(leaf);
671
672         btrfs_release_path(root, &path);
673
674         ins_key.objectid = disk_bytenr;
675         ins_key.offset = num_bytes;
676         ins_key.type = BTRFS_EXTENT_ITEM_KEY;
677
678         ret = btrfs_insert_empty_item(trans, extent_root, &path,
679                                 &ins_key, sizeof(*ei));
680         if (ret == 0) {
681                 leaf = path.nodes[0];
682                 ei = btrfs_item_ptr(leaf, path.slots[0],
683                                     struct btrfs_extent_item);
684
685                 btrfs_set_extent_refs(leaf, ei, 0);
686                 btrfs_set_extent_generation(leaf, ei, trans->transid);
687                 btrfs_set_extent_flags(leaf, ei, BTRFS_EXTENT_FLAG_DATA);
688
689                 btrfs_mark_buffer_dirty(leaf);
690                 ret = btrfs_update_block_group(trans, root, disk_bytenr,
691                                                num_bytes, 1, 0);
692                 if (ret)
693                         goto fail;
694         } else if (ret != -EEXIST) {
695                 goto fail;
696         }
697
698         ret = btrfs_inc_extent_ref(trans, root, disk_bytenr, num_bytes, 0,
699                                    root->root_key.objectid,
700                                    objectid, 0);
701 fail:
702         btrfs_release_path(root, &path);
703         return ret;
704 }
705
706 static int add_symbolic_link(struct btrfs_trans_handle *trans,
707                              struct btrfs_root *root,
708                              u64 objectid, const char *path_name)
709 {
710         int ret;
711         u64 sectorsize = root->sectorsize;
712         char *buf = malloc(sectorsize);
713
714         ret = readlink(path_name, buf, sectorsize);
715         if (ret <= 0) {
716                 fprintf(stderr, "readlink failed for %s\n", path_name);
717                 goto fail;
718         }
719         if (ret >= sectorsize) {
720                 fprintf(stderr, "symlink too long for %s", path_name);
721                 ret = -1;
722                 goto fail;
723         }
724
725         buf[ret] = '\0'; /* readlink does not do it for us */
726         ret = btrfs_insert_inline_extent(trans, root, objectid, 0,
727                                          buf, ret + 1);
728 fail:
729         free(buf);
730         return ret;
731 }
732
733 static int add_file_items(struct btrfs_trans_handle *trans,
734                           struct btrfs_root *root,
735                           struct btrfs_inode_item *btrfs_inode, u64 objectid,
736                           ino_t parent_inum, struct stat *st,
737                           const char *path_name, int out_fd)
738 {
739         int ret;
740         ssize_t ret_read;
741         u64 bytes_read = 0;
742         char *buffer = NULL;
743         struct btrfs_key key;
744         int blocks;
745         u32 sectorsize = root->sectorsize;
746         u64 first_block = 0;
747         u64 num_blocks = 0;
748         int fd;
749
750         fd = open(path_name, O_RDONLY);
751         if (fd == -1) {
752                 fprintf(stderr, "%s open failed\n", path_name);
753                 goto end;
754         }
755
756         blocks = st->st_size / sectorsize;
757         if (st->st_size % sectorsize)
758                 blocks += 1;
759
760         if (st->st_size <= BTRFS_MAX_INLINE_DATA_SIZE(root)) {
761                 buffer = malloc(st->st_size);
762                 ret_read = pread64(fd, buffer, st->st_size, bytes_read);
763                 if (ret_read == -1) {
764                         fprintf(stderr, "%s read failed\n", path_name);
765                         goto end;
766                 }
767
768                 ret = btrfs_insert_inline_extent(trans, root, objectid, 0,
769                                                  buffer, st->st_size);
770                 goto end;
771         }
772
773         ret = custom_alloc_extent(root, blocks * sectorsize, 0, &key);
774         if (ret)
775                 goto end;
776
777         first_block = key.objectid;
778         bytes_read = 0;
779         buffer = malloc(sectorsize);
780
781         do {
782                 memset(buffer, 0, sectorsize);
783                 ret_read = pread64(fd, buffer, sectorsize, bytes_read);
784                 if (ret_read == -1) {
785                         fprintf(stderr, "%s read failed\n", path_name);
786                         goto end;
787                 }
788
789                 ret = pwrite64(out_fd, buffer, sectorsize,
790                                first_block + bytes_read);
791                 if (ret != sectorsize) {
792                         fprintf(stderr, "output file write failed\n");
793                         goto end;
794                 }
795
796                 /* checksum for file data */
797                 ret = btrfs_csum_file_block(trans, root->fs_info->csum_root,
798                                 first_block + (blocks * sectorsize),
799                                 first_block + bytes_read,
800                                 buffer, sectorsize);
801                 if (ret) {
802                         fprintf(stderr, "%s checksum failed\n", path_name);
803                         goto end;
804                 }
805
806                 bytes_read += ret_read;
807                 num_blocks++;
808         } while (ret_read == sectorsize);
809
810         if (num_blocks > 0) {
811                 ret = record_file_extent(trans, root, objectid, btrfs_inode,
812                                          first_block, first_block,
813                                          blocks * sectorsize);
814                 if (ret)
815                         goto end;
816         }
817
818 end:
819         if (buffer)
820                 free(buffer);
821         close(fd);
822         return ret;
823 }
824
825 static char *make_path(char *dir, char *name)
826 {
827         char *path;
828
829         path = malloc(strlen(dir) + strlen(name) + 2);
830         if (!path)
831                 return NULL;
832         strcpy(path, dir);
833         if (dir[strlen(dir) - 1] != '/')
834                 strcat(path, "/");
835         strcat(path, name);
836         return path;
837 }
838
839 static int traverse_directory(struct btrfs_trans_handle *trans,
840                               struct btrfs_root *root, char *dir_name,
841                               struct directory_name_entry *dir_head, int out_fd)
842 {
843         int ret = 0;
844
845         struct btrfs_inode_item cur_inode;
846         struct btrfs_inode_item *inode_item;
847         int count, i, dir_index_cnt;
848         struct direct **files;
849         struct stat st;
850         struct directory_name_entry *dir_entry, *parent_dir_entry;
851         struct direct *cur_file;
852         ino_t parent_inum, cur_inum;
853         ino_t highest_inum = 0;
854         char *parent_dir_name;
855         struct btrfs_path path;
856         struct extent_buffer *leaf;
857         struct btrfs_key root_dir_key;
858         u64 root_dir_inode_size = 0;
859
860         /* Add list for source directory */
861         dir_entry = malloc(sizeof(struct directory_name_entry));
862         dir_entry->dir_name = dir_name;
863         dir_entry->path = malloc(strlen(dir_name) + 1);
864         strcpy(dir_entry->path, dir_name);
865
866         parent_inum = highest_inum + BTRFS_FIRST_FREE_OBJECTID;
867         dir_entry->inum = parent_inum;
868         list_add_tail(&dir_entry->list, &dir_head->list);
869
870         btrfs_init_path(&path);
871
872         root_dir_key.objectid = btrfs_root_dirid(&root->root_item);
873         root_dir_key.offset = 0;
874         btrfs_set_key_type(&root_dir_key, BTRFS_INODE_ITEM_KEY);
875         ret = btrfs_lookup_inode(trans, root, &path, &root_dir_key, 1);
876         if (ret) {
877                 fprintf(stderr, "root dir lookup error\n");
878                 goto fail;
879         }
880
881         leaf = path.nodes[0];
882         inode_item = btrfs_item_ptr(leaf, path.slots[0],
883                                     struct btrfs_inode_item);
884
885         root_dir_inode_size = calculate_dir_inode_size(dir_name);
886         btrfs_set_inode_size(leaf, inode_item, root_dir_inode_size);
887         btrfs_mark_buffer_dirty(leaf);
888
889         btrfs_release_path(root, &path);
890
891         do {
892                 parent_dir_entry = list_entry(dir_head->list.next,
893                                               struct directory_name_entry,
894                                               list);
895                 list_del(&parent_dir_entry->list);
896
897                 parent_inum = parent_dir_entry->inum;
898                 parent_dir_name = parent_dir_entry->dir_name;
899                 if (chdir(parent_dir_entry->path)) {
900                         fprintf(stderr, "chdir error for %s\n",
901                                 parent_dir_name);
902                         goto fail;
903                 }
904
905                 count = scandir(parent_dir_entry->path, &files,
906                                 directory_select, NULL);
907                 if (count == -1)
908                 {
909                         fprintf(stderr, "scandir for %s failed: %s\n",
910                                 parent_dir_name, strerror (errno));
911                         goto fail;
912                 }
913
914                 for (i = 0; i < count; i++) {
915                         cur_file = files[i];
916
917                         if (lstat(cur_file->d_name, &st) == -1) {
918                                 fprintf(stderr, "lstat failed for file %s\n",
919                                         cur_file->d_name);
920                                 goto fail;
921                         }
922
923                         cur_inum = ++highest_inum + BTRFS_FIRST_FREE_OBJECTID;
924                         ret = add_directory_items(trans, root,
925                                                   cur_inum, parent_inum,
926                                                   cur_file->d_name,
927                                                   &st, &dir_index_cnt);
928                         if (ret) {
929                                 fprintf(stderr, "add_directory_items failed\n");
930                                 goto fail;
931                         }
932
933                         ret = add_inode_items(trans, root, &st,
934                                               cur_file->d_name, cur_inum,
935                                               parent_inum, dir_index_cnt,
936                                               &cur_inode);
937                         if (ret) {
938                                 fprintf(stderr, "add_inode_items failed\n");
939                                 goto fail;
940                         }
941
942                         ret = add_xattr_item(trans, root,
943                                              cur_inum, cur_file->d_name);
944                         if (ret) {
945                                 fprintf(stderr, "add_xattr_item failed\n");
946                                 goto fail;
947                         }
948
949                         if (S_ISDIR(st.st_mode)) {
950                                 dir_entry = malloc(sizeof(struct directory_name_entry));
951                                 dir_entry->dir_name = cur_file->d_name;
952                                 dir_entry->path = make_path(parent_dir_entry->path,
953                                                             cur_file->d_name);
954                                 dir_entry->inum = cur_inum;
955                                 list_add_tail(&dir_entry->list, &dir_head->list);
956                         } else if (S_ISREG(st.st_mode)) {
957                                 ret = add_file_items(trans, root, &cur_inode,
958                                                      cur_inum, parent_inum, &st,
959                                                      cur_file->d_name, out_fd);
960                                 if (ret) {
961                                         fprintf(stderr, "add_file_items failed\n");
962                                         goto fail;
963                                 }
964                         } else if (S_ISLNK(st.st_mode)) {
965                                 ret = add_symbolic_link(trans, root,
966                                                         cur_inum, cur_file->d_name);
967                                 if (ret) {
968                                         fprintf(stderr, "add_symbolic_link failed\n");
969                                         goto fail;
970                                 }
971                         }
972                 }
973
974                 free(parent_dir_entry->path);
975                 free(parent_dir_entry);
976
977                 index_cnt = 2;
978
979         } while (!list_empty(&dir_head->list));
980
981         return 0;
982 fail:
983         free(parent_dir_entry->path);
984         free(parent_dir_entry);
985         return -1;
986 }
987
988 static int open_target(char *output_name)
989 {
990         int output_fd;
991         output_fd = open(output_name, O_CREAT | O_RDWR | O_TRUNC,
992                          S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
993
994         return output_fd;
995 }
996
997 static int create_chunks(struct btrfs_trans_handle *trans,
998                          struct btrfs_root *root, u64 num_of_meta_chunks,
999                          u64 size_of_data)
1000 {
1001         u64 chunk_start;
1002         u64 chunk_size;
1003         u64 meta_type = BTRFS_BLOCK_GROUP_METADATA;
1004         u64 data_type = BTRFS_BLOCK_GROUP_DATA;
1005         u64 minimum_data_chunk_size = 64 * 1024 * 1024;
1006         u64 i;
1007         int ret;
1008
1009         for (i = 0; i < num_of_meta_chunks; i++) {
1010                 ret = btrfs_alloc_chunk(trans, root->fs_info->extent_root,
1011                                         &chunk_start, &chunk_size, meta_type);
1012                 BUG_ON(ret);
1013                 ret = btrfs_make_block_group(trans, root->fs_info->extent_root, 0,
1014                                              meta_type, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
1015                                              chunk_start, chunk_size);
1016                 BUG_ON(ret);
1017                 set_extent_dirty(&root->fs_info->free_space_cache,
1018                                  chunk_start, chunk_start + chunk_size - 1, 0);
1019         }
1020
1021         if (size_of_data < minimum_data_chunk_size)
1022                 size_of_data = minimum_data_chunk_size;
1023         ret = btrfs_alloc_data_chunk(trans, root->fs_info->extent_root,
1024                                      &chunk_start, size_of_data, data_type);
1025         BUG_ON(ret);
1026         ret = btrfs_make_block_group(trans, root->fs_info->extent_root, 0,
1027                                      data_type, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
1028                                      chunk_start, size_of_data);
1029         BUG_ON(ret);
1030         set_extent_dirty(&root->fs_info->free_space_cache,
1031                          chunk_start, chunk_start + size_of_data - 1, 0);
1032         return ret;
1033 }
1034
1035 static int make_image(char *source_dir, struct btrfs_root *root, int out_fd)
1036 {
1037         int ret;
1038         struct btrfs_trans_handle *trans;
1039
1040         struct stat root_st;
1041         int root_len;
1042
1043         struct directory_name_entry dir_head;
1044
1045         ret = lstat(source_dir, &root_st);
1046         if (ret) {
1047                 fprintf(stderr, "unable to lstat the %s\n", source_dir);
1048                 goto fail;
1049         }
1050
1051         root_len = strlen(source_dir);
1052
1053         INIT_LIST_HEAD(&dir_head.list);
1054
1055         trans = btrfs_start_transaction(root, 1);
1056         ret = traverse_directory(trans, root, source_dir, &dir_head, out_fd);
1057         if (ret) {
1058                 fprintf(stderr, "unable to traverse_directory\n");
1059                 goto fail;
1060         }
1061         btrfs_commit_transaction(trans, root);
1062
1063         printf("Making image is completed.\n");
1064         return 0;
1065 fail:
1066         fprintf(stderr, "Making image is aborted.\n");
1067         return -1;
1068 }
1069
1070 static u64 size_sourcedir(char *dir_name, u64 sectorsize,
1071                           u64 *num_of_meta_chunks_ret, u64 *size_of_data_ret)
1072 {
1073         u64 dir_size = 0;
1074         u64 total_size = 0;
1075         int ret;
1076         char command[1024];
1077         char path[512];
1078         char *file_name = "temp_file";
1079         FILE *file;
1080         u64 minimum_data_size = 256 * 1024 * 1024;      /* 256MB */
1081         u64 default_chunk_size = 8 * 1024 * 1024;       /* 8MB */
1082         u64 allocated_meta_size = 8 * 1024 * 1024;      /* 8MB */
1083         u64 allocated_total_size = 20 * 1024 * 1024;    /* 20MB */
1084         u64 num_of_meta_chunks = 0;
1085         u64 num_of_allocated_meta_chunks =
1086                         allocated_meta_size / default_chunk_size;
1087
1088         ret = sprintf(command, "du -B 4096 -s ");
1089         if (ret < 0) {
1090                 fprintf(stderr, "error executing sprintf for du command\n");
1091                 return -1;
1092         }
1093         strcat(command, dir_name);
1094         strcat(command, " > ");
1095         strcat(command, file_name);
1096         ret = system(command);
1097
1098         file = fopen(file_name, "r");
1099         ret = fscanf(file, "%lld %s\n", &dir_size, path);
1100         fclose(file);
1101         remove(file_name);
1102
1103         dir_size *= sectorsize;
1104         *size_of_data_ret = dir_size;
1105
1106         num_of_meta_chunks = (dir_size / 2) / default_chunk_size;
1107         if (((dir_size / 2) % default_chunk_size) != 0)
1108                 num_of_meta_chunks++;
1109         if (num_of_meta_chunks <= num_of_allocated_meta_chunks)
1110                 num_of_meta_chunks = 0;
1111         else
1112                 num_of_meta_chunks -= num_of_allocated_meta_chunks;
1113
1114         total_size = allocated_total_size + dir_size +
1115                      (num_of_meta_chunks * default_chunk_size);
1116
1117         *num_of_meta_chunks_ret = num_of_meta_chunks;
1118
1119         if (total_size < minimum_data_size)
1120                 total_size = minimum_data_size;
1121
1122         return total_size;
1123 }
1124
1125 static int zero_output_file(int out_fd, u64 size, u32 sectorsize)
1126 {
1127         int len = sectorsize;
1128         int loop_num = size / sectorsize;
1129         u64 location = 0;
1130         char *buf = malloc(len);
1131         int ret = 0, i;
1132         ssize_t written;
1133
1134         if (!buf)
1135                 return -ENOMEM;
1136         memset(buf, 0, len);
1137         for (i = 0; i < loop_num; i++) {
1138                 written = pwrite64(out_fd, buf, len, location);
1139                 if (written != len)
1140                         ret = -EIO;
1141                 location += sectorsize;
1142         }
1143         free(buf);
1144         return ret;
1145 }
1146
1147 int main(int ac, char **av)
1148 {
1149         char *file;
1150         struct btrfs_root *root;
1151         struct btrfs_trans_handle *trans;
1152         char *label = NULL;
1153         char *first_file;
1154         u64 block_count = 0;
1155         u64 dev_block_count = 0;
1156         u64 blocks[7];
1157         u64 alloc_start = 0;
1158         u64 metadata_profile = BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_DUP;
1159         u64 data_profile = BTRFS_BLOCK_GROUP_RAID0;
1160         u32 leafsize = getpagesize();
1161         u32 sectorsize = 4096;
1162         u32 nodesize = leafsize;
1163         u32 stripesize = 4096;
1164         int zero_end = 1;
1165         int option_index = 0;
1166         int fd;
1167         int ret;
1168         int i;
1169         int mixed = 0;
1170         int data_profile_opt = 0;
1171         int metadata_profile_opt = 0;
1172
1173         char *source_dir = NULL;
1174         int source_dir_set = 0;
1175         char *output = "output.img";
1176         u64 num_of_meta_chunks = 0;
1177         u64 size_of_data = 0;
1178         char *pretty_buf;
1179
1180         while(1) {
1181                 int c;
1182                 c = getopt_long(ac, av, "A:b:l:n:s:m:d:L:r:VM", long_options,
1183                                 &option_index);
1184                 if (c < 0)
1185                         break;
1186                 switch(c) {
1187                         case 'A':
1188                                 alloc_start = parse_size(optarg);
1189                                 break;
1190                         case 'd':
1191                                 data_profile = parse_profile(optarg);
1192                                 data_profile_opt = 1;
1193                                 break;
1194                         case 'l':
1195                                 leafsize = parse_size(optarg);
1196                                 break;
1197                         case 'L':
1198                                 label = parse_label(optarg);
1199                                 break;
1200                         case 'm':
1201                                 metadata_profile = parse_profile(optarg);
1202                                 metadata_profile_opt = 1;
1203                                 break;
1204                         case 'M':
1205                                 mixed = 1;
1206                                 break;
1207                         case 'n':
1208                                 nodesize = parse_size(optarg);
1209                                 break;
1210                         case 's':
1211                                 sectorsize = parse_size(optarg);
1212                                 break;
1213                         case 'b':
1214                                 block_count = parse_size(optarg);
1215                                 if (block_count <= 1024*1024*1024) {
1216                                         printf("SMALL VOLUME: forcing mixed "
1217                                                "metadata/data groups\n");
1218                                         mixed = 1;
1219                                 }
1220                                 zero_end = 0;
1221                                 break;
1222                         case 'V':
1223                                 print_version();
1224                                 break;
1225                         case 'r':
1226                                 source_dir = optarg;
1227                                 source_dir_set = 1;
1228                                 break;
1229                         default:
1230                                 print_usage();
1231                 }
1232         }
1233         sectorsize = max(sectorsize, (u32)getpagesize());
1234         if (leafsize < sectorsize || (leafsize & (sectorsize - 1))) {
1235                 fprintf(stderr, "Illegal leafsize %u\n", leafsize);
1236                 exit(1);
1237         }
1238         if (nodesize < sectorsize || (nodesize & (sectorsize - 1))) {
1239                 fprintf(stderr, "Illegal nodesize %u\n", nodesize);
1240                 exit(1);
1241         }
1242         if (source_dir_set)
1243                 ac++;
1244         ac = ac - optind;
1245         if (ac == 0)
1246                 print_usage();
1247
1248         printf("\nWARNING! - %s IS EXPERIMENTAL\n", BTRFS_BUILD_VERSION);
1249         printf("WARNING! - see http://btrfs.wiki.kernel.org before using\n\n");
1250
1251         if (source_dir == 0) {
1252                 file = av[optind++];
1253                 ret = check_mounted(file);
1254                 if (ret < 0) {
1255                         fprintf(stderr, "error checking %s mount status\n", file);
1256                         exit(1);
1257                 }
1258                 if (ret == 1) {
1259                         fprintf(stderr, "%s is mounted\n", file);
1260                         exit(1);
1261                 }
1262                 ac--;
1263                 fd = open(file, O_RDWR);
1264                 if (fd < 0) {
1265                         fprintf(stderr, "unable to open %s\n", file);
1266                         exit(1);
1267                 }
1268                 first_file = file;
1269                 ret = btrfs_prepare_device(fd, file, zero_end, &dev_block_count, &mixed);
1270                 if (block_count == 0)
1271                         block_count = dev_block_count;
1272         } else {
1273                 ac = 0;
1274                 fd = open_target(output);
1275                 if (fd < 0) {
1276                         fprintf(stderr, "unable to open the %s\n", file);
1277                         exit(1);
1278                 }
1279
1280                 file = output;
1281                 first_file = file;
1282                 block_count = size_sourcedir(source_dir, sectorsize,
1283                                              &num_of_meta_chunks, &size_of_data);
1284                 ret = zero_output_file(fd, block_count, sectorsize);
1285                 if (ret) {
1286                         fprintf(stderr, "unable to zero the output file\n");
1287                         exit(1);
1288                 }
1289         }
1290         if (mixed) {
1291                 if (!metadata_profile_opt)
1292                         metadata_profile = 0;
1293                 if (!data_profile_opt)
1294                         data_profile = 0;
1295
1296                 if (metadata_profile != data_profile) {
1297                         fprintf(stderr, "With mixed block groups data and metadata "
1298                                 "profiles must be the same\n");
1299                         exit(1);
1300                 }
1301         }
1302
1303         blocks[0] = BTRFS_SUPER_INFO_OFFSET;
1304         for (i = 1; i < 7; i++) {
1305                 blocks[i] = BTRFS_SUPER_INFO_OFFSET + 1024 * 1024 +
1306                         leafsize * i;
1307         }
1308
1309         ret = make_btrfs(fd, file, label, blocks, block_count,
1310                          nodesize, leafsize,
1311                          sectorsize, stripesize);
1312         if (ret) {
1313                 fprintf(stderr, "error during mkfs %d\n", ret);
1314                 exit(1);
1315         }
1316         root = open_ctree(file, 0, O_RDWR);
1317         root->fs_info->alloc_start = alloc_start;
1318
1319         ret = make_root_dir(root, mixed);
1320         if (ret) {
1321                 fprintf(stderr, "failed to setup the root directory\n");
1322                 exit(1);
1323         }
1324
1325         trans = btrfs_start_transaction(root, 1);
1326
1327         if (ac == 0)
1328                 goto raid_groups;
1329
1330         btrfs_register_one_device(file);
1331         if (!root) {
1332                 fprintf(stderr, "ctree init failed\n");
1333                 return -1;
1334         }
1335
1336         zero_end = 1;
1337         while(ac-- > 0) {
1338                 int old_mixed = mixed;
1339
1340                 file = av[optind++];
1341                 ret = check_mounted(file);
1342                 if (ret < 0) {
1343                         fprintf(stderr, "error checking %s mount status\n",
1344                                 file);
1345                         exit(1);
1346                 }
1347                 if (ret == 1) {
1348                         fprintf(stderr, "%s is mounted\n", file);
1349                         exit(1);
1350                 }
1351                 fd = open(file, O_RDWR);
1352                 if (fd < 0) {
1353                         fprintf(stderr, "unable to open %s\n", file);
1354                         exit(1);
1355                 }
1356                 ret = btrfs_device_already_in_root(root, fd,
1357                                                    BTRFS_SUPER_INFO_OFFSET);
1358                 if (ret) {
1359                         fprintf(stderr, "skipping duplicate device %s in FS\n",
1360                                 file);
1361                         close(fd);
1362                         continue;
1363                 }
1364                 ret = btrfs_prepare_device(fd, file, zero_end,
1365                                            &dev_block_count, &mixed);
1366                 mixed = old_mixed;
1367                 BUG_ON(ret);
1368
1369                 ret = btrfs_add_to_fsid(trans, root, fd, file, dev_block_count,
1370                                         sectorsize, sectorsize, sectorsize);
1371                 BUG_ON(ret);
1372                 btrfs_register_one_device(file);
1373         }
1374
1375 raid_groups:
1376         if (!source_dir_set) {
1377                 ret = create_raid_groups(trans, root, data_profile,
1378                                  metadata_profile, mixed);
1379                 BUG_ON(ret);
1380         }
1381
1382         ret = create_data_reloc_tree(trans, root);
1383         BUG_ON(ret);
1384
1385         if (mixed) {
1386                 struct btrfs_super_block *super = &root->fs_info->super_copy;
1387                 u64 flags = btrfs_super_incompat_flags(super);
1388
1389                 flags |= BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS;
1390                 btrfs_set_super_incompat_flags(super, flags);
1391         }
1392
1393         printf("fs created label %s on %s\n\tnodesize %u leafsize %u "
1394             "sectorsize %u size %s\n",
1395             label, first_file, nodesize, leafsize, sectorsize,
1396             pretty_buf = pretty_sizes(btrfs_super_total_bytes(&root->fs_info->super_copy)));
1397         free(pretty_buf);
1398
1399         printf("%s\n", BTRFS_BUILD_VERSION);
1400         btrfs_commit_transaction(trans, root);
1401
1402         if (source_dir_set) {
1403                 trans = btrfs_start_transaction(root, 1);
1404                 ret = create_chunks(trans, root,
1405                                     num_of_meta_chunks, size_of_data);
1406                 BUG_ON(ret);
1407                 btrfs_commit_transaction(trans, root);
1408
1409                 ret = make_image(source_dir, root, fd);
1410                 BUG_ON(ret);
1411         }
1412
1413         ret = close_ctree(root);
1414         BUG_ON(ret);
1415
1416         free(label);
1417         return 0;
1418 }
1419