c16aeb9a5fc79849b2147b65b379afa58a16f04c
[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 #include "kerncompat.h"
20
21 #include <sys/ioctl.h>
22 #include <sys/mount.h>
23 #include "ioctl.h"
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <sys/dir.h>
29 #include <fcntl.h>
30 #include <unistd.h>
31 #include <getopt.h>
32 #include <uuid/uuid.h>
33 #include <ctype.h>
34 #include <sys/xattr.h>
35 #include <limits.h>
36 #include <linux/limits.h>
37 #include <blkid/blkid.h>
38 #include <ftw.h>
39 #include "ctree.h"
40 #include "disk-io.h"
41 #include "volumes.h"
42 #include "transaction.h"
43 #include "utils.h"
44
45 static u64 index_cnt = 2;
46
47 struct directory_name_entry {
48         char *dir_name;
49         char *path;
50         ino_t inum;
51         struct list_head list;
52 };
53
54 static int make_root_dir(struct btrfs_root *root, int mixed)
55 {
56         struct btrfs_trans_handle *trans;
57         struct btrfs_key location;
58         u64 bytes_used;
59         u64 chunk_start = 0;
60         u64 chunk_size = 0;
61         int ret;
62
63         trans = btrfs_start_transaction(root, 1);
64         bytes_used = btrfs_super_bytes_used(root->fs_info->super_copy);
65
66         root->fs_info->system_allocs = 1;
67         ret = btrfs_make_block_group(trans, root, bytes_used,
68                                      BTRFS_BLOCK_GROUP_SYSTEM,
69                                      BTRFS_FIRST_CHUNK_TREE_OBJECTID,
70                                      0, BTRFS_MKFS_SYSTEM_GROUP_SIZE);
71         BUG_ON(ret);
72
73         if (mixed) {
74                 ret = btrfs_alloc_chunk(trans, root->fs_info->extent_root,
75                                         &chunk_start, &chunk_size,
76                                         BTRFS_BLOCK_GROUP_METADATA |
77                                         BTRFS_BLOCK_GROUP_DATA);
78                 if (ret == -ENOSPC) {
79                         fprintf(stderr,
80                                 "no space to alloc data/metadata chunk\n");
81                         goto err;
82                 }
83                 BUG_ON(ret);
84                 ret = btrfs_make_block_group(trans, root, 0,
85                                              BTRFS_BLOCK_GROUP_METADATA |
86                                              BTRFS_BLOCK_GROUP_DATA,
87                                              BTRFS_FIRST_CHUNK_TREE_OBJECTID,
88                                              chunk_start, chunk_size);
89                 BUG_ON(ret);
90                 printf("Created a data/metadata chunk of size %llu\n", chunk_size);
91         } else {
92                 ret = btrfs_alloc_chunk(trans, root->fs_info->extent_root,
93                                         &chunk_start, &chunk_size,
94                                         BTRFS_BLOCK_GROUP_METADATA);
95                 if (ret == -ENOSPC) {
96                         fprintf(stderr, "no space to alloc metadata chunk\n");
97                         goto err;
98                 }
99                 BUG_ON(ret);
100                 ret = btrfs_make_block_group(trans, root, 0,
101                                              BTRFS_BLOCK_GROUP_METADATA,
102                                              BTRFS_FIRST_CHUNK_TREE_OBJECTID,
103                                              chunk_start, chunk_size);
104                 BUG_ON(ret);
105         }
106
107         root->fs_info->system_allocs = 0;
108         btrfs_commit_transaction(trans, root);
109         trans = btrfs_start_transaction(root, 1);
110         BUG_ON(!trans);
111
112         if (!mixed) {
113                 ret = btrfs_alloc_chunk(trans, root->fs_info->extent_root,
114                                         &chunk_start, &chunk_size,
115                                         BTRFS_BLOCK_GROUP_DATA);
116                 if (ret == -ENOSPC) {
117                         fprintf(stderr, "no space to alloc data chunk\n");
118                         goto err;
119                 }
120                 BUG_ON(ret);
121                 ret = btrfs_make_block_group(trans, root, 0,
122                                              BTRFS_BLOCK_GROUP_DATA,
123                                              BTRFS_FIRST_CHUNK_TREE_OBJECTID,
124                                              chunk_start, chunk_size);
125                 BUG_ON(ret);
126         }
127
128         ret = btrfs_make_root_dir(trans, root->fs_info->tree_root,
129                               BTRFS_ROOT_TREE_DIR_OBJECTID);
130         if (ret)
131                 goto err;
132         ret = btrfs_make_root_dir(trans, root, BTRFS_FIRST_FREE_OBJECTID);
133         if (ret)
134                 goto err;
135         memcpy(&location, &root->fs_info->fs_root->root_key, sizeof(location));
136         location.offset = (u64)-1;
137         ret = btrfs_insert_dir_item(trans, root->fs_info->tree_root,
138                         "default", 7,
139                         btrfs_super_root_dir(root->fs_info->super_copy),
140                         &location, BTRFS_FT_DIR, 0);
141         if (ret)
142                 goto err;
143
144         ret = btrfs_insert_inode_ref(trans, root->fs_info->tree_root,
145                              "default", 7, location.objectid,
146                              BTRFS_ROOT_TREE_DIR_OBJECTID, 0);
147         if (ret)
148                 goto err;
149
150         btrfs_commit_transaction(trans, root);
151 err:
152         return ret;
153 }
154
155 static void __recow_root(struct btrfs_trans_handle *trans,
156                          struct btrfs_root *root)
157 {
158         int ret;
159         struct extent_buffer *tmp;
160
161         if (trans->transid != btrfs_root_generation(&root->root_item)) {
162                 extent_buffer_get(root->node);
163                 ret = __btrfs_cow_block(trans, root, root->node,
164                                         NULL, 0, &tmp, 0, 0);
165                 BUG_ON(ret);
166                 free_extent_buffer(tmp);
167         }
168 }
169
170 static void recow_roots(struct btrfs_trans_handle *trans,
171                        struct btrfs_root *root)
172 {
173         struct btrfs_fs_info *info = root->fs_info;
174
175         __recow_root(trans, info->fs_root);
176         __recow_root(trans, info->tree_root);
177         __recow_root(trans, info->extent_root);
178         __recow_root(trans, info->chunk_root);
179         __recow_root(trans, info->dev_root);
180         __recow_root(trans, info->csum_root);
181 }
182
183 static int create_one_raid_group(struct btrfs_trans_handle *trans,
184                               struct btrfs_root *root, u64 type)
185 {
186         u64 chunk_start;
187         u64 chunk_size;
188         int ret;
189
190         ret = btrfs_alloc_chunk(trans, root->fs_info->extent_root,
191                                 &chunk_start, &chunk_size, type);
192         if (ret == -ENOSPC) {
193                 fprintf(stderr, "not enough free space\n");
194                 exit(1);
195         }
196         BUG_ON(ret);
197         ret = btrfs_make_block_group(trans, root->fs_info->extent_root, 0,
198                                      type, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
199                                      chunk_start, chunk_size);
200         BUG_ON(ret);
201         return ret;
202 }
203
204 static int create_raid_groups(struct btrfs_trans_handle *trans,
205                               struct btrfs_root *root, u64 data_profile,
206                               int data_profile_opt, u64 metadata_profile,
207                               int mixed)
208 {
209         u64 num_devices = btrfs_super_num_devices(root->fs_info->super_copy);
210         int ret;
211
212         if (metadata_profile) {
213                 u64 meta_flags = BTRFS_BLOCK_GROUP_METADATA;
214
215                 ret = create_one_raid_group(trans, root,
216                                             BTRFS_BLOCK_GROUP_SYSTEM |
217                                             metadata_profile);
218                 BUG_ON(ret);
219
220                 if (mixed)
221                         meta_flags |= BTRFS_BLOCK_GROUP_DATA;
222
223                 ret = create_one_raid_group(trans, root, meta_flags |
224                                             metadata_profile);
225                 BUG_ON(ret);
226
227         }
228         if (!mixed && num_devices > 1 && data_profile) {
229                 ret = create_one_raid_group(trans, root,
230                                             BTRFS_BLOCK_GROUP_DATA |
231                                             data_profile);
232                 BUG_ON(ret);
233         }
234         recow_roots(trans, root);
235
236         return 0;
237 }
238
239 static int create_data_reloc_tree(struct btrfs_trans_handle *trans,
240                                   struct btrfs_root *root)
241 {
242         struct btrfs_key location;
243         struct btrfs_root_item root_item;
244         struct extent_buffer *tmp;
245         u64 objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
246         int ret;
247
248         ret = btrfs_copy_root(trans, root, root->node, &tmp, objectid);
249         BUG_ON(ret);
250
251         memcpy(&root_item, &root->root_item, sizeof(root_item));
252         btrfs_set_root_bytenr(&root_item, tmp->start);
253         btrfs_set_root_level(&root_item, btrfs_header_level(tmp));
254         btrfs_set_root_generation(&root_item, trans->transid);
255         free_extent_buffer(tmp);
256
257         location.objectid = objectid;
258         location.type = BTRFS_ROOT_ITEM_KEY;
259         location.offset = 0;
260         ret = btrfs_insert_root(trans, root->fs_info->tree_root,
261                                 &location, &root_item);
262         BUG_ON(ret);
263         return 0;
264 }
265
266
267 static void print_usage(void) __attribute__((noreturn));
268 static void print_usage(void)
269 {
270         fprintf(stderr, "usage: mkfs.btrfs [options] dev [ dev ... ]\n");
271         fprintf(stderr, "options:\n");
272         fprintf(stderr, "\t-A|--alloc-start START  the offset to start the FS\n");
273         fprintf(stderr, "\t-b|--byte-count SIZE    total number of bytes in the FS\n");
274         fprintf(stderr, "\t-d|--data PROFILE       data profile, raid0, raid1, raid5, raid6, raid10, dup or single\n");
275         fprintf(stderr, "\t-f|--force              force overwrite of existing filesystem\n");
276         fprintf(stderr, "\t-l|--leafsize SIZE      deprecated, alias for nodesize\n");
277         fprintf(stderr, "\t-L|--label LABEL        set a label\n");
278         fprintf(stderr, "\t-m|--metadata PROFILE   metadata profile, values like data profile\n");
279         fprintf(stderr, "\t-M|--mixed              mix metadata and data together\n");
280         fprintf(stderr, "\t-n|--nodesize SIZE      size of btree nodes\n");
281         fprintf(stderr, "\t-s|--sectorsize SIZE    min block allocation (may not mountable by current kernel)\n");
282         fprintf(stderr, "\t-r|--rootdir DIR        the source directory\n");
283         fprintf(stderr, "\t-K|--nodiscard          do not perform whole device TRIM\n");
284         fprintf(stderr, "\t-O|--features LIST      comma separated list of filesystem features, use '-O list-all' to list features\n");
285         fprintf(stderr, "\t-U|--uuid UUID          specify the filesystem UUID\n");
286         fprintf(stderr, "\t-V|--version            print the mkfs.btrfs version and exit\n");
287         fprintf(stderr, "%s\n", PACKAGE_STRING);
288         exit(1);
289 }
290
291 static void print_version(void) __attribute__((noreturn));
292 static void print_version(void)
293 {
294         fprintf(stderr, "mkfs.btrfs, part of %s\n", PACKAGE_STRING);
295         exit(0);
296 }
297
298 static u64 parse_profile(char *s)
299 {
300         if (strcmp(s, "raid0") == 0) {
301                 return BTRFS_BLOCK_GROUP_RAID0;
302         } else if (strcmp(s, "raid1") == 0) {
303                 return BTRFS_BLOCK_GROUP_RAID1;
304         } else if (strcmp(s, "raid5") == 0) {
305                 return BTRFS_BLOCK_GROUP_RAID5;
306         } else if (strcmp(s, "raid6") == 0) {
307                 return BTRFS_BLOCK_GROUP_RAID6;
308         } else if (strcmp(s, "raid10") == 0) {
309                 return BTRFS_BLOCK_GROUP_RAID10;
310         } else if (strcmp(s, "dup") == 0) {
311                 return BTRFS_BLOCK_GROUP_DUP;
312         } else if (strcmp(s, "single") == 0) {
313                 return 0;
314         } else {
315                 fprintf(stderr, "Unknown profile %s\n", s);
316                 print_usage();
317         }
318         /* not reached */
319         return 0;
320 }
321
322 static char *parse_label(char *input)
323 {
324         int len = strlen(input);
325
326         if (len >= BTRFS_LABEL_SIZE) {
327                 fprintf(stderr, "Label %s is too long (max %d)\n", input,
328                         BTRFS_LABEL_SIZE - 1);
329                 exit(1);
330         }
331         return strdup(input);
332 }
333
334 static int add_directory_items(struct btrfs_trans_handle *trans,
335                                struct btrfs_root *root, u64 objectid,
336                                ino_t parent_inum, const char *name,
337                                struct stat *st, int *dir_index_cnt)
338 {
339         int ret;
340         int name_len;
341         struct btrfs_key location;
342         u8 filetype = 0;
343
344         name_len = strlen(name);
345
346         location.objectid = objectid;
347         location.offset = 0;
348         btrfs_set_key_type(&location, BTRFS_INODE_ITEM_KEY);
349
350         if (S_ISDIR(st->st_mode))
351                 filetype = BTRFS_FT_DIR;
352         if (S_ISREG(st->st_mode))
353                 filetype = BTRFS_FT_REG_FILE;
354         if (S_ISLNK(st->st_mode))
355                 filetype = BTRFS_FT_SYMLINK;
356
357         ret = btrfs_insert_dir_item(trans, root, name, name_len,
358                                     parent_inum, &location,
359                                     filetype, index_cnt);
360         if (ret)
361                 return ret;
362         ret = btrfs_insert_inode_ref(trans, root, name, name_len,
363                                      objectid, parent_inum, index_cnt);
364         *dir_index_cnt = index_cnt;
365         index_cnt++;
366
367         return ret;
368 }
369
370 static int fill_inode_item(struct btrfs_trans_handle *trans,
371                            struct btrfs_root *root,
372                            struct btrfs_inode_item *dst, struct stat *src)
373 {
374         u64 blocks = 0;
375         u64 sectorsize = root->sectorsize;
376
377         /*
378          * btrfs_inode_item has some reserved fields
379          * and represents on-disk inode entry, so
380          * zero everything to prevent information leak
381          */
382         memset(dst, 0, sizeof (*dst));
383
384         btrfs_set_stack_inode_generation(dst, trans->transid);
385         btrfs_set_stack_inode_size(dst, src->st_size);
386         btrfs_set_stack_inode_nbytes(dst, 0);
387         btrfs_set_stack_inode_block_group(dst, 0);
388         btrfs_set_stack_inode_nlink(dst, src->st_nlink);
389         btrfs_set_stack_inode_uid(dst, src->st_uid);
390         btrfs_set_stack_inode_gid(dst, src->st_gid);
391         btrfs_set_stack_inode_mode(dst, src->st_mode);
392         btrfs_set_stack_inode_rdev(dst, 0);
393         btrfs_set_stack_inode_flags(dst, 0);
394         btrfs_set_stack_timespec_sec(&dst->atime, src->st_atime);
395         btrfs_set_stack_timespec_nsec(&dst->atime, 0);
396         btrfs_set_stack_timespec_sec(&dst->ctime, src->st_ctime);
397         btrfs_set_stack_timespec_nsec(&dst->ctime, 0);
398         btrfs_set_stack_timespec_sec(&dst->mtime, src->st_mtime);
399         btrfs_set_stack_timespec_nsec(&dst->mtime, 0);
400         btrfs_set_stack_timespec_sec(&dst->otime, 0);
401         btrfs_set_stack_timespec_nsec(&dst->otime, 0);
402
403         if (S_ISDIR(src->st_mode)) {
404                 btrfs_set_stack_inode_size(dst, 0);
405                 btrfs_set_stack_inode_nlink(dst, 1);
406         }
407         if (S_ISREG(src->st_mode)) {
408                 btrfs_set_stack_inode_size(dst, (u64)src->st_size);
409                 if (src->st_size <= BTRFS_MAX_INLINE_DATA_SIZE(root))
410                         btrfs_set_stack_inode_nbytes(dst, src->st_size);
411                 else {
412                         blocks = src->st_size / sectorsize;
413                         if (src->st_size % sectorsize)
414                                 blocks += 1;
415                         blocks *= sectorsize;
416                         btrfs_set_stack_inode_nbytes(dst, blocks);
417                 }
418         }
419         if (S_ISLNK(src->st_mode))
420                 btrfs_set_stack_inode_nbytes(dst, src->st_size + 1);
421
422         return 0;
423 }
424
425 static int directory_select(const struct direct *entry)
426 {
427         if ((strncmp(entry->d_name, ".", entry->d_reclen) == 0) ||
428                 (strncmp(entry->d_name, "..", entry->d_reclen) == 0))
429                 return 0;
430         else
431                 return 1;
432 }
433
434 static void free_namelist(struct direct **files, int count)
435 {
436         int i;
437
438         if (count < 0)
439                 return;
440
441         for (i = 0; i < count; ++i)
442                 free(files[i]);
443         free(files);
444 }
445
446 static u64 calculate_dir_inode_size(char *dirname)
447 {
448         int count, i;
449         struct direct **files, *cur_file;
450         u64 dir_inode_size = 0;
451
452         count = scandir(dirname, &files, directory_select, NULL);
453
454         for (i = 0; i < count; i++) {
455                 cur_file = files[i];
456                 dir_inode_size += strlen(cur_file->d_name);
457         }
458
459         free_namelist(files, count);
460
461         dir_inode_size *= 2;
462         return dir_inode_size;
463 }
464
465 static int add_inode_items(struct btrfs_trans_handle *trans,
466                            struct btrfs_root *root,
467                            struct stat *st, char *name,
468                            u64 self_objectid, ino_t parent_inum,
469                            int dir_index_cnt, struct btrfs_inode_item *inode_ret)
470 {
471         int ret;
472         struct btrfs_key inode_key;
473         struct btrfs_inode_item btrfs_inode;
474         u64 objectid;
475         u64 inode_size = 0;
476
477         fill_inode_item(trans, root, &btrfs_inode, st);
478         objectid = self_objectid;
479
480         if (S_ISDIR(st->st_mode)) {
481                 inode_size = calculate_dir_inode_size(name);
482                 btrfs_set_stack_inode_size(&btrfs_inode, inode_size);
483         }
484
485         inode_key.objectid = objectid;
486         inode_key.offset = 0;
487         btrfs_set_key_type(&inode_key, BTRFS_INODE_ITEM_KEY);
488
489         ret = btrfs_insert_inode(trans, root, objectid, &btrfs_inode);
490
491         *inode_ret = btrfs_inode;
492         return ret;
493 }
494
495 static int add_xattr_item(struct btrfs_trans_handle *trans,
496                           struct btrfs_root *root, u64 objectid,
497                           const char *file_name)
498 {
499         int ret;
500         int cur_name_len;
501         char xattr_list[XATTR_LIST_MAX];
502         char *cur_name;
503         char cur_value[XATTR_SIZE_MAX];
504         char delimiter = '\0';
505         char *next_location = xattr_list;
506
507         ret = llistxattr(file_name, xattr_list, XATTR_LIST_MAX);
508         if (ret < 0) {
509                 if(errno == ENOTSUP)
510                         return 0;
511                 fprintf(stderr, "get a list of xattr failed for %s\n",
512                         file_name);
513                 return ret;
514         }
515         if (ret == 0)
516                 return ret;
517
518         cur_name = strtok(xattr_list, &delimiter);
519         while (cur_name != NULL) {
520                 cur_name_len = strlen(cur_name);
521                 next_location += cur_name_len + 1;
522
523                 ret = getxattr(file_name, cur_name, cur_value, XATTR_SIZE_MAX);
524                 if (ret < 0) {
525                         if(errno == ENOTSUP)
526                                 return 0;
527                         fprintf(stderr, "get a xattr value failed for %s attr %s\n",
528                                 file_name, cur_name);
529                         return ret;
530                 }
531
532                 ret = btrfs_insert_xattr_item(trans, root, cur_name,
533                                               cur_name_len, cur_value,
534                                               ret, objectid);
535                 if (ret) {
536                         fprintf(stderr, "insert a xattr item failed for %s\n",
537                                 file_name);
538                 }
539
540                 cur_name = strtok(next_location, &delimiter);
541         }
542
543         return ret;
544 }
545
546 static int add_symbolic_link(struct btrfs_trans_handle *trans,
547                              struct btrfs_root *root,
548                              u64 objectid, const char *path_name)
549 {
550         int ret;
551         u64 sectorsize = root->sectorsize;
552         char *buf = malloc(sectorsize);
553
554         ret = readlink(path_name, buf, sectorsize);
555         if (ret <= 0) {
556                 fprintf(stderr, "readlink failed for %s\n", path_name);
557                 goto fail;
558         }
559         if (ret >= sectorsize) {
560                 fprintf(stderr, "symlink too long for %s", path_name);
561                 ret = -1;
562                 goto fail;
563         }
564
565         buf[ret] = '\0'; /* readlink does not do it for us */
566         ret = btrfs_insert_inline_extent(trans, root, objectid, 0,
567                                          buf, ret + 1);
568 fail:
569         free(buf);
570         return ret;
571 }
572
573 static int add_file_items(struct btrfs_trans_handle *trans,
574                           struct btrfs_root *root,
575                           struct btrfs_inode_item *btrfs_inode, u64 objectid,
576                           ino_t parent_inum, struct stat *st,
577                           const char *path_name, int out_fd)
578 {
579         int ret = -1;
580         ssize_t ret_read;
581         u64 bytes_read = 0;
582         struct btrfs_key key;
583         int blocks;
584         u32 sectorsize = root->sectorsize;
585         u64 first_block = 0;
586         u64 file_pos = 0;
587         u64 cur_bytes;
588         u64 total_bytes;
589         struct extent_buffer *eb = NULL;
590         int fd;
591
592         if (st->st_size == 0)
593                 return 0;
594
595         fd = open(path_name, O_RDONLY);
596         if (fd == -1) {
597                 fprintf(stderr, "%s open failed\n", path_name);
598                 return ret;
599         }
600
601         blocks = st->st_size / sectorsize;
602         if (st->st_size % sectorsize)
603                 blocks += 1;
604
605         if (st->st_size <= BTRFS_MAX_INLINE_DATA_SIZE(root)) {
606                 char *buffer = malloc(st->st_size);
607                 ret_read = pread64(fd, buffer, st->st_size, bytes_read);
608                 if (ret_read == -1) {
609                         fprintf(stderr, "%s read failed\n", path_name);
610                         free(buffer);
611                         goto end;
612                 }
613
614                 ret = btrfs_insert_inline_extent(trans, root, objectid, 0,
615                                                  buffer, st->st_size);
616                 free(buffer);
617                 goto end;
618         }
619
620         /* round up our st_size to the FS blocksize */
621         total_bytes = (u64)blocks * sectorsize;
622
623         /*
624          * do our IO in extent buffers so it can work
625          * against any raid type
626          */
627         eb = malloc(sizeof(*eb) + sectorsize);
628         if (!eb) {
629                 ret = -ENOMEM;
630                 goto end;
631         }
632         memset(eb, 0, sizeof(*eb) + sectorsize);
633
634 again:
635
636         /*
637          * keep our extent size at 1MB max, this makes it easier to work inside
638          * the tiny block groups created during mkfs
639          */
640         cur_bytes = min(total_bytes, 1024ULL * 1024);
641         ret = btrfs_reserve_extent(trans, root, cur_bytes, 0, 0, (u64)-1,
642                                    &key, 1);
643         if (ret)
644                 goto end;
645
646         first_block = key.objectid;
647         bytes_read = 0;
648
649         while (bytes_read < cur_bytes) {
650
651                 memset(eb->data, 0, sectorsize);
652
653                 ret_read = pread64(fd, eb->data, sectorsize, file_pos + bytes_read);
654                 if (ret_read == -1) {
655                         fprintf(stderr, "%s read failed\n", path_name);
656                         goto end;
657                 }
658
659                 eb->start = first_block + bytes_read;
660                 eb->len = sectorsize;
661
662                 /*
663                  * we're doing the csum before we record the extent, but
664                  * that's ok
665                  */
666                 ret = btrfs_csum_file_block(trans, root->fs_info->csum_root,
667                                             first_block + bytes_read + sectorsize,
668                                             first_block + bytes_read,
669                                             eb->data, sectorsize);
670                 if (ret)
671                         goto end;
672
673                 ret = write_and_map_eb(trans, root, eb);
674                 if (ret) {
675                         fprintf(stderr, "output file write failed\n");
676                         goto end;
677                 }
678
679                 bytes_read += sectorsize;
680         }
681
682         if (bytes_read) {
683                 ret = btrfs_record_file_extent(trans, root, objectid, btrfs_inode,
684                                                file_pos, first_block, cur_bytes);
685                 if (ret)
686                         goto end;
687
688         }
689
690         file_pos += cur_bytes;
691         total_bytes -= cur_bytes;
692
693         if (total_bytes)
694                 goto again;
695
696 end:
697         free(eb);
698         close(fd);
699         return ret;
700 }
701
702 static char *make_path(char *dir, char *name)
703 {
704         char *path;
705
706         path = malloc(strlen(dir) + strlen(name) + 2);
707         if (!path)
708                 return NULL;
709         strcpy(path, dir);
710         if (dir[strlen(dir) - 1] != '/')
711                 strcat(path, "/");
712         strcat(path, name);
713         return path;
714 }
715
716 static int traverse_directory(struct btrfs_trans_handle *trans,
717                               struct btrfs_root *root, char *dir_name,
718                               struct directory_name_entry *dir_head, int out_fd)
719 {
720         int ret = 0;
721
722         struct btrfs_inode_item cur_inode;
723         struct btrfs_inode_item *inode_item;
724         int count, i, dir_index_cnt;
725         struct direct **files;
726         struct stat st;
727         struct directory_name_entry *dir_entry, *parent_dir_entry;
728         struct direct *cur_file;
729         ino_t parent_inum, cur_inum;
730         ino_t highest_inum = 0;
731         char *parent_dir_name;
732         char real_path[PATH_MAX];
733         struct btrfs_path path;
734         struct extent_buffer *leaf;
735         struct btrfs_key root_dir_key;
736         u64 root_dir_inode_size = 0;
737
738         /* Add list for source directory */
739         dir_entry = malloc(sizeof(struct directory_name_entry));
740         dir_entry->dir_name = dir_name;
741         dir_entry->path = realpath(dir_name, real_path);
742         if (!dir_entry->path) {
743                 fprintf(stderr, "get directory real path error\n");
744                 ret = -1;
745                 goto fail_no_dir;
746         }
747
748         parent_inum = highest_inum + BTRFS_FIRST_FREE_OBJECTID;
749         dir_entry->inum = parent_inum;
750         list_add_tail(&dir_entry->list, &dir_head->list);
751
752         btrfs_init_path(&path);
753
754         root_dir_key.objectid = btrfs_root_dirid(&root->root_item);
755         root_dir_key.offset = 0;
756         btrfs_set_key_type(&root_dir_key, BTRFS_INODE_ITEM_KEY);
757         ret = btrfs_lookup_inode(trans, root, &path, &root_dir_key, 1);
758         if (ret) {
759                 fprintf(stderr, "root dir lookup error\n");
760                 goto fail_no_dir;
761         }
762
763         leaf = path.nodes[0];
764         inode_item = btrfs_item_ptr(leaf, path.slots[0],
765                                     struct btrfs_inode_item);
766
767         root_dir_inode_size = calculate_dir_inode_size(dir_name);
768         btrfs_set_inode_size(leaf, inode_item, root_dir_inode_size);
769         btrfs_mark_buffer_dirty(leaf);
770
771         btrfs_release_path(&path);
772
773         do {
774                 parent_dir_entry = list_entry(dir_head->list.next,
775                                               struct directory_name_entry,
776                                               list);
777                 list_del(&parent_dir_entry->list);
778
779                 parent_inum = parent_dir_entry->inum;
780                 parent_dir_name = parent_dir_entry->dir_name;
781                 if (chdir(parent_dir_entry->path)) {
782                         fprintf(stderr, "chdir error for %s\n",
783                                 parent_dir_name);
784                         ret = -1;
785                         goto fail_no_files;
786                 }
787
788                 count = scandir(parent_dir_entry->path, &files,
789                                 directory_select, NULL);
790                 if (count == -1)
791                 {
792                         fprintf(stderr, "scandir for %s failed: %s\n",
793                                 parent_dir_name, strerror (errno));
794                         ret = -1;
795                         goto fail;
796                 }
797
798                 for (i = 0; i < count; i++) {
799                         cur_file = files[i];
800
801                         if (lstat(cur_file->d_name, &st) == -1) {
802                                 fprintf(stderr, "lstat failed for file %s\n",
803                                         cur_file->d_name);
804                                 ret = -1;
805                                 goto fail;
806                         }
807
808                         cur_inum = st.st_ino;
809                         ret = add_directory_items(trans, root,
810                                                   cur_inum, parent_inum,
811                                                   cur_file->d_name,
812                                                   &st, &dir_index_cnt);
813                         if (ret) {
814                                 fprintf(stderr, "add_directory_items failed\n");
815                                 goto fail;
816                         }
817
818                         ret = add_inode_items(trans, root, &st,
819                                               cur_file->d_name, cur_inum,
820                                               parent_inum, dir_index_cnt,
821                                               &cur_inode);
822                         if (ret == -EEXIST) {
823                                 BUG_ON(st.st_nlink <= 1);
824                                 continue;
825                         }
826                         if (ret) {
827                                 fprintf(stderr, "add_inode_items failed\n");
828                                 goto fail;
829                         }
830
831                         ret = add_xattr_item(trans, root,
832                                              cur_inum, cur_file->d_name);
833                         if (ret) {
834                                 fprintf(stderr, "add_xattr_item failed\n");
835                                 if(ret != -ENOTSUP)
836                                         goto fail;
837                         }
838
839                         if (S_ISDIR(st.st_mode)) {
840                                 dir_entry = malloc(sizeof(struct directory_name_entry));
841                                 dir_entry->dir_name = cur_file->d_name;
842                                 dir_entry->path = make_path(parent_dir_entry->path,
843                                                             cur_file->d_name);
844                                 dir_entry->inum = cur_inum;
845                                 list_add_tail(&dir_entry->list, &dir_head->list);
846                         } else if (S_ISREG(st.st_mode)) {
847                                 ret = add_file_items(trans, root, &cur_inode,
848                                                      cur_inum, parent_inum, &st,
849                                                      cur_file->d_name, out_fd);
850                                 if (ret) {
851                                         fprintf(stderr, "add_file_items failed\n");
852                                         goto fail;
853                                 }
854                         } else if (S_ISLNK(st.st_mode)) {
855                                 ret = add_symbolic_link(trans, root,
856                                                         cur_inum, cur_file->d_name);
857                                 if (ret) {
858                                         fprintf(stderr, "add_symbolic_link failed\n");
859                                         goto fail;
860                                 }
861                         }
862                 }
863
864                 free_namelist(files, count);
865                 free(parent_dir_entry);
866
867                 index_cnt = 2;
868
869         } while (!list_empty(&dir_head->list));
870
871 out:
872         return !!ret;
873 fail:
874         free_namelist(files, count);
875 fail_no_files:
876         free(parent_dir_entry);
877         goto out;
878 fail_no_dir:
879         free(dir_entry);
880         goto out;
881 }
882
883 static int open_target(char *output_name)
884 {
885         int output_fd;
886         output_fd = open(output_name, O_CREAT | O_RDWR | O_TRUNC,
887                          S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
888
889         return output_fd;
890 }
891
892 static int create_chunks(struct btrfs_trans_handle *trans,
893                          struct btrfs_root *root, u64 num_of_meta_chunks,
894                          u64 size_of_data)
895 {
896         u64 chunk_start;
897         u64 chunk_size;
898         u64 meta_type = BTRFS_BLOCK_GROUP_METADATA;
899         u64 data_type = BTRFS_BLOCK_GROUP_DATA;
900         u64 minimum_data_chunk_size = 8 * 1024 * 1024;
901         u64 i;
902         int ret;
903
904         for (i = 0; i < num_of_meta_chunks; i++) {
905                 ret = btrfs_alloc_chunk(trans, root->fs_info->extent_root,
906                                         &chunk_start, &chunk_size, meta_type);
907                 BUG_ON(ret);
908                 ret = btrfs_make_block_group(trans, root->fs_info->extent_root, 0,
909                                              meta_type, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
910                                              chunk_start, chunk_size);
911                 BUG_ON(ret);
912                 set_extent_dirty(&root->fs_info->free_space_cache,
913                                  chunk_start, chunk_start + chunk_size - 1, 0);
914         }
915
916         if (size_of_data < minimum_data_chunk_size)
917                 size_of_data = minimum_data_chunk_size;
918
919         ret = btrfs_alloc_data_chunk(trans, root->fs_info->extent_root,
920                                      &chunk_start, size_of_data, data_type);
921         BUG_ON(ret);
922         ret = btrfs_make_block_group(trans, root->fs_info->extent_root, 0,
923                                      data_type, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
924                                      chunk_start, size_of_data);
925         BUG_ON(ret);
926         set_extent_dirty(&root->fs_info->free_space_cache,
927                          chunk_start, chunk_start + size_of_data - 1, 0);
928         return ret;
929 }
930
931 static int make_image(char *source_dir, struct btrfs_root *root, int out_fd)
932 {
933         int ret;
934         struct btrfs_trans_handle *trans;
935
936         struct stat root_st;
937
938         struct directory_name_entry dir_head;
939
940         struct directory_name_entry *dir_entry = NULL;
941
942         ret = lstat(source_dir, &root_st);
943         if (ret) {
944                 fprintf(stderr, "unable to lstat the %s\n", source_dir);
945                 goto out;
946         }
947
948         INIT_LIST_HEAD(&dir_head.list);
949
950         trans = btrfs_start_transaction(root, 1);
951         ret = traverse_directory(trans, root, source_dir, &dir_head, out_fd);
952         if (ret) {
953                 fprintf(stderr, "unable to traverse_directory\n");
954                 goto fail;
955         }
956         btrfs_commit_transaction(trans, root);
957
958         printf("Making image is completed.\n");
959         return 0;
960 fail:
961         while (!list_empty(&dir_head.list)) {
962                 dir_entry = list_entry(dir_head.list.next,
963                                        struct directory_name_entry, list);
964                 list_del(&dir_entry->list);
965                 free(dir_entry);
966         }
967 out:
968         fprintf(stderr, "Making image is aborted.\n");
969         return -1;
970 }
971
972 /*
973  * This ignores symlinks with unreadable targets and subdirs that can't
974  * be read.  It's a best-effort to give a rough estimate of the size of
975  * a subdir.  It doesn't guarantee that prepopulating btrfs from this
976  * tree won't still run out of space. 
977  *
978  * The rounding up to 4096 is questionable.  Previous code used du -B 4096.
979  */
980 static u64 global_total_size;
981 static int ftw_add_entry_size(const char *fpath, const struct stat *st,
982                               int type)
983 {
984         if (type == FTW_F || type == FTW_D)
985                 global_total_size += round_up(st->st_size, 4096);
986
987         return 0;
988 }
989
990 static u64 size_sourcedir(char *dir_name, u64 sectorsize,
991                           u64 *num_of_meta_chunks_ret, u64 *size_of_data_ret)
992 {
993         u64 dir_size = 0;
994         u64 total_size = 0;
995         int ret;
996         u64 default_chunk_size = 8 * 1024 * 1024;       /* 8MB */
997         u64 allocated_meta_size = 8 * 1024 * 1024;      /* 8MB */
998         u64 allocated_total_size = 20 * 1024 * 1024;    /* 20MB */
999         u64 num_of_meta_chunks = 0;
1000         u64 num_of_data_chunks = 0;
1001         u64 num_of_allocated_meta_chunks =
1002                         allocated_meta_size / default_chunk_size;
1003
1004         global_total_size = 0;
1005         ret = ftw(dir_name, ftw_add_entry_size, 10);
1006         dir_size = global_total_size;
1007         if (ret < 0) {
1008                 fprintf(stderr, "ftw subdir walk of '%s' failed: %s\n",
1009                         dir_name, strerror(errno));
1010                 exit(1);
1011         }
1012
1013         num_of_data_chunks = (dir_size + default_chunk_size - 1) /
1014                 default_chunk_size;
1015
1016         num_of_meta_chunks = (dir_size / 2) / default_chunk_size;
1017         if (((dir_size / 2) % default_chunk_size) != 0)
1018                 num_of_meta_chunks++;
1019         if (num_of_meta_chunks <= num_of_allocated_meta_chunks)
1020                 num_of_meta_chunks = 0;
1021         else
1022                 num_of_meta_chunks -= num_of_allocated_meta_chunks;
1023
1024         total_size = allocated_total_size +
1025                      (num_of_data_chunks * default_chunk_size) +
1026                      (num_of_meta_chunks * default_chunk_size);
1027
1028         *num_of_meta_chunks_ret = num_of_meta_chunks;
1029         *size_of_data_ret = num_of_data_chunks * default_chunk_size;
1030         return total_size;
1031 }
1032
1033 static int zero_output_file(int out_fd, u64 size, u32 sectorsize)
1034 {
1035         int len = sectorsize;
1036         int loop_num = size / sectorsize;
1037         u64 location = 0;
1038         char *buf = malloc(len);
1039         int ret = 0, i;
1040         ssize_t written;
1041
1042         if (!buf)
1043                 return -ENOMEM;
1044         memset(buf, 0, len);
1045         for (i = 0; i < loop_num; i++) {
1046                 written = pwrite64(out_fd, buf, len, location);
1047                 if (written != len)
1048                         ret = -EIO;
1049                 location += sectorsize;
1050         }
1051         free(buf);
1052         return ret;
1053 }
1054
1055 static int is_ssd(const char *file)
1056 {
1057         blkid_probe probe;
1058         char wholedisk[32];
1059         char sysfs_path[PATH_MAX];
1060         dev_t devno;
1061         int fd;
1062         char rotational;
1063         int ret;
1064
1065         probe = blkid_new_probe_from_filename(file);
1066         if (!probe)
1067                 return 0;
1068
1069         /* Device number of this disk (possibly a partition) */
1070         devno = blkid_probe_get_devno(probe);
1071         if (!devno) {
1072                 blkid_free_probe(probe);
1073                 return 0;
1074         }
1075
1076         /* Get whole disk name (not full path) for this devno */
1077         ret = blkid_devno_to_wholedisk(devno,
1078                         wholedisk, sizeof(wholedisk), NULL);
1079         if (ret) {
1080                 blkid_free_probe(probe);
1081                 return 0;
1082         }
1083
1084         snprintf(sysfs_path, PATH_MAX, "/sys/block/%s/queue/rotational",
1085                  wholedisk);
1086
1087         blkid_free_probe(probe);
1088
1089         fd = open(sysfs_path, O_RDONLY);
1090         if (fd < 0) {
1091                 return 0;
1092         }
1093
1094         if (read(fd, &rotational, sizeof(char)) < sizeof(char)) {
1095                 close(fd);
1096                 return 0;
1097         }
1098         close(fd);
1099
1100         return !atoi((const char *)&rotational);
1101 }
1102
1103 int main(int ac, char **av)
1104 {
1105         char *file;
1106         struct btrfs_root *root;
1107         struct btrfs_trans_handle *trans;
1108         char *label = NULL;
1109         char *first_file;
1110         u64 block_count = 0;
1111         u64 dev_block_count = 0;
1112         u64 blocks[7];
1113         u64 alloc_start = 0;
1114         u64 metadata_profile = 0;
1115         u64 data_profile = 0;
1116         u32 nodesize = max_t(u32, sysconf(_SC_PAGESIZE),
1117                         BTRFS_MKFS_DEFAULT_NODE_SIZE);
1118         u32 sectorsize = 4096;
1119         u32 stripesize = 4096;
1120         int zero_end = 1;
1121         int fd;
1122         int ret;
1123         int i;
1124         int mixed = 0;
1125         int nodesize_forced = 0;
1126         int data_profile_opt = 0;
1127         int metadata_profile_opt = 0;
1128         int discard = 1;
1129         int ssd = 0;
1130         int force_overwrite = 0;
1131
1132         char *source_dir = NULL;
1133         int source_dir_set = 0;
1134         u64 num_of_meta_chunks = 0;
1135         u64 size_of_data = 0;
1136         u64 source_dir_size = 0;
1137         int dev_cnt = 0;
1138         int saved_optind;
1139         char estr[100];
1140         char *fs_uuid = NULL;
1141         u64 features = BTRFS_MKFS_DEFAULT_FEATURES;
1142
1143         while(1) {
1144                 int c;
1145                 static const struct option long_options[] = {
1146                         { "alloc-start", required_argument, NULL, 'A'},
1147                         { "byte-count", required_argument, NULL, 'b' },
1148                         { "force", no_argument, NULL, 'f' },
1149                         { "leafsize", required_argument, NULL, 'l' },
1150                         { "label", required_argument, NULL, 'L'},
1151                         { "metadata", required_argument, NULL, 'm' },
1152                         { "mixed", no_argument, NULL, 'M' },
1153                         { "nodesize", required_argument, NULL, 'n' },
1154                         { "sectorsize", required_argument, NULL, 's' },
1155                         { "data", required_argument, NULL, 'd' },
1156                         { "version", no_argument, NULL, 'V' },
1157                         { "rootdir", required_argument, NULL, 'r' },
1158                         { "nodiscard", no_argument, NULL, 'K' },
1159                         { "features", required_argument, NULL, 'O' },
1160                         { "uuid", required_argument, NULL, 'U' },
1161                         { NULL, 0, NULL, 0}
1162                 };
1163
1164                 c = getopt_long(ac, av, "A:b:fl:n:s:m:d:L:O:r:U:VMK",
1165                                 long_options, NULL);
1166                 if (c < 0)
1167                         break;
1168                 switch(c) {
1169                         case 'A':
1170                                 alloc_start = parse_size(optarg);
1171                                 break;
1172                         case 'f':
1173                                 force_overwrite = 1;
1174                                 break;
1175                         case 'd':
1176                                 data_profile = parse_profile(optarg);
1177                                 data_profile_opt = 1;
1178                                 break;
1179                         case 'l':
1180                                 fprintf(stderr,
1181                         "WARNING: --leafsize is deprecated, use --nodesize\n");
1182                         case 'n':
1183                                 nodesize = parse_size(optarg);
1184                                 nodesize_forced = 1;
1185                                 break;
1186                         case 'L':
1187                                 label = parse_label(optarg);
1188                                 break;
1189                         case 'm':
1190                                 metadata_profile = parse_profile(optarg);
1191                                 metadata_profile_opt = 1;
1192                                 break;
1193                         case 'M':
1194                                 mixed = 1;
1195                                 break;
1196                         case 'O': {
1197                                 char *orig = strdup(optarg);
1198                                 char *tmp = orig;
1199
1200                                 tmp = btrfs_parse_fs_features(tmp, &features);
1201                                 if (tmp) {
1202                                         fprintf(stderr,
1203                                                 "Unrecognized filesystem feature '%s'\n",
1204                                                         tmp);
1205                                         free(orig);
1206                                         exit(1);
1207                                 }
1208                                 free(orig);
1209                                 if (features & BTRFS_FEATURE_LIST_ALL) {
1210                                         btrfs_list_all_fs_features(0);
1211                                         exit(0);
1212                                 }
1213                                 break;
1214                                 }
1215                         case 's':
1216                                 sectorsize = parse_size(optarg);
1217                                 break;
1218                         case 'b':
1219                                 block_count = parse_size(optarg);
1220                                 if (block_count <= BTRFS_MKFS_SMALL_VOLUME_SIZE) {
1221                                         fprintf(stdout,
1222                                 "SMALL VOLUME: forcing mixed metadata/data groups\n");
1223                                         mixed = 1;
1224                                 }
1225                                 zero_end = 0;
1226                                 break;
1227                         case 'V':
1228                                 print_version();
1229                                 break;
1230                         case 'r':
1231                                 source_dir = optarg;
1232                                 source_dir_set = 1;
1233                                 break;
1234                         case 'U':
1235                                 fs_uuid = optarg;
1236                                 break;
1237                         case 'K':
1238                                 discard = 0;
1239                                 break;
1240                         default:
1241                                 print_usage();
1242                 }
1243         }
1244         sectorsize = max(sectorsize, (u32)sysconf(_SC_PAGESIZE));
1245         if (btrfs_check_nodesize(nodesize, sectorsize))
1246                 exit(1);
1247         saved_optind = optind;
1248         dev_cnt = ac - optind;
1249         if (dev_cnt == 0)
1250                 print_usage();
1251
1252         if (source_dir_set && dev_cnt > 1) {
1253                 fprintf(stderr,
1254                         "The -r option is limited to a single device\n");
1255                 exit(1);
1256         }
1257
1258         if (fs_uuid) {
1259                 uuid_t dummy_uuid;
1260
1261                 if (uuid_parse(fs_uuid, dummy_uuid) != 0) {
1262                         fprintf(stderr, "could not parse UUID: %s\n", fs_uuid);
1263                         exit(1);
1264                 }
1265                 if (!test_uuid_unique(fs_uuid)) {
1266                         fprintf(stderr, "non-unique UUID: %s\n", fs_uuid);
1267                         exit(1);
1268                 }
1269         }
1270         
1271         while (dev_cnt-- > 0) {
1272                 file = av[optind++];
1273                 if (is_block_device(file))
1274                         if (test_dev_for_mkfs(file, force_overwrite, estr)) {
1275                                 fprintf(stderr, "Error: %s", estr);
1276                                 exit(1);
1277                         }
1278         }
1279
1280         optind = saved_optind;
1281         dev_cnt = ac - optind;
1282
1283         file = av[optind++];
1284         ssd = is_ssd(file);
1285
1286         if (is_vol_small(file)) {
1287                 printf("SMALL VOLUME: forcing mixed metadata/data groups\n");
1288                 mixed = 1;
1289         }
1290
1291         /*
1292         * Set default profiles according to number of added devices.
1293         * For mixed groups defaults are single/single.
1294         */
1295         if (!mixed) {
1296                 if (!metadata_profile_opt) {
1297                         if (dev_cnt == 1 && ssd)
1298                                 printf("Detected a SSD, turning off metadata "
1299                                 "duplication.  Mkfs with -m dup if you want to "
1300                                 "force metadata duplication.\n");
1301
1302                         metadata_profile = (dev_cnt > 1) ?
1303                                         BTRFS_BLOCK_GROUP_RAID1 : (ssd) ?
1304                                         0: BTRFS_BLOCK_GROUP_DUP;
1305                 }
1306                 if (!data_profile_opt) {
1307                         data_profile = (dev_cnt > 1) ?
1308                                 BTRFS_BLOCK_GROUP_RAID0 : 0; /* raid0 or single */
1309                 }
1310         } else {
1311                 u32 best_nodesize = max_t(u32, sysconf(_SC_PAGESIZE), sectorsize);
1312
1313                 if (metadata_profile_opt || data_profile_opt) {
1314                         if (metadata_profile != data_profile) {
1315                                 fprintf(stderr,
1316         "ERROR: With mixed block groups data and metadata profiles must be the same\n");
1317                                 exit(1);
1318                         }
1319                 }
1320
1321                 if (!nodesize_forced) {
1322                         nodesize = best_nodesize;
1323                         if (btrfs_check_nodesize(nodesize, sectorsize))
1324                                 exit(1);
1325                 }
1326                 if (nodesize != sectorsize) {
1327                         fprintf(stderr, "Error: mixed metadata/data block groups "
1328                                 "require metadata blocksizes equal to the sectorsize\n");
1329                         exit(1);
1330                 }
1331         }
1332
1333         /* Check device/block_count after the nodesize is determined */
1334         if (block_count && block_count < btrfs_min_dev_size(nodesize)) {
1335                 fprintf(stderr,
1336                         "Size '%llu' is too small to make a usable filesystem\n",
1337                         block_count);
1338                 fprintf(stderr,
1339                         "Minimum size for btrfs filesystem is %llu\n",
1340                         btrfs_min_dev_size(nodesize));
1341                 exit(1);
1342         }
1343         for (i = saved_optind; i < saved_optind + dev_cnt; i++) {
1344                 char *path;
1345
1346                 path = av[i];
1347                 ret = test_minimum_size(path, nodesize);
1348                 if (ret < 0) {
1349                         fprintf(stderr, "Failed to check size for '%s': %s\n",
1350                                 path, strerror(-ret));
1351                         exit (1);
1352                 }
1353                 if (ret > 0) {
1354                         fprintf(stderr,
1355                                 "'%s' is too small to make a usable filesystem\n",
1356                                 path);
1357                         fprintf(stderr,
1358                                 "Minimum size for each btrfs device is %llu.\n",
1359                                 btrfs_min_dev_size(nodesize));
1360                         exit(1);
1361                 }
1362         }
1363         ret = test_num_disk_vs_raid(metadata_profile, data_profile,
1364                         dev_cnt, mixed, estr);
1365         if (ret) {
1366                 fprintf(stderr, "Error: %s\n", estr);
1367                 exit(1);
1368         }
1369
1370         /* if we are here that means all devs are good to btrfsify */
1371         printf("%s\n", PACKAGE_STRING);
1372         printf("See %s for more information.\n\n", PACKAGE_URL);
1373
1374         dev_cnt--;
1375
1376         if (!source_dir_set) {
1377                 /*
1378                  * open without O_EXCL so that the problem should not
1379                  * occur by the following processing.
1380                  * (btrfs_register_one_device() fails if O_EXCL is on)
1381                  */
1382                 fd = open(file, O_RDWR);
1383                 if (fd < 0) {
1384                         fprintf(stderr, "unable to open %s: %s\n", file,
1385                                 strerror(errno));
1386                         exit(1);
1387                 }
1388                 first_file = file;
1389                 ret = btrfs_prepare_device(fd, file, zero_end, &dev_block_count,
1390                                            block_count, &mixed, discard);
1391                 if (ret) {
1392                         close(fd);
1393                         exit(1);
1394                 }
1395                 if (block_count && block_count > dev_block_count) {
1396                         fprintf(stderr, "%s is smaller than requested size\n", file);
1397                         exit(1);
1398                 }
1399         } else {
1400                 fd = open_target(file);
1401                 if (fd < 0) {
1402                         fprintf(stderr, "unable to open the %s\n", file);
1403                         exit(1);
1404                 }
1405
1406                 first_file = file;
1407                 source_dir_size = size_sourcedir(source_dir, sectorsize,
1408                                              &num_of_meta_chunks, &size_of_data);
1409                 if(block_count < source_dir_size)
1410                         block_count = source_dir_size;
1411                 ret = zero_output_file(fd, block_count, sectorsize);
1412                 if (ret) {
1413                         fprintf(stderr, "unable to zero the output file\n");
1414                         exit(1);
1415                 }
1416                 /* our "device" is the new image file */
1417                 dev_block_count = block_count;
1418         }
1419
1420         /* To create the first block group and chunk 0 in make_btrfs */
1421         if (dev_block_count < BTRFS_MKFS_SYSTEM_GROUP_SIZE) {
1422                 fprintf(stderr, "device is too small to make filesystem\n");
1423                 exit(1);
1424         }
1425
1426         blocks[0] = BTRFS_SUPER_INFO_OFFSET;
1427         for (i = 1; i < 7; i++) {
1428                 blocks[i] = BTRFS_SUPER_INFO_OFFSET + 1024 * 1024 +
1429                         nodesize * i;
1430         }
1431
1432         /*
1433          * FS features that can be set by other means than -O
1434          * just set the bit here
1435          */
1436         if (mixed)
1437                 features |= BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS;
1438
1439         if ((data_profile | metadata_profile) &
1440             (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6)) {
1441                 features |= BTRFS_FEATURE_INCOMPAT_RAID56;
1442         }
1443
1444         btrfs_process_fs_features(features);
1445
1446         ret = make_btrfs(fd, file, label, fs_uuid, blocks, dev_block_count,
1447                          nodesize, sectorsize, stripesize, features);
1448         if (ret) {
1449                 fprintf(stderr, "error during mkfs: %s\n", strerror(-ret));
1450                 exit(1);
1451         }
1452
1453         root = open_ctree(file, 0, OPEN_CTREE_WRITES);
1454         if (!root) {
1455                 fprintf(stderr, "Open ctree failed\n");
1456                 close(fd);
1457                 exit(1);
1458         }
1459         root->fs_info->alloc_start = alloc_start;
1460
1461         ret = make_root_dir(root, mixed);
1462         if (ret) {
1463                 fprintf(stderr, "failed to setup the root directory\n");
1464                 exit(1);
1465         }
1466
1467         trans = btrfs_start_transaction(root, 1);
1468
1469         btrfs_register_one_device(file);
1470
1471         if (dev_cnt == 0)
1472                 goto raid_groups;
1473
1474         while (dev_cnt-- > 0) {
1475                 int old_mixed = mixed;
1476
1477                 file = av[optind++];
1478
1479                 /*
1480                  * open without O_EXCL so that the problem should not
1481                  * occur by the following processing.
1482                  * (btrfs_register_one_device() fails if O_EXCL is on)
1483                  */
1484                 fd = open(file, O_RDWR);
1485                 if (fd < 0) {
1486                         fprintf(stderr, "unable to open %s: %s\n", file,
1487                                 strerror(errno));
1488                         exit(1);
1489                 }
1490                 ret = btrfs_device_already_in_root(root, fd,
1491                                                    BTRFS_SUPER_INFO_OFFSET);
1492                 if (ret) {
1493                         fprintf(stderr, "skipping duplicate device %s in FS\n",
1494                                 file);
1495                         close(fd);
1496                         continue;
1497                 }
1498                 ret = btrfs_prepare_device(fd, file, zero_end, &dev_block_count,
1499                                            block_count, &mixed, discard);
1500                 if (ret) {
1501                         close(fd);
1502                         exit(1);
1503                 }
1504                 mixed = old_mixed;
1505
1506                 ret = btrfs_add_to_fsid(trans, root, fd, file, dev_block_count,
1507                                         sectorsize, sectorsize, sectorsize);
1508                 BUG_ON(ret);
1509                 btrfs_register_one_device(file);
1510         }
1511
1512 raid_groups:
1513         if (!source_dir_set) {
1514                 ret = create_raid_groups(trans, root, data_profile,
1515                                  data_profile_opt, metadata_profile,
1516                                  mixed);
1517                 BUG_ON(ret);
1518         }
1519
1520         ret = create_data_reloc_tree(trans, root);
1521         BUG_ON(ret);
1522
1523         printf("fs created label %s on %s\n\tnodesize %u leafsize %u "
1524             "sectorsize %u size %s\n",
1525             label, first_file, nodesize, nodesize, sectorsize,
1526             pretty_size(btrfs_super_total_bytes(root->fs_info->super_copy)));
1527
1528         btrfs_commit_transaction(trans, root);
1529
1530         if (source_dir_set) {
1531                 trans = btrfs_start_transaction(root, 1);
1532                 ret = create_chunks(trans, root,
1533                                     num_of_meta_chunks, size_of_data);
1534                 BUG_ON(ret);
1535                 btrfs_commit_transaction(trans, root);
1536
1537                 ret = make_image(source_dir, root, fd);
1538                 BUG_ON(ret);
1539         }
1540
1541         ret = close_ctree(root);
1542         BUG_ON(ret);
1543         free(label);
1544         return 0;
1545 }