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