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