mkfs.btrfs: fix symlink names writing
[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
718         buf[ret] = '\0'; /* readlink does not do it for us */
719         ret = btrfs_insert_inline_extent(trans, root, objectid, 0,
720                                          buf, ret + 1);
721 fail:
722         free(buf);
723         return ret;
724 }
725
726 static int add_file_items(struct btrfs_trans_handle *trans,
727                           struct btrfs_root *root,
728                           struct btrfs_inode_item *btrfs_inode, u64 objectid,
729                           ino_t parent_inum, struct stat *st,
730                           const char *path_name, int out_fd)
731 {
732         int ret;
733         ssize_t ret_read;
734         u64 bytes_read = 0;
735         char *buffer = NULL;
736         struct btrfs_key key;
737         int blocks;
738         u32 sectorsize = root->sectorsize;
739         u64 first_block = 0;
740         u64 num_blocks = 0;
741         int fd;
742
743         fd = open(path_name, O_RDONLY);
744         if (fd == -1) {
745                 fprintf(stderr, "%s open failed\n", path_name);
746                 goto end;
747         }
748
749         blocks = st->st_size / sectorsize;
750         if (st->st_size % sectorsize)
751                 blocks += 1;
752
753         if (st->st_size <= BTRFS_MAX_INLINE_DATA_SIZE(root)) {
754                 buffer = malloc(st->st_size);
755                 ret_read = pread64(fd, buffer, st->st_size, bytes_read);
756                 if (ret_read == -1) {
757                         fprintf(stderr, "%s read failed\n", path_name);
758                         goto end;
759                 }
760
761                 ret = btrfs_insert_inline_extent(trans, root, objectid, 0,
762                                                  buffer, st->st_size);
763                 goto end;
764         }
765
766         ret = custom_alloc_extent(root, blocks * sectorsize, 0, &key);
767         if (ret)
768                 goto end;
769
770         first_block = key.objectid;
771         bytes_read = 0;
772         buffer = malloc(sectorsize);
773
774         do {
775                 memset(buffer, 0, sectorsize);
776                 ret_read = pread64(fd, buffer, sectorsize, bytes_read);
777                 if (ret_read == -1) {
778                         fprintf(stderr, "%s read failed\n", path_name);
779                         goto end;
780                 }
781
782                 ret = pwrite64(out_fd, buffer, sectorsize,
783                                first_block + bytes_read);
784                 if (ret != sectorsize) {
785                         fprintf(stderr, "output file write failed\n");
786                         goto end;
787                 }
788
789                 /* checksum for file data */
790                 ret = btrfs_csum_file_block(trans, root->fs_info->csum_root,
791                                 first_block + (blocks * sectorsize),
792                                 first_block + bytes_read,
793                                 buffer, sectorsize);
794                 if (ret) {
795                         fprintf(stderr, "%s checksum failed\n", path_name);
796                         goto end;
797                 }
798
799                 bytes_read += ret_read;
800                 num_blocks++;
801         } while (ret_read == sectorsize);
802
803         if (num_blocks > 0) {
804                 ret = record_file_extent(trans, root, objectid, btrfs_inode,
805                                          first_block, first_block,
806                                          blocks * sectorsize);
807                 if (ret)
808                         goto end;
809         }
810
811 end:
812         if (buffer)
813                 free(buffer);
814         close(fd);
815         return ret;
816 }
817
818 static char *make_path(char *dir, char *name)
819 {
820         char *path;
821
822         path = malloc(strlen(dir) + strlen(name) + 2);
823         if (!path)
824                 return NULL;
825         strcpy(path, dir);
826         if (dir[strlen(dir) - 1] != '/')
827                 strcat(path, "/");
828         strcat(path, name);
829         return path;
830 }
831
832 static int traverse_directory(struct btrfs_trans_handle *trans,
833                               struct btrfs_root *root, char *dir_name,
834                               struct directory_name_entry *dir_head, int out_fd)
835 {
836         int ret = 0;
837
838         struct btrfs_inode_item cur_inode;
839         struct btrfs_inode_item *inode_item;
840         int count, i, dir_index_cnt;
841         struct direct **files;
842         struct stat st;
843         struct directory_name_entry *dir_entry, *parent_dir_entry;
844         struct direct *cur_file;
845         ino_t parent_inum, cur_inum;
846         ino_t highest_inum = 0;
847         char *parent_dir_name;
848         struct btrfs_path path;
849         struct extent_buffer *leaf;
850         struct btrfs_key root_dir_key;
851         u64 root_dir_inode_size = 0;
852
853         /* Add list for source directory */
854         dir_entry = malloc(sizeof(struct directory_name_entry));
855         dir_entry->dir_name = dir_name;
856         dir_entry->path = malloc(strlen(dir_name) + 1);
857         strcpy(dir_entry->path, dir_name);
858
859         parent_inum = highest_inum + BTRFS_FIRST_FREE_OBJECTID;
860         dir_entry->inum = parent_inum;
861         list_add_tail(&dir_entry->list, &dir_head->list);
862
863         btrfs_init_path(&path);
864
865         root_dir_key.objectid = btrfs_root_dirid(&root->root_item);
866         root_dir_key.offset = 0;
867         btrfs_set_key_type(&root_dir_key, BTRFS_INODE_ITEM_KEY);
868         ret = btrfs_lookup_inode(trans, root, &path, &root_dir_key, 1);
869         if (ret) {
870                 fprintf(stderr, "root dir lookup error\n");
871                 goto fail;
872         }
873
874         leaf = path.nodes[0];
875         inode_item = btrfs_item_ptr(leaf, path.slots[0],
876                                     struct btrfs_inode_item);
877
878         root_dir_inode_size = calculate_dir_inode_size(dir_name);
879         btrfs_set_inode_size(leaf, inode_item, root_dir_inode_size);
880         btrfs_mark_buffer_dirty(leaf);
881
882         btrfs_release_path(root, &path);
883
884         do {
885                 parent_dir_entry = list_entry(dir_head->list.next,
886                                               struct directory_name_entry,
887                                               list);
888                 list_del(&parent_dir_entry->list);
889
890                 parent_inum = parent_dir_entry->inum;
891                 parent_dir_name = parent_dir_entry->dir_name;
892                 if (chdir(parent_dir_entry->path)) {
893                         fprintf(stderr, "chdir error for %s\n",
894                                 parent_dir_name);
895                         goto fail;
896                 }
897
898                 count = scandir(parent_dir_entry->path, &files,
899                                 directory_select, NULL);
900                 if (count == -1)
901                 {
902                         fprintf(stderr, "scandir for %s failed: %s\n",
903                                 parent_dir_name, strerror (errno));
904                         goto fail;
905                 }
906
907                 for (i = 0; i < count; i++) {
908                         cur_file = files[i];
909
910                         if (lstat(cur_file->d_name, &st) == -1) {
911                                 fprintf(stderr, "lstat failed for file %s\n",
912                                         cur_file->d_name);
913                                 goto fail;
914                         }
915
916                         cur_inum = ++highest_inum + BTRFS_FIRST_FREE_OBJECTID;
917                         ret = add_directory_items(trans, root,
918                                                   cur_inum, parent_inum,
919                                                   cur_file->d_name,
920                                                   &st, &dir_index_cnt);
921                         if (ret) {
922                                 fprintf(stderr, "add_directory_items failed\n");
923                                 goto fail;
924                         }
925
926                         ret = add_inode_items(trans, root, &st,
927                                               cur_file->d_name, cur_inum,
928                                               parent_inum, dir_index_cnt,
929                                               &cur_inode);
930                         if (ret) {
931                                 fprintf(stderr, "add_inode_items failed\n");
932                                 goto fail;
933                         }
934
935                         ret = add_xattr_item(trans, root,
936                                              cur_inum, cur_file->d_name);
937                         if (ret) {
938                                 fprintf(stderr, "add_xattr_item failed\n");
939                                 goto fail;
940                         }
941
942                         if (S_ISDIR(st.st_mode)) {
943                                 dir_entry = malloc(sizeof(struct directory_name_entry));
944                                 dir_entry->dir_name = cur_file->d_name;
945                                 dir_entry->path = make_path(parent_dir_entry->path,
946                                                             cur_file->d_name);
947                                 dir_entry->inum = cur_inum;
948                                 list_add_tail(&dir_entry->list, &dir_head->list);
949                         } else if (S_ISREG(st.st_mode)) {
950                                 ret = add_file_items(trans, root, &cur_inode,
951                                                      cur_inum, parent_inum, &st,
952                                                      cur_file->d_name, out_fd);
953                                 if (ret) {
954                                         fprintf(stderr, "add_file_items failed\n");
955                                         goto fail;
956                                 }
957                         } else if (S_ISLNK(st.st_mode)) {
958                                 ret = add_symbolic_link(trans, root,
959                                                         cur_inum, cur_file->d_name);
960                                 if (ret) {
961                                         fprintf(stderr, "add_symbolic_link failed\n");
962                                         goto fail;
963                                 }
964                         }
965                 }
966
967                 free(parent_dir_entry->path);
968                 free(parent_dir_entry);
969
970                 index_cnt = 2;
971
972         } while (!list_empty(&dir_head->list));
973
974         return 0;
975 fail:
976         free(parent_dir_entry->path);
977         free(parent_dir_entry);
978         return -1;
979 }
980
981 static int open_target(char *output_name)
982 {
983         int output_fd;
984         output_fd = open(output_name, O_CREAT | O_RDWR | O_TRUNC,
985                          S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
986
987         return output_fd;
988 }
989
990 static int create_chunks(struct btrfs_trans_handle *trans,
991                          struct btrfs_root *root, u64 num_of_meta_chunks,
992                          u64 size_of_data)
993 {
994         u64 chunk_start;
995         u64 chunk_size;
996         u64 meta_type = BTRFS_BLOCK_GROUP_METADATA;
997         u64 data_type = BTRFS_BLOCK_GROUP_DATA;
998         u64 minimum_data_chunk_size = 64 * 1024 * 1024;
999         u64 i;
1000         int ret;
1001
1002         for (i = 0; i < num_of_meta_chunks; i++) {
1003                 ret = btrfs_alloc_chunk(trans, root->fs_info->extent_root,
1004                                         &chunk_start, &chunk_size, meta_type);
1005                 BUG_ON(ret);
1006                 ret = btrfs_make_block_group(trans, root->fs_info->extent_root, 0,
1007                                              meta_type, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
1008                                              chunk_start, chunk_size);
1009                 BUG_ON(ret);
1010                 set_extent_dirty(&root->fs_info->free_space_cache,
1011                                  chunk_start, chunk_start + chunk_size - 1, 0);
1012         }
1013
1014         if (size_of_data < minimum_data_chunk_size)
1015                 size_of_data = minimum_data_chunk_size;
1016         ret = btrfs_alloc_data_chunk(trans, root->fs_info->extent_root,
1017                                      &chunk_start, size_of_data, data_type);
1018         BUG_ON(ret);
1019         ret = btrfs_make_block_group(trans, root->fs_info->extent_root, 0,
1020                                      data_type, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
1021                                      chunk_start, size_of_data);
1022         BUG_ON(ret);
1023         set_extent_dirty(&root->fs_info->free_space_cache,
1024                          chunk_start, chunk_start + size_of_data - 1, 0);
1025         return ret;
1026 }
1027
1028 static int make_image(char *source_dir, struct btrfs_root *root, int out_fd)
1029 {
1030         int ret;
1031         struct btrfs_trans_handle *trans;
1032
1033         struct stat root_st;
1034         int root_len;
1035
1036         struct directory_name_entry dir_head;
1037
1038         ret = lstat(source_dir, &root_st);
1039         if (ret) {
1040                 fprintf(stderr, "unable to lstat the %s\n", source_dir);
1041                 goto fail;
1042         }
1043
1044         root_len = strlen(source_dir);
1045
1046         INIT_LIST_HEAD(&dir_head.list);
1047
1048         trans = btrfs_start_transaction(root, 1);
1049         ret = traverse_directory(trans, root, source_dir, &dir_head, out_fd);
1050         if (ret) {
1051                 fprintf(stderr, "unable to traverse_directory\n");
1052                 goto fail;
1053         }
1054         btrfs_commit_transaction(trans, root);
1055
1056         printf("Making image is completed.\n");
1057         return 0;
1058 fail:
1059         fprintf(stderr, "Making image is aborted.\n");
1060         return -1;
1061 }
1062
1063 static u64 size_sourcedir(char *dir_name, u64 sectorsize,
1064                           u64 *num_of_meta_chunks_ret, u64 *size_of_data_ret)
1065 {
1066         u64 dir_size = 0;
1067         u64 total_size = 0;
1068         int ret;
1069         char command[1024];
1070         char path[512];
1071         char *file_name = "temp_file";
1072         FILE *file;
1073         u64 minimum_data_size = 256 * 1024 * 1024;      /* 256MB */
1074         u64 default_chunk_size = 8 * 1024 * 1024;       /* 8MB */
1075         u64 allocated_meta_size = 8 * 1024 * 1024;      /* 8MB */
1076         u64 allocated_total_size = 20 * 1024 * 1024;    /* 20MB */
1077         u64 num_of_meta_chunks = 0;
1078         u64 num_of_allocated_meta_chunks =
1079                         allocated_meta_size / default_chunk_size;
1080
1081         ret = sprintf(command, "du -B 4096 -s ");
1082         if (ret < 0) {
1083                 fprintf(stderr, "error executing sprintf for du command\n");
1084                 return -1;
1085         }
1086         strcat(command, dir_name);
1087         strcat(command, " > ");
1088         strcat(command, file_name);
1089         ret = system(command);
1090
1091         file = fopen(file_name, "r");
1092         ret = fscanf(file, "%lld %s\n", &dir_size, path);
1093         fclose(file);
1094         remove(file_name);
1095
1096         dir_size *= sectorsize;
1097         *size_of_data_ret = dir_size;
1098
1099         num_of_meta_chunks = (dir_size / 2) / default_chunk_size;
1100         if (((dir_size / 2) % default_chunk_size) != 0)
1101                 num_of_meta_chunks++;
1102         if (num_of_meta_chunks <= num_of_allocated_meta_chunks)
1103                 num_of_meta_chunks = 0;
1104         else
1105                 num_of_meta_chunks -= num_of_allocated_meta_chunks;
1106
1107         total_size = allocated_total_size + dir_size +
1108                      (num_of_meta_chunks * default_chunk_size);
1109
1110         *num_of_meta_chunks_ret = num_of_meta_chunks;
1111
1112         if (total_size < minimum_data_size)
1113                 total_size = minimum_data_size;
1114
1115         return total_size;
1116 }
1117
1118 static int zero_output_file(int out_fd, u64 size, u32 sectorsize)
1119 {
1120         int len = sectorsize;
1121         int loop_num = size / sectorsize;
1122         u64 location = 0;
1123         char *buf = malloc(len);
1124         int ret = 0, i;
1125         ssize_t written;
1126
1127         if (!buf)
1128                 return -ENOMEM;
1129         memset(buf, 0, len);
1130         for (i = 0; i < loop_num; i++) {
1131                 written = pwrite64(out_fd, buf, len, location);
1132                 if (written != len)
1133                         ret = -EIO;
1134                 location += sectorsize;
1135         }
1136         free(buf);
1137         return ret;
1138 }
1139
1140 int main(int ac, char **av)
1141 {
1142         char *file;
1143         struct btrfs_root *root;
1144         struct btrfs_trans_handle *trans;
1145         char *label = NULL;
1146         char *first_file;
1147         u64 block_count = 0;
1148         u64 dev_block_count = 0;
1149         u64 blocks[7];
1150         u64 alloc_start = 0;
1151         u64 metadata_profile = BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_DUP;
1152         u64 data_profile = BTRFS_BLOCK_GROUP_RAID0;
1153         u32 leafsize = getpagesize();
1154         u32 sectorsize = 4096;
1155         u32 nodesize = leafsize;
1156         u32 stripesize = 4096;
1157         int zero_end = 1;
1158         int option_index = 0;
1159         int fd;
1160         int ret;
1161         int i;
1162         int mixed = 0;
1163         int data_profile_opt = 0;
1164         int metadata_profile_opt = 0;
1165
1166         char *source_dir = NULL;
1167         int source_dir_set = 0;
1168         char *output = "output.img";
1169         u64 num_of_meta_chunks = 0;
1170         u64 size_of_data = 0;
1171
1172         while(1) {
1173                 int c;
1174                 c = getopt_long(ac, av, "A:b:l:n:s:m:d:L:r:VM", long_options,
1175                                 &option_index);
1176                 if (c < 0)
1177                         break;
1178                 switch(c) {
1179                         case 'A':
1180                                 alloc_start = parse_size(optarg);
1181                                 break;
1182                         case 'd':
1183                                 data_profile = parse_profile(optarg);
1184                                 data_profile_opt = 1;
1185                                 break;
1186                         case 'l':
1187                                 leafsize = parse_size(optarg);
1188                                 break;
1189                         case 'L':
1190                                 label = parse_label(optarg);
1191                                 break;
1192                         case 'm':
1193                                 metadata_profile = parse_profile(optarg);
1194                                 metadata_profile_opt = 1;
1195                                 break;
1196                         case 'M':
1197                                 mixed = 1;
1198                                 break;
1199                         case 'n':
1200                                 nodesize = parse_size(optarg);
1201                                 break;
1202                         case 's':
1203                                 sectorsize = parse_size(optarg);
1204                                 break;
1205                         case 'b':
1206                                 block_count = parse_size(optarg);
1207                                 if (block_count <= 1024*1024*1024) {
1208                                         printf("SMALL VOLUME: forcing mixed "
1209                                                "metadata/data groups\n");
1210                                         mixed = 1;
1211                                 }
1212                                 zero_end = 0;
1213                                 break;
1214                         case 'V':
1215                                 print_version();
1216                                 break;
1217                         case 'r':
1218                                 source_dir = optarg;
1219                                 source_dir_set = 1;
1220                                 break;
1221                         default:
1222                                 print_usage();
1223                 }
1224         }
1225         sectorsize = max(sectorsize, (u32)getpagesize());
1226         if (leafsize < sectorsize || (leafsize & (sectorsize - 1))) {
1227                 fprintf(stderr, "Illegal leafsize %u\n", leafsize);
1228                 exit(1);
1229         }
1230         if (nodesize < sectorsize || (nodesize & (sectorsize - 1))) {
1231                 fprintf(stderr, "Illegal nodesize %u\n", nodesize);
1232                 exit(1);
1233         }
1234         if (source_dir_set)
1235                 ac++;
1236         ac = ac - optind;
1237         if (ac == 0)
1238                 print_usage();
1239
1240         printf("\nWARNING! - %s IS EXPERIMENTAL\n", BTRFS_BUILD_VERSION);
1241         printf("WARNING! - see http://btrfs.wiki.kernel.org before using\n\n");
1242
1243         if (source_dir == 0) {
1244                 file = av[optind++];
1245                 ret = check_mounted(file);
1246                 if (ret < 0) {
1247                         fprintf(stderr, "error checking %s mount status\n", file);
1248                         exit(1);
1249                 }
1250                 if (ret == 1) {
1251                         fprintf(stderr, "%s is mounted\n", file);
1252                         exit(1);
1253                 }
1254                 ac--;
1255                 fd = open(file, O_RDWR);
1256                 if (fd < 0) {
1257                         fprintf(stderr, "unable to open %s\n", file);
1258                         exit(1);
1259                 }
1260                 first_file = file;
1261                 ret = btrfs_prepare_device(fd, file, zero_end, &dev_block_count, &mixed);
1262                 if (block_count == 0)
1263                         block_count = dev_block_count;
1264         } else {
1265                 ac = 0;
1266                 fd = open_target(output);
1267                 if (fd < 0) {
1268                         fprintf(stderr, "unable to open the %s\n", file);
1269                         exit(1);
1270                 }
1271
1272                 file = output;
1273                 first_file = file;
1274                 block_count = size_sourcedir(source_dir, sectorsize,
1275                                              &num_of_meta_chunks, &size_of_data);
1276                 ret = zero_output_file(fd, block_count, sectorsize);
1277                 if (ret) {
1278                         fprintf(stderr, "unable to zero the output file\n");
1279                         exit(1);
1280                 }
1281         }
1282         if (mixed) {
1283                 if (!metadata_profile_opt)
1284                         metadata_profile = 0;
1285                 if (!data_profile_opt)
1286                         data_profile = 0;
1287
1288                 if (metadata_profile != data_profile) {
1289                         fprintf(stderr, "With mixed block groups data and metadata "
1290                                 "profiles must be the same\n");
1291                         exit(1);
1292                 }
1293         }
1294
1295         blocks[0] = BTRFS_SUPER_INFO_OFFSET;
1296         for (i = 1; i < 7; i++) {
1297                 blocks[i] = BTRFS_SUPER_INFO_OFFSET + 1024 * 1024 +
1298                         leafsize * i;
1299         }
1300
1301         ret = make_btrfs(fd, file, label, blocks, block_count,
1302                          nodesize, leafsize,
1303                          sectorsize, stripesize);
1304         if (ret) {
1305                 fprintf(stderr, "error during mkfs %d\n", ret);
1306                 exit(1);
1307         }
1308         root = open_ctree(file, 0, O_RDWR);
1309         root->fs_info->alloc_start = alloc_start;
1310
1311         ret = make_root_dir(root, mixed);
1312         if (ret) {
1313                 fprintf(stderr, "failed to setup the root directory\n");
1314                 exit(1);
1315         }
1316
1317         trans = btrfs_start_transaction(root, 1);
1318
1319         if (ac == 0)
1320                 goto raid_groups;
1321
1322         btrfs_register_one_device(file);
1323         if (!root) {
1324                 fprintf(stderr, "ctree init failed\n");
1325                 return -1;
1326         }
1327
1328         zero_end = 1;
1329         while(ac-- > 0) {
1330                 int old_mixed = mixed;
1331
1332                 file = av[optind++];
1333                 ret = check_mounted(file);
1334                 if (ret < 0) {
1335                         fprintf(stderr, "error checking %s mount status\n",
1336                                 file);
1337                         exit(1);
1338                 }
1339                 if (ret == 1) {
1340                         fprintf(stderr, "%s is mounted\n", file);
1341                         exit(1);
1342                 }
1343                 fd = open(file, O_RDWR);
1344                 if (fd < 0) {
1345                         fprintf(stderr, "unable to open %s\n", file);
1346                         exit(1);
1347                 }
1348                 ret = btrfs_device_already_in_root(root, fd,
1349                                                    BTRFS_SUPER_INFO_OFFSET);
1350                 if (ret) {
1351                         fprintf(stderr, "skipping duplicate device %s in FS\n",
1352                                 file);
1353                         close(fd);
1354                         continue;
1355                 }
1356                 ret = btrfs_prepare_device(fd, file, zero_end,
1357                                            &dev_block_count, &mixed);
1358                 mixed = old_mixed;
1359                 BUG_ON(ret);
1360
1361                 ret = btrfs_add_to_fsid(trans, root, fd, file, dev_block_count,
1362                                         sectorsize, sectorsize, sectorsize);
1363                 BUG_ON(ret);
1364                 btrfs_register_one_device(file);
1365         }
1366
1367 raid_groups:
1368         if (!source_dir_set) {
1369                 ret = create_raid_groups(trans, root, data_profile,
1370                                  metadata_profile, mixed);
1371                 BUG_ON(ret);
1372         }
1373
1374         ret = create_data_reloc_tree(trans, root);
1375         BUG_ON(ret);
1376
1377         if (mixed) {
1378                 struct btrfs_super_block *super = &root->fs_info->super_copy;
1379                 u64 flags = btrfs_super_incompat_flags(super);
1380
1381                 flags |= BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS;
1382                 btrfs_set_super_incompat_flags(super, flags);
1383         }
1384
1385         printf("fs created label %s on %s\n\tnodesize %u leafsize %u "
1386             "sectorsize %u size %s\n",
1387             label, first_file, nodesize, leafsize, sectorsize,
1388             pretty_sizes(btrfs_super_total_bytes(&root->fs_info->super_copy)));
1389
1390         printf("%s\n", BTRFS_BUILD_VERSION);
1391         btrfs_commit_transaction(trans, root);
1392
1393         if (source_dir_set) {
1394                 trans = btrfs_start_transaction(root, 1);
1395                 ret = create_chunks(trans, root,
1396                                     num_of_meta_chunks, size_of_data);
1397                 BUG_ON(ret);
1398                 btrfs_commit_transaction(trans, root);
1399
1400                 ret = make_image(source_dir, root, fd);
1401                 BUG_ON(ret);
1402         }
1403
1404         ret = close_ctree(root);
1405         BUG_ON(ret);
1406
1407         free(label);
1408         return 0;
1409 }
1410