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