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