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