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