69df39b782d6c777f204eb691cfa50c7aac4bc23
[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         ret = lstat(source_dir, &root_st);
1024         if (ret) {
1025                 fprintf(stderr, "unable to lstat the %s\n", source_dir);
1026                 goto fail;
1027         }
1028
1029         INIT_LIST_HEAD(&dir_head.list);
1030
1031         trans = btrfs_start_transaction(root, 1);
1032         ret = traverse_directory(trans, root, source_dir, &dir_head, out_fd);
1033         if (ret) {
1034                 fprintf(stderr, "unable to traverse_directory\n");
1035                 goto fail;
1036         }
1037         btrfs_commit_transaction(trans, root);
1038
1039         printf("Making image is completed.\n");
1040         return 0;
1041 fail:
1042         fprintf(stderr, "Making image is aborted.\n");
1043         return -1;
1044 }
1045
1046 /*
1047  * This ignores symlinks with unreadable targets and subdirs that can't
1048  * be read.  It's a best-effort to give a rough estimate of the size of
1049  * a subdir.  It doesn't guarantee that prepopulating btrfs from this
1050  * tree won't still run out of space. 
1051  *
1052  * The rounding up to 4096 is questionable.  Previous code used du -B 4096.
1053  */
1054 static u64 global_total_size;
1055 static int ftw_add_entry_size(const char *fpath, const struct stat *st,
1056                               int type)
1057 {
1058         if (type == FTW_F || type == FTW_D)
1059                 global_total_size += round_up(st->st_size, 4096);
1060
1061         return 0;
1062 }
1063
1064 static u64 size_sourcedir(char *dir_name, u64 sectorsize,
1065                           u64 *num_of_meta_chunks_ret, u64 *size_of_data_ret)
1066 {
1067         u64 dir_size = 0;
1068         u64 total_size = 0;
1069         int ret;
1070         u64 default_chunk_size = 8 * 1024 * 1024;       /* 8MB */
1071         u64 allocated_meta_size = 8 * 1024 * 1024;      /* 8MB */
1072         u64 allocated_total_size = 20 * 1024 * 1024;    /* 20MB */
1073         u64 num_of_meta_chunks = 0;
1074         u64 num_of_allocated_meta_chunks =
1075                         allocated_meta_size / default_chunk_size;
1076
1077         global_total_size = 0;
1078         ret = ftw(dir_name, ftw_add_entry_size, 10);
1079         dir_size = global_total_size;
1080         if (ret < 0) {
1081                 fprintf(stderr, "ftw subdir walk of '%s' failed: %s\n",
1082                         dir_name, strerror(errno));
1083                 exit(1);
1084         }
1085
1086         num_of_meta_chunks = (dir_size / 2) / default_chunk_size;
1087         if (((dir_size / 2) % default_chunk_size) != 0)
1088                 num_of_meta_chunks++;
1089         if (num_of_meta_chunks <= num_of_allocated_meta_chunks)
1090                 num_of_meta_chunks = 0;
1091         else
1092                 num_of_meta_chunks -= num_of_allocated_meta_chunks;
1093
1094         total_size = allocated_total_size + dir_size +
1095                      (num_of_meta_chunks * default_chunk_size);
1096
1097         *num_of_meta_chunks_ret = num_of_meta_chunks;
1098
1099         return total_size;
1100 }
1101
1102 static int zero_output_file(int out_fd, u64 size, u32 sectorsize)
1103 {
1104         int len = sectorsize;
1105         int loop_num = size / sectorsize;
1106         u64 location = 0;
1107         char *buf = malloc(len);
1108         int ret = 0, i;
1109         ssize_t written;
1110
1111         if (!buf)
1112                 return -ENOMEM;
1113         memset(buf, 0, len);
1114         for (i = 0; i < loop_num; i++) {
1115                 written = pwrite64(out_fd, buf, len, location);
1116                 if (written != len)
1117                         ret = -EIO;
1118                 location += sectorsize;
1119         }
1120         free(buf);
1121         return ret;
1122 }
1123
1124 static int check_leaf_or_node_size(u32 size, u32 sectorsize)
1125 {
1126         if (size < sectorsize) {
1127                 fprintf(stderr,
1128                         "Illegal leafsize (or nodesize) %u (smaller than %u)\n",
1129                         size, sectorsize);
1130                 return -1;
1131         } else if (size > BTRFS_MAX_METADATA_BLOCKSIZE) {
1132                 fprintf(stderr,
1133                         "Illegal leafsize (or nodesize) %u (larger than %u)\n",
1134                         size, BTRFS_MAX_METADATA_BLOCKSIZE);
1135                 return -1;
1136         } else if (size & (sectorsize - 1)) {
1137                 fprintf(stderr,
1138                         "Illegal leafsize (or nodesize) %u (not align to %u)\n",
1139                         size, sectorsize);
1140                 return -1;
1141         }
1142         return 0;
1143 }
1144
1145 static int is_ssd(const char *file)
1146 {
1147         blkid_probe probe;
1148         char wholedisk[32];
1149         char sysfs_path[PATH_MAX];
1150         dev_t devno;
1151         int fd;
1152         char rotational;
1153
1154         probe = blkid_new_probe_from_filename(file);
1155         if (!probe)
1156                 return 0;
1157
1158         /* Device number of this disk (possibly a partition) */
1159         devno = blkid_probe_get_devno(probe);
1160         if (!devno)
1161                 return 0;
1162
1163         /* Get whole disk name (not full path) for this devno */
1164         blkid_devno_to_wholedisk(devno, wholedisk, sizeof(wholedisk), NULL);
1165
1166         snprintf(sysfs_path, PATH_MAX, "/sys/block/%s/queue/rotational",
1167                  wholedisk);
1168
1169         blkid_free_probe(probe);
1170
1171         fd = open(sysfs_path, O_RDONLY);
1172         if (fd < 0) {
1173                 return 0;
1174         }
1175
1176         if (read(fd, &rotational, sizeof(char)) < sizeof(char)) {
1177                 close(fd);
1178                 return 0;
1179         }
1180         close(fd);
1181
1182         return !atoi((const char *)&rotational);
1183 }
1184
1185 #define BTRFS_FEATURE_LIST_ALL          (1ULL << 63)
1186
1187 static const struct btrfs_fs_feature {
1188         const char *name;
1189         u64 flag;
1190         const char *desc;
1191 } mkfs_features[] = {
1192         { "mixed-bg", BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS,
1193                 "mixed data and metadata block groups" },
1194         { "extref", BTRFS_FEATURE_INCOMPAT_EXTENDED_IREF,
1195                 "increased hardlink limit per file to 65536" },
1196         { "raid56", BTRFS_FEATURE_INCOMPAT_RAID56,
1197                 "raid56 extended format" },
1198         { "skinny-metadata", BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA,
1199                 "reduced-size metadata extent refs" },
1200         /* Keep this one last */
1201         { "list-all", BTRFS_FEATURE_LIST_ALL, NULL }
1202 };
1203
1204 static void list_all_fs_features(void)
1205 {
1206         int i;
1207
1208         fprintf(stderr, "Filesystem features available at mkfs time:\n");
1209         for (i = 0; i < ARRAY_SIZE(mkfs_features) - 1; i++) {
1210                 fprintf(stderr, "%-20s- %s (0x%llx)\n",
1211                                 mkfs_features[i].name,
1212                                 mkfs_features[i].desc,
1213                                 mkfs_features[i].flag);
1214         }
1215 }
1216
1217 static int parse_one_fs_feature(const char *name, u64 *flags)
1218 {
1219         int i;
1220         int found = 0;
1221
1222         for (i = 0; i < ARRAY_SIZE(mkfs_features); i++) {
1223                 if (!strcmp(mkfs_features[i].name, name)) {
1224                         *flags |= mkfs_features[i].flag;
1225                         found = 1;
1226                 }
1227         }
1228
1229         return !found;
1230 }
1231
1232 static void process_fs_features(u64 flags)
1233 {
1234         int i;
1235
1236         for (i = 0; i < ARRAY_SIZE(mkfs_features); i++) {
1237                 if (flags & mkfs_features[i].flag) {
1238                         fprintf(stderr,
1239                                 "Turning ON incompat feature '%s': %s\n",
1240                                 mkfs_features[i].name,
1241                                 mkfs_features[i].desc);
1242                 }
1243         }
1244 }
1245
1246
1247 /*
1248  * Return NULL if all features were parsed fine, otherwise return the name of
1249  * the first unparsed.
1250  */
1251 static char* parse_fs_features(char *namelist, u64 *flags)
1252 {
1253         char *this_char;
1254         char *save_ptr = NULL; /* Satisfy static checkers */
1255
1256         for (this_char = strtok_r(namelist, ",", &save_ptr);
1257              this_char != NULL;
1258              this_char = strtok_r(NULL, ",", &save_ptr)) {
1259                 if (parse_one_fs_feature(this_char, flags))
1260                         return this_char;
1261         }
1262
1263         return NULL;
1264 }
1265
1266 int main(int ac, char **av)
1267 {
1268         char *file;
1269         struct btrfs_root *root;
1270         struct btrfs_trans_handle *trans;
1271         char *label = NULL;
1272         char *first_file;
1273         u64 block_count = 0;
1274         u64 dev_block_count = 0;
1275         u64 blocks[7];
1276         u64 alloc_start = 0;
1277         u64 metadata_profile = 0;
1278         u64 data_profile = 0;
1279         u32 leafsize = sysconf(_SC_PAGESIZE);
1280         u32 sectorsize = 4096;
1281         u32 nodesize = leafsize;
1282         u32 stripesize = 4096;
1283         int zero_end = 1;
1284         int option_index = 0;
1285         int fd;
1286         int ret;
1287         int i;
1288         int mixed = 0;
1289         int data_profile_opt = 0;
1290         int metadata_profile_opt = 0;
1291         int nodiscard = 0;
1292         int ssd = 0;
1293         int force_overwrite = 0;
1294
1295         char *source_dir = NULL;
1296         int source_dir_set = 0;
1297         u64 num_of_meta_chunks = 0;
1298         u64 size_of_data = 0;
1299         u64 source_dir_size = 0;
1300         int dev_cnt = 0;
1301         int saved_optind;
1302         char estr[100];
1303         u64 features = 0;
1304
1305         while(1) {
1306                 int c;
1307                 c = getopt_long(ac, av, "A:b:fl:n:s:m:d:L:O:r:VMK",
1308                                 long_options, &option_index);
1309                 if (c < 0)
1310                         break;
1311                 switch(c) {
1312                         case 'A':
1313                                 alloc_start = parse_size(optarg);
1314                                 break;
1315                         case 'f':
1316                                 force_overwrite = 1;
1317                                 break;
1318                         case 'd':
1319                                 data_profile = parse_profile(optarg);
1320                                 data_profile_opt = 1;
1321                                 break;
1322                         case 'l':
1323                         case 'n':
1324                                 nodesize = parse_size(optarg);
1325                                 leafsize = parse_size(optarg);
1326                                 break;
1327                         case 'L':
1328                                 label = parse_label(optarg);
1329                                 break;
1330                         case 'm':
1331                                 metadata_profile = parse_profile(optarg);
1332                                 metadata_profile_opt = 1;
1333                                 break;
1334                         case 'M':
1335                                 mixed = 1;
1336                                 break;
1337                         case 'O': {
1338                                 char *orig = strdup(optarg);
1339                                 char *tmp = orig;
1340
1341                                 tmp = parse_fs_features(tmp, &features);
1342                                 if (tmp) {
1343                                         fprintf(stderr,
1344                                                 "Unrecognized filesystem feature '%s'\n",
1345                                                         tmp);
1346                                         free(orig);
1347                                         exit(1);
1348                                 }
1349                                 free(orig);
1350                                 if (features & BTRFS_FEATURE_LIST_ALL) {
1351                                         list_all_fs_features();
1352                                         exit(0);
1353                                 }
1354                                 break;
1355                                 }
1356                         case 's':
1357                                 sectorsize = parse_size(optarg);
1358                                 break;
1359                         case 'b':
1360                                 block_count = parse_size(optarg);
1361                                 if (block_count <= 1024*1024*1024) {
1362                                         printf("SMALL VOLUME: forcing mixed "
1363                                                "metadata/data groups\n");
1364                                         mixed = 1;
1365                                 }
1366                                 zero_end = 0;
1367                                 break;
1368                         case 'V':
1369                                 print_version();
1370                                 break;
1371                         case 'r':
1372                                 source_dir = optarg;
1373                                 source_dir_set = 1;
1374                                 break;
1375                         case 'K':
1376                                 nodiscard=1;
1377                                 break;
1378                         default:
1379                                 print_usage();
1380                 }
1381         }
1382         sectorsize = max(sectorsize, (u32)sysconf(_SC_PAGESIZE));
1383         if (check_leaf_or_node_size(leafsize, sectorsize))
1384                 exit(1);
1385         if (check_leaf_or_node_size(nodesize, sectorsize))
1386                 exit(1);
1387         saved_optind = optind;
1388         dev_cnt = ac - optind;
1389         if (dev_cnt == 0)
1390                 print_usage();
1391
1392         if (source_dir_set && dev_cnt > 1) {
1393                 fprintf(stderr,
1394                         "The -r option is limited to a single device\n");
1395                 exit(1);
1396         }
1397         while (dev_cnt-- > 0) {
1398                 file = av[optind++];
1399                 if (is_block_device(file))
1400                         if (test_dev_for_mkfs(file, force_overwrite, estr)) {
1401                                 fprintf(stderr, "Error: %s", estr);
1402                                 exit(1);
1403                         }
1404         }
1405
1406         optind = saved_optind;
1407         dev_cnt = ac - optind;
1408
1409         file = av[optind++];
1410         ssd = is_ssd(file);
1411
1412         if (is_vol_small(file)) {
1413                 printf("SMALL VOLUME: forcing mixed metadata/data groups\n");
1414                 mixed = 1;
1415                 if (metadata_profile != data_profile) {
1416                         if (metadata_profile_opt || data_profile_opt) {
1417                                 fprintf(stderr,
1418         "With mixed block groups data and metadata profiles must be the same\n");
1419                                 exit(1);
1420                         }
1421                 }
1422         }
1423         /*
1424         * Set default profiles according to number of added devices.
1425         * For mixed groups defaults are single/single.
1426         */
1427         if (!mixed) {
1428                 if (!metadata_profile_opt) {
1429                         if (dev_cnt == 1 && ssd)
1430                                 printf("Detected a SSD, turning off metadata "
1431                                 "duplication.  Mkfs with -m dup if you want to "
1432                                 "force metadata duplication.\n");
1433
1434                         metadata_profile = (dev_cnt > 1) ?
1435                                         BTRFS_BLOCK_GROUP_RAID1 : (ssd) ?
1436                                         0: BTRFS_BLOCK_GROUP_DUP;
1437                 }
1438                 if (!data_profile_opt) {
1439                         data_profile = (dev_cnt > 1) ?
1440                                 BTRFS_BLOCK_GROUP_RAID0 : 0; /* raid0 or single */
1441                 }
1442         } else {
1443                 metadata_profile = 0;
1444                 data_profile = 0;
1445         }
1446
1447         ret = test_num_disk_vs_raid(metadata_profile, data_profile,
1448                         dev_cnt, mixed, estr);
1449         if (ret) {
1450                 fprintf(stderr, "Error: %s\n", estr);
1451                 exit(1);
1452         }
1453
1454         /* if we are here that means all devs are good to btrfsify */
1455         printf("\nWARNING! - %s IS EXPERIMENTAL\n", BTRFS_BUILD_VERSION);
1456         printf("WARNING! - see http://btrfs.wiki.kernel.org before using\n\n");
1457
1458         dev_cnt--;
1459
1460         if (!source_dir_set) {
1461                 /*
1462                  * open without O_EXCL so that the problem should not
1463                  * occur by the following processing.
1464                  * (btrfs_register_one_device() fails if O_EXCL is on)
1465                  */
1466                 fd = open(file, O_RDWR);
1467                 if (fd < 0) {
1468                         fprintf(stderr, "unable to open %s: %s\n", file,
1469                                 strerror(errno));
1470                         exit(1);
1471                 }
1472                 first_file = file;
1473                 ret = btrfs_prepare_device(fd, file, zero_end, &dev_block_count,
1474                                            block_count, &mixed, nodiscard);
1475                 if (block_count && block_count > dev_block_count) {
1476                         fprintf(stderr, "%s is smaller than requested size\n", file);
1477                         exit(1);
1478                 }
1479         } else {
1480                 fd = open_target(file);
1481                 if (fd < 0) {
1482                         fprintf(stderr, "unable to open the %s\n", file);
1483                         exit(1);
1484                 }
1485
1486                 first_file = file;
1487                 source_dir_size = size_sourcedir(source_dir, sectorsize,
1488                                              &num_of_meta_chunks, &size_of_data);
1489                 if(block_count < source_dir_size)
1490                         block_count = source_dir_size;
1491                 ret = zero_output_file(fd, block_count, sectorsize);
1492                 if (ret) {
1493                         fprintf(stderr, "unable to zero the output file\n");
1494                         exit(1);
1495                 }
1496                 /* our "device" is the new image file */
1497                 dev_block_count = block_count;
1498         }
1499
1500
1501         blocks[0] = BTRFS_SUPER_INFO_OFFSET;
1502         for (i = 1; i < 7; i++) {
1503                 blocks[i] = BTRFS_SUPER_INFO_OFFSET + 1024 * 1024 +
1504                         leafsize * i;
1505         }
1506
1507         /*
1508          * FS features that can be set by other means than -O
1509          * just set the bit here
1510          */
1511         if (mixed)
1512                 features |= BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS;
1513
1514         if ((data_profile | metadata_profile) &
1515             (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6)) {
1516                 features |= BTRFS_FEATURE_INCOMPAT_RAID56;
1517         }
1518
1519         process_fs_features(features);
1520
1521         ret = make_btrfs(fd, file, label, blocks, dev_block_count,
1522                          nodesize, leafsize,
1523                          sectorsize, stripesize, features);
1524         if (ret) {
1525                 fprintf(stderr, "error during mkfs: %s\n", strerror(-ret));
1526                 exit(1);
1527         }
1528
1529         root = open_ctree(file, 0, O_RDWR);
1530         if (!root) {
1531                 fprintf(stderr, "Open ctree failed\n");
1532                 close(fd);
1533                 exit(1);
1534         }
1535         root->fs_info->alloc_start = alloc_start;
1536
1537         ret = make_root_dir(root, mixed);
1538         if (ret) {
1539                 fprintf(stderr, "failed to setup the root directory\n");
1540                 exit(1);
1541         }
1542
1543         trans = btrfs_start_transaction(root, 1);
1544
1545         if (dev_cnt == 0)
1546                 goto raid_groups;
1547
1548         btrfs_register_one_device(file);
1549
1550         zero_end = 1;
1551         while (dev_cnt-- > 0) {
1552                 int old_mixed = mixed;
1553
1554                 file = av[optind++];
1555
1556                 /*
1557                  * open without O_EXCL so that the problem should not
1558                  * occur by the following processing.
1559                  * (btrfs_register_one_device() fails if O_EXCL is on)
1560                  */
1561                 fd = open(file, O_RDWR);
1562                 if (fd < 0) {
1563                         fprintf(stderr, "unable to open %s: %s\n", file,
1564                                 strerror(errno));
1565                         exit(1);
1566                 }
1567                 ret = btrfs_device_already_in_root(root, fd,
1568                                                    BTRFS_SUPER_INFO_OFFSET);
1569                 if (ret) {
1570                         fprintf(stderr, "skipping duplicate device %s in FS\n",
1571                                 file);
1572                         close(fd);
1573                         continue;
1574                 }
1575                 ret = btrfs_prepare_device(fd, file, zero_end, &dev_block_count,
1576                                            block_count, &mixed, nodiscard);
1577                 mixed = old_mixed;
1578                 BUG_ON(ret);
1579
1580                 ret = btrfs_add_to_fsid(trans, root, fd, file, dev_block_count,
1581                                         sectorsize, sectorsize, sectorsize);
1582                 BUG_ON(ret);
1583                 btrfs_register_one_device(file);
1584         }
1585
1586 raid_groups:
1587         if (!source_dir_set) {
1588                 ret = create_raid_groups(trans, root, data_profile,
1589                                  data_profile_opt, metadata_profile,
1590                                  metadata_profile_opt, mixed, ssd);
1591                 BUG_ON(ret);
1592         }
1593
1594         ret = create_data_reloc_tree(trans, root);
1595         BUG_ON(ret);
1596
1597         printf("fs created label %s on %s\n\tnodesize %u leafsize %u "
1598             "sectorsize %u size %s\n",
1599             label, first_file, nodesize, leafsize, sectorsize,
1600             pretty_size(btrfs_super_total_bytes(root->fs_info->super_copy)));
1601
1602         printf("%s\n", BTRFS_BUILD_VERSION);
1603         btrfs_commit_transaction(trans, root);
1604
1605         if (source_dir_set) {
1606                 trans = btrfs_start_transaction(root, 1);
1607                 ret = create_chunks(trans, root,
1608                                     num_of_meta_chunks, size_of_data);
1609                 BUG_ON(ret);
1610                 btrfs_commit_transaction(trans, root);
1611
1612                 ret = make_image(source_dir, root, fd);
1613                 BUG_ON(ret);
1614         }
1615
1616         ret = close_ctree(root);
1617         BUG_ON(ret);
1618         free(label);
1619         return 0;
1620 }