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