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