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