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