btrfs-progs: doc quota, sort subcommands alphabetically
[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 struct option long_options[] = {
344         { "alloc-start", 1, NULL, 'A'},
345         { "byte-count", 1, NULL, 'b' },
346         { "force", 0, NULL, 'f' },
347         { "leafsize", 1, NULL, 'l' },
348         { "label", 1, NULL, 'L'},
349         { "metadata", 1, NULL, 'm' },
350         { "mixed", 0, NULL, 'M' },
351         { "nodesize", 1, NULL, 'n' },
352         { "sectorsize", 1, NULL, 's' },
353         { "data", 1, NULL, 'd' },
354         { "version", 0, NULL, 'V' },
355         { "rootdir", 1, NULL, 'r' },
356         { "nodiscard", 0, NULL, 'K' },
357         { "features", 1, NULL, 'O' },
358         { "uuid", required_argument, NULL, 'U' },
359         { NULL, 0, NULL, 0}
360 };
361
362 static int add_directory_items(struct btrfs_trans_handle *trans,
363                                struct btrfs_root *root, u64 objectid,
364                                ino_t parent_inum, const char *name,
365                                struct stat *st, int *dir_index_cnt)
366 {
367         int ret;
368         int name_len;
369         struct btrfs_key location;
370         u8 filetype = 0;
371
372         name_len = strlen(name);
373
374         location.objectid = objectid;
375         location.offset = 0;
376         btrfs_set_key_type(&location, BTRFS_INODE_ITEM_KEY);
377
378         if (S_ISDIR(st->st_mode))
379                 filetype = BTRFS_FT_DIR;
380         if (S_ISREG(st->st_mode))
381                 filetype = BTRFS_FT_REG_FILE;
382         if (S_ISLNK(st->st_mode))
383                 filetype = BTRFS_FT_SYMLINK;
384
385         ret = btrfs_insert_dir_item(trans, root, name, name_len,
386                                     parent_inum, &location,
387                                     filetype, index_cnt);
388         if (ret)
389                 return ret;
390         ret = btrfs_insert_inode_ref(trans, root, name, name_len,
391                                      objectid, parent_inum, index_cnt);
392         *dir_index_cnt = index_cnt;
393         index_cnt++;
394
395         return ret;
396 }
397
398 static int fill_inode_item(struct btrfs_trans_handle *trans,
399                            struct btrfs_root *root,
400                            struct btrfs_inode_item *dst, struct stat *src)
401 {
402         u64 blocks = 0;
403         u64 sectorsize = root->sectorsize;
404
405         /*
406          * btrfs_inode_item has some reserved fields
407          * and represents on-disk inode entry, so
408          * zero everything to prevent information leak
409          */
410         memset(dst, 0, sizeof (*dst));
411
412         btrfs_set_stack_inode_generation(dst, trans->transid);
413         btrfs_set_stack_inode_size(dst, src->st_size);
414         btrfs_set_stack_inode_nbytes(dst, 0);
415         btrfs_set_stack_inode_block_group(dst, 0);
416         btrfs_set_stack_inode_nlink(dst, src->st_nlink);
417         btrfs_set_stack_inode_uid(dst, src->st_uid);
418         btrfs_set_stack_inode_gid(dst, src->st_gid);
419         btrfs_set_stack_inode_mode(dst, src->st_mode);
420         btrfs_set_stack_inode_rdev(dst, 0);
421         btrfs_set_stack_inode_flags(dst, 0);
422         btrfs_set_stack_timespec_sec(&dst->atime, src->st_atime);
423         btrfs_set_stack_timespec_nsec(&dst->atime, 0);
424         btrfs_set_stack_timespec_sec(&dst->ctime, src->st_ctime);
425         btrfs_set_stack_timespec_nsec(&dst->ctime, 0);
426         btrfs_set_stack_timespec_sec(&dst->mtime, src->st_mtime);
427         btrfs_set_stack_timespec_nsec(&dst->mtime, 0);
428         btrfs_set_stack_timespec_sec(&dst->otime, 0);
429         btrfs_set_stack_timespec_nsec(&dst->otime, 0);
430
431         if (S_ISDIR(src->st_mode)) {
432                 btrfs_set_stack_inode_size(dst, 0);
433                 btrfs_set_stack_inode_nlink(dst, 1);
434         }
435         if (S_ISREG(src->st_mode)) {
436                 btrfs_set_stack_inode_size(dst, (u64)src->st_size);
437                 if (src->st_size <= BTRFS_MAX_INLINE_DATA_SIZE(root))
438                         btrfs_set_stack_inode_nbytes(dst, src->st_size);
439                 else {
440                         blocks = src->st_size / sectorsize;
441                         if (src->st_size % sectorsize)
442                                 blocks += 1;
443                         blocks *= sectorsize;
444                         btrfs_set_stack_inode_nbytes(dst, blocks);
445                 }
446         }
447         if (S_ISLNK(src->st_mode))
448                 btrfs_set_stack_inode_nbytes(dst, src->st_size + 1);
449
450         return 0;
451 }
452
453 static int directory_select(const struct direct *entry)
454 {
455         if ((strncmp(entry->d_name, ".", entry->d_reclen) == 0) ||
456                 (strncmp(entry->d_name, "..", entry->d_reclen) == 0))
457                 return 0;
458         else
459                 return 1;
460 }
461
462 static void free_namelist(struct direct **files, int count)
463 {
464         int i;
465
466         if (count < 0)
467                 return;
468
469         for (i = 0; i < count; ++i)
470                 free(files[i]);
471         free(files);
472 }
473
474 static u64 calculate_dir_inode_size(char *dirname)
475 {
476         int count, i;
477         struct direct **files, *cur_file;
478         u64 dir_inode_size = 0;
479
480         count = scandir(dirname, &files, directory_select, NULL);
481
482         for (i = 0; i < count; i++) {
483                 cur_file = files[i];
484                 dir_inode_size += strlen(cur_file->d_name);
485         }
486
487         free_namelist(files, count);
488
489         dir_inode_size *= 2;
490         return dir_inode_size;
491 }
492
493 static int add_inode_items(struct btrfs_trans_handle *trans,
494                            struct btrfs_root *root,
495                            struct stat *st, char *name,
496                            u64 self_objectid, ino_t parent_inum,
497                            int dir_index_cnt, struct btrfs_inode_item *inode_ret)
498 {
499         int ret;
500         struct btrfs_key inode_key;
501         struct btrfs_inode_item btrfs_inode;
502         u64 objectid;
503         u64 inode_size = 0;
504
505         fill_inode_item(trans, root, &btrfs_inode, st);
506         objectid = self_objectid;
507
508         if (S_ISDIR(st->st_mode)) {
509                 inode_size = calculate_dir_inode_size(name);
510                 btrfs_set_stack_inode_size(&btrfs_inode, inode_size);
511         }
512
513         inode_key.objectid = objectid;
514         inode_key.offset = 0;
515         btrfs_set_key_type(&inode_key, BTRFS_INODE_ITEM_KEY);
516
517         ret = btrfs_insert_inode(trans, root, objectid, &btrfs_inode);
518
519         *inode_ret = btrfs_inode;
520         return ret;
521 }
522
523 static int add_xattr_item(struct btrfs_trans_handle *trans,
524                           struct btrfs_root *root, u64 objectid,
525                           const char *file_name)
526 {
527         int ret;
528         int cur_name_len;
529         char xattr_list[XATTR_LIST_MAX];
530         char *cur_name;
531         char cur_value[XATTR_SIZE_MAX];
532         char delimiter = '\0';
533         char *next_location = xattr_list;
534
535         ret = llistxattr(file_name, xattr_list, XATTR_LIST_MAX);
536         if (ret < 0) {
537                 if(errno == ENOTSUP)
538                         return 0;
539                 fprintf(stderr, "get a list of xattr failed for %s\n",
540                         file_name);
541                 return ret;
542         }
543         if (ret == 0)
544                 return ret;
545
546         cur_name = strtok(xattr_list, &delimiter);
547         while (cur_name != NULL) {
548                 cur_name_len = strlen(cur_name);
549                 next_location += cur_name_len + 1;
550
551                 ret = getxattr(file_name, cur_name, cur_value, XATTR_SIZE_MAX);
552                 if (ret < 0) {
553                         if(errno == ENOTSUP)
554                                 return 0;
555                         fprintf(stderr, "get a xattr value failed for %s attr %s\n",
556                                 file_name, cur_name);
557                         return ret;
558                 }
559
560                 ret = btrfs_insert_xattr_item(trans, root, cur_name,
561                                               cur_name_len, cur_value,
562                                               ret, objectid);
563                 if (ret) {
564                         fprintf(stderr, "insert a xattr item failed for %s\n",
565                                 file_name);
566                 }
567
568                 cur_name = strtok(next_location, &delimiter);
569         }
570
571         return ret;
572 }
573
574 static int add_symbolic_link(struct btrfs_trans_handle *trans,
575                              struct btrfs_root *root,
576                              u64 objectid, const char *path_name)
577 {
578         int ret;
579         u64 sectorsize = root->sectorsize;
580         char *buf = malloc(sectorsize);
581
582         ret = readlink(path_name, buf, sectorsize);
583         if (ret <= 0) {
584                 fprintf(stderr, "readlink failed for %s\n", path_name);
585                 goto fail;
586         }
587         if (ret >= sectorsize) {
588                 fprintf(stderr, "symlink too long for %s", path_name);
589                 ret = -1;
590                 goto fail;
591         }
592
593         buf[ret] = '\0'; /* readlink does not do it for us */
594         ret = btrfs_insert_inline_extent(trans, root, objectid, 0,
595                                          buf, ret + 1);
596 fail:
597         free(buf);
598         return ret;
599 }
600
601 static int add_file_items(struct btrfs_trans_handle *trans,
602                           struct btrfs_root *root,
603                           struct btrfs_inode_item *btrfs_inode, u64 objectid,
604                           ino_t parent_inum, struct stat *st,
605                           const char *path_name, int out_fd)
606 {
607         int ret = -1;
608         ssize_t ret_read;
609         u64 bytes_read = 0;
610         struct btrfs_key key;
611         int blocks;
612         u32 sectorsize = root->sectorsize;
613         u64 first_block = 0;
614         u64 file_pos = 0;
615         u64 cur_bytes;
616         u64 total_bytes;
617         struct extent_buffer *eb = NULL;
618         int fd;
619
620         if (st->st_size == 0)
621                 return 0;
622
623         fd = open(path_name, O_RDONLY);
624         if (fd == -1) {
625                 fprintf(stderr, "%s open failed\n", path_name);
626                 return ret;
627         }
628
629         blocks = st->st_size / sectorsize;
630         if (st->st_size % sectorsize)
631                 blocks += 1;
632
633         if (st->st_size <= BTRFS_MAX_INLINE_DATA_SIZE(root)) {
634                 char *buffer = malloc(st->st_size);
635                 ret_read = pread64(fd, buffer, st->st_size, bytes_read);
636                 if (ret_read == -1) {
637                         fprintf(stderr, "%s read failed\n", path_name);
638                         free(buffer);
639                         goto end;
640                 }
641
642                 ret = btrfs_insert_inline_extent(trans, root, objectid, 0,
643                                                  buffer, st->st_size);
644                 free(buffer);
645                 goto end;
646         }
647
648         /* round up our st_size to the FS blocksize */
649         total_bytes = (u64)blocks * sectorsize;
650
651         /*
652          * do our IO in extent buffers so it can work
653          * against any raid type
654          */
655         eb = malloc(sizeof(*eb) + sectorsize);
656         if (!eb) {
657                 ret = -ENOMEM;
658                 goto end;
659         }
660         memset(eb, 0, sizeof(*eb) + sectorsize);
661
662 again:
663
664         /*
665          * keep our extent size at 1MB max, this makes it easier to work inside
666          * the tiny block groups created during mkfs
667          */
668         cur_bytes = min(total_bytes, 1024ULL * 1024);
669         ret = btrfs_reserve_extent(trans, root, cur_bytes, 0, 0, (u64)-1,
670                                    &key, 1);
671         if (ret)
672                 goto end;
673
674         first_block = key.objectid;
675         bytes_read = 0;
676
677         while (bytes_read < cur_bytes) {
678
679                 memset(eb->data, 0, sectorsize);
680
681                 ret_read = pread64(fd, eb->data, sectorsize, file_pos + bytes_read);
682                 if (ret_read == -1) {
683                         fprintf(stderr, "%s read failed\n", path_name);
684                         goto end;
685                 }
686
687                 eb->start = first_block + bytes_read;
688                 eb->len = sectorsize;
689
690                 /*
691                  * we're doing the csum before we record the extent, but
692                  * that's ok
693                  */
694                 ret = btrfs_csum_file_block(trans, root->fs_info->csum_root,
695                                             first_block + bytes_read + sectorsize,
696                                             first_block + bytes_read,
697                                             eb->data, sectorsize);
698                 if (ret)
699                         goto end;
700
701                 ret = write_and_map_eb(trans, root, eb);
702                 if (ret) {
703                         fprintf(stderr, "output file write failed\n");
704                         goto end;
705                 }
706
707                 bytes_read += sectorsize;
708         }
709
710         if (bytes_read) {
711                 ret = btrfs_record_file_extent(trans, root, objectid, btrfs_inode,
712                                                file_pos, first_block, cur_bytes);
713                 if (ret)
714                         goto end;
715
716         }
717
718         file_pos += cur_bytes;
719         total_bytes -= cur_bytes;
720
721         if (total_bytes)
722                 goto again;
723
724 end:
725         free(eb);
726         close(fd);
727         return ret;
728 }
729
730 static char *make_path(char *dir, char *name)
731 {
732         char *path;
733
734         path = malloc(strlen(dir) + strlen(name) + 2);
735         if (!path)
736                 return NULL;
737         strcpy(path, dir);
738         if (dir[strlen(dir) - 1] != '/')
739                 strcat(path, "/");
740         strcat(path, name);
741         return path;
742 }
743
744 static int traverse_directory(struct btrfs_trans_handle *trans,
745                               struct btrfs_root *root, char *dir_name,
746                               struct directory_name_entry *dir_head, int out_fd)
747 {
748         int ret = 0;
749
750         struct btrfs_inode_item cur_inode;
751         struct btrfs_inode_item *inode_item;
752         int count, i, dir_index_cnt;
753         struct direct **files;
754         struct stat st;
755         struct directory_name_entry *dir_entry, *parent_dir_entry;
756         struct direct *cur_file;
757         ino_t parent_inum, cur_inum;
758         ino_t highest_inum = 0;
759         char *parent_dir_name;
760         char real_path[PATH_MAX];
761         struct btrfs_path path;
762         struct extent_buffer *leaf;
763         struct btrfs_key root_dir_key;
764         u64 root_dir_inode_size = 0;
765
766         /* Add list for source directory */
767         dir_entry = malloc(sizeof(struct directory_name_entry));
768         dir_entry->dir_name = dir_name;
769         dir_entry->path = realpath(dir_name, real_path);
770         if (!dir_entry->path) {
771                 fprintf(stderr, "get directory real path error\n");
772                 ret = -1;
773                 goto fail_no_dir;
774         }
775
776         parent_inum = highest_inum + BTRFS_FIRST_FREE_OBJECTID;
777         dir_entry->inum = parent_inum;
778         list_add_tail(&dir_entry->list, &dir_head->list);
779
780         btrfs_init_path(&path);
781
782         root_dir_key.objectid = btrfs_root_dirid(&root->root_item);
783         root_dir_key.offset = 0;
784         btrfs_set_key_type(&root_dir_key, BTRFS_INODE_ITEM_KEY);
785         ret = btrfs_lookup_inode(trans, root, &path, &root_dir_key, 1);
786         if (ret) {
787                 fprintf(stderr, "root dir lookup error\n");
788                 goto fail_no_dir;
789         }
790
791         leaf = path.nodes[0];
792         inode_item = btrfs_item_ptr(leaf, path.slots[0],
793                                     struct btrfs_inode_item);
794
795         root_dir_inode_size = calculate_dir_inode_size(dir_name);
796         btrfs_set_inode_size(leaf, inode_item, root_dir_inode_size);
797         btrfs_mark_buffer_dirty(leaf);
798
799         btrfs_release_path(&path);
800
801         do {
802                 parent_dir_entry = list_entry(dir_head->list.next,
803                                               struct directory_name_entry,
804                                               list);
805                 list_del(&parent_dir_entry->list);
806
807                 parent_inum = parent_dir_entry->inum;
808                 parent_dir_name = parent_dir_entry->dir_name;
809                 if (chdir(parent_dir_entry->path)) {
810                         fprintf(stderr, "chdir error for %s\n",
811                                 parent_dir_name);
812                         ret = -1;
813                         goto fail_no_files;
814                 }
815
816                 count = scandir(parent_dir_entry->path, &files,
817                                 directory_select, NULL);
818                 if (count == -1)
819                 {
820                         fprintf(stderr, "scandir for %s failed: %s\n",
821                                 parent_dir_name, strerror (errno));
822                         ret = -1;
823                         goto fail;
824                 }
825
826                 for (i = 0; i < count; i++) {
827                         cur_file = files[i];
828
829                         if (lstat(cur_file->d_name, &st) == -1) {
830                                 fprintf(stderr, "lstat failed for file %s\n",
831                                         cur_file->d_name);
832                                 ret = -1;
833                                 goto fail;
834                         }
835
836                         cur_inum = st.st_ino;
837                         ret = add_directory_items(trans, root,
838                                                   cur_inum, parent_inum,
839                                                   cur_file->d_name,
840                                                   &st, &dir_index_cnt);
841                         if (ret) {
842                                 fprintf(stderr, "add_directory_items failed\n");
843                                 goto fail;
844                         }
845
846                         ret = add_inode_items(trans, root, &st,
847                                               cur_file->d_name, cur_inum,
848                                               parent_inum, dir_index_cnt,
849                                               &cur_inode);
850                         if (ret == -EEXIST) {
851                                 BUG_ON(st.st_nlink <= 1);
852                                 continue;
853                         }
854                         if (ret) {
855                                 fprintf(stderr, "add_inode_items failed\n");
856                                 goto fail;
857                         }
858
859                         ret = add_xattr_item(trans, root,
860                                              cur_inum, cur_file->d_name);
861                         if (ret) {
862                                 fprintf(stderr, "add_xattr_item failed\n");
863                                 if(ret != -ENOTSUP)
864                                         goto fail;
865                         }
866
867                         if (S_ISDIR(st.st_mode)) {
868                                 dir_entry = malloc(sizeof(struct directory_name_entry));
869                                 dir_entry->dir_name = cur_file->d_name;
870                                 dir_entry->path = make_path(parent_dir_entry->path,
871                                                             cur_file->d_name);
872                                 dir_entry->inum = cur_inum;
873                                 list_add_tail(&dir_entry->list, &dir_head->list);
874                         } else if (S_ISREG(st.st_mode)) {
875                                 ret = add_file_items(trans, root, &cur_inode,
876                                                      cur_inum, parent_inum, &st,
877                                                      cur_file->d_name, out_fd);
878                                 if (ret) {
879                                         fprintf(stderr, "add_file_items failed\n");
880                                         goto fail;
881                                 }
882                         } else if (S_ISLNK(st.st_mode)) {
883                                 ret = add_symbolic_link(trans, root,
884                                                         cur_inum, cur_file->d_name);
885                                 if (ret) {
886                                         fprintf(stderr, "add_symbolic_link failed\n");
887                                         goto fail;
888                                 }
889                         }
890                 }
891
892                 free_namelist(files, count);
893                 free(parent_dir_entry);
894
895                 index_cnt = 2;
896
897         } while (!list_empty(&dir_head->list));
898
899 out:
900         return !!ret;
901 fail:
902         free_namelist(files, count);
903 fail_no_files:
904         free(parent_dir_entry);
905         goto out;
906 fail_no_dir:
907         free(dir_entry);
908         goto out;
909 }
910
911 static int open_target(char *output_name)
912 {
913         int output_fd;
914         output_fd = open(output_name, O_CREAT | O_RDWR | O_TRUNC,
915                          S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
916
917         return output_fd;
918 }
919
920 static int create_chunks(struct btrfs_trans_handle *trans,
921                          struct btrfs_root *root, u64 num_of_meta_chunks,
922                          u64 size_of_data)
923 {
924         u64 chunk_start;
925         u64 chunk_size;
926         u64 meta_type = BTRFS_BLOCK_GROUP_METADATA;
927         u64 data_type = BTRFS_BLOCK_GROUP_DATA;
928         u64 minimum_data_chunk_size = 8 * 1024 * 1024;
929         u64 i;
930         int ret;
931
932         for (i = 0; i < num_of_meta_chunks; i++) {
933                 ret = btrfs_alloc_chunk(trans, root->fs_info->extent_root,
934                                         &chunk_start, &chunk_size, meta_type);
935                 BUG_ON(ret);
936                 ret = btrfs_make_block_group(trans, root->fs_info->extent_root, 0,
937                                              meta_type, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
938                                              chunk_start, chunk_size);
939                 BUG_ON(ret);
940                 set_extent_dirty(&root->fs_info->free_space_cache,
941                                  chunk_start, chunk_start + chunk_size - 1, 0);
942         }
943
944         if (size_of_data < minimum_data_chunk_size)
945                 size_of_data = minimum_data_chunk_size;
946
947         ret = btrfs_alloc_data_chunk(trans, root->fs_info->extent_root,
948                                      &chunk_start, size_of_data, data_type);
949         BUG_ON(ret);
950         ret = btrfs_make_block_group(trans, root->fs_info->extent_root, 0,
951                                      data_type, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
952                                      chunk_start, size_of_data);
953         BUG_ON(ret);
954         set_extent_dirty(&root->fs_info->free_space_cache,
955                          chunk_start, chunk_start + size_of_data - 1, 0);
956         return ret;
957 }
958
959 static int make_image(char *source_dir, struct btrfs_root *root, int out_fd)
960 {
961         int ret;
962         struct btrfs_trans_handle *trans;
963
964         struct stat root_st;
965
966         struct directory_name_entry dir_head;
967
968         struct directory_name_entry *dir_entry = NULL;
969
970         ret = lstat(source_dir, &root_st);
971         if (ret) {
972                 fprintf(stderr, "unable to lstat the %s\n", source_dir);
973                 goto out;
974         }
975
976         INIT_LIST_HEAD(&dir_head.list);
977
978         trans = btrfs_start_transaction(root, 1);
979         ret = traverse_directory(trans, root, source_dir, &dir_head, out_fd);
980         if (ret) {
981                 fprintf(stderr, "unable to traverse_directory\n");
982                 goto fail;
983         }
984         btrfs_commit_transaction(trans, root);
985
986         printf("Making image is completed.\n");
987         return 0;
988 fail:
989         while (!list_empty(&dir_head.list)) {
990                 dir_entry = list_entry(dir_head.list.next,
991                                        struct directory_name_entry, list);
992                 list_del(&dir_entry->list);
993                 free(dir_entry);
994         }
995 out:
996         fprintf(stderr, "Making image is aborted.\n");
997         return -1;
998 }
999
1000 /*
1001  * This ignores symlinks with unreadable targets and subdirs that can't
1002  * be read.  It's a best-effort to give a rough estimate of the size of
1003  * a subdir.  It doesn't guarantee that prepopulating btrfs from this
1004  * tree won't still run out of space. 
1005  *
1006  * The rounding up to 4096 is questionable.  Previous code used du -B 4096.
1007  */
1008 static u64 global_total_size;
1009 static int ftw_add_entry_size(const char *fpath, const struct stat *st,
1010                               int type)
1011 {
1012         if (type == FTW_F || type == FTW_D)
1013                 global_total_size += round_up(st->st_size, 4096);
1014
1015         return 0;
1016 }
1017
1018 static u64 size_sourcedir(char *dir_name, u64 sectorsize,
1019                           u64 *num_of_meta_chunks_ret, u64 *size_of_data_ret)
1020 {
1021         u64 dir_size = 0;
1022         u64 total_size = 0;
1023         int ret;
1024         u64 default_chunk_size = 8 * 1024 * 1024;       /* 8MB */
1025         u64 allocated_meta_size = 8 * 1024 * 1024;      /* 8MB */
1026         u64 allocated_total_size = 20 * 1024 * 1024;    /* 20MB */
1027         u64 num_of_meta_chunks = 0;
1028         u64 num_of_data_chunks = 0;
1029         u64 num_of_allocated_meta_chunks =
1030                         allocated_meta_size / default_chunk_size;
1031
1032         global_total_size = 0;
1033         ret = ftw(dir_name, ftw_add_entry_size, 10);
1034         dir_size = global_total_size;
1035         if (ret < 0) {
1036                 fprintf(stderr, "ftw subdir walk of '%s' failed: %s\n",
1037                         dir_name, strerror(errno));
1038                 exit(1);
1039         }
1040
1041         num_of_data_chunks = (dir_size + default_chunk_size - 1) /
1042                 default_chunk_size;
1043
1044         num_of_meta_chunks = (dir_size / 2) / default_chunk_size;
1045         if (((dir_size / 2) % default_chunk_size) != 0)
1046                 num_of_meta_chunks++;
1047         if (num_of_meta_chunks <= num_of_allocated_meta_chunks)
1048                 num_of_meta_chunks = 0;
1049         else
1050                 num_of_meta_chunks -= num_of_allocated_meta_chunks;
1051
1052         total_size = allocated_total_size +
1053                      (num_of_data_chunks * default_chunk_size) +
1054                      (num_of_meta_chunks * default_chunk_size);
1055
1056         *num_of_meta_chunks_ret = num_of_meta_chunks;
1057         *size_of_data_ret = num_of_data_chunks * default_chunk_size;
1058         return total_size;
1059 }
1060
1061 static int zero_output_file(int out_fd, u64 size, u32 sectorsize)
1062 {
1063         int len = sectorsize;
1064         int loop_num = size / sectorsize;
1065         u64 location = 0;
1066         char *buf = malloc(len);
1067         int ret = 0, i;
1068         ssize_t written;
1069
1070         if (!buf)
1071                 return -ENOMEM;
1072         memset(buf, 0, len);
1073         for (i = 0; i < loop_num; i++) {
1074                 written = pwrite64(out_fd, buf, len, location);
1075                 if (written != len)
1076                         ret = -EIO;
1077                 location += sectorsize;
1078         }
1079         free(buf);
1080         return ret;
1081 }
1082
1083 static int check_leaf_or_node_size(u32 size, u32 sectorsize)
1084 {
1085         if (size < sectorsize) {
1086                 fprintf(stderr,
1087                         "Illegal leafsize (or nodesize) %u (smaller than %u)\n",
1088                         size, sectorsize);
1089                 return -1;
1090         } else if (size > BTRFS_MAX_METADATA_BLOCKSIZE) {
1091                 fprintf(stderr,
1092                         "Illegal leafsize (or nodesize) %u (larger than %u)\n",
1093                         size, BTRFS_MAX_METADATA_BLOCKSIZE);
1094                 return -1;
1095         } else if (size & (sectorsize - 1)) {
1096                 fprintf(stderr,
1097                         "Illegal leafsize (or nodesize) %u (not align to %u)\n",
1098                         size, sectorsize);
1099                 return -1;
1100         }
1101         return 0;
1102 }
1103
1104 static int is_ssd(const char *file)
1105 {
1106         blkid_probe probe;
1107         char wholedisk[32];
1108         char sysfs_path[PATH_MAX];
1109         dev_t devno;
1110         int fd;
1111         char rotational;
1112         int ret;
1113
1114         probe = blkid_new_probe_from_filename(file);
1115         if (!probe)
1116                 return 0;
1117
1118         /* Device number of this disk (possibly a partition) */
1119         devno = blkid_probe_get_devno(probe);
1120         if (!devno) {
1121                 blkid_free_probe(probe);
1122                 return 0;
1123         }
1124
1125         /* Get whole disk name (not full path) for this devno */
1126         ret = blkid_devno_to_wholedisk(devno,
1127                         wholedisk, sizeof(wholedisk), NULL);
1128         if (ret) {
1129                 blkid_free_probe(probe);
1130                 return 0;
1131         }
1132
1133         snprintf(sysfs_path, PATH_MAX, "/sys/block/%s/queue/rotational",
1134                  wholedisk);
1135
1136         blkid_free_probe(probe);
1137
1138         fd = open(sysfs_path, O_RDONLY);
1139         if (fd < 0) {
1140                 return 0;
1141         }
1142
1143         if (read(fd, &rotational, sizeof(char)) < sizeof(char)) {
1144                 close(fd);
1145                 return 0;
1146         }
1147         close(fd);
1148
1149         return !atoi((const char *)&rotational);
1150 }
1151
1152 #define BTRFS_FEATURE_LIST_ALL          (1ULL << 63)
1153
1154 static const struct btrfs_fs_feature {
1155         const char *name;
1156         u64 flag;
1157         const char *desc;
1158 } mkfs_features[] = {
1159         { "mixed-bg", BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS,
1160                 "mixed data and metadata block groups" },
1161         { "extref", BTRFS_FEATURE_INCOMPAT_EXTENDED_IREF,
1162                 "increased hardlink limit per file to 65536" },
1163         { "raid56", BTRFS_FEATURE_INCOMPAT_RAID56,
1164                 "raid56 extended format" },
1165         { "skinny-metadata", BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA,
1166                 "reduced-size metadata extent refs" },
1167         { "no-holes", BTRFS_FEATURE_INCOMPAT_NO_HOLES,
1168                 "no explicit hole extents for files" },
1169         /* Keep this one last */
1170         { "list-all", BTRFS_FEATURE_LIST_ALL, NULL }
1171 };
1172
1173 static void list_all_fs_features(void)
1174 {
1175         int i;
1176
1177         fprintf(stderr, "Filesystem features available at mkfs time:\n");
1178         for (i = 0; i < ARRAY_SIZE(mkfs_features) - 1; i++) {
1179                 char *is_default = "";
1180
1181                 if (mkfs_features[i].flag & DEFAULT_MKFS_FEATURES)
1182                         is_default = ", default";
1183                 fprintf(stderr, "%-20s- %s (0x%llx%s)\n",
1184                                 mkfs_features[i].name,
1185                                 mkfs_features[i].desc,
1186                                 mkfs_features[i].flag,
1187                                 is_default);
1188         }
1189 }
1190
1191 static int parse_one_fs_feature(const char *name, u64 *flags)
1192 {
1193         int i;
1194         int found = 0;
1195
1196         for (i = 0; i < ARRAY_SIZE(mkfs_features); i++) {
1197                 if (name[0] == '^' &&
1198                         !strcmp(mkfs_features[i].name, name + 1)) {
1199                         *flags &= ~ mkfs_features[i].flag;
1200                         found = 1;
1201                 } else if (!strcmp(mkfs_features[i].name, name)) {
1202                         *flags |= mkfs_features[i].flag;
1203                         found = 1;
1204                 }
1205         }
1206
1207         return !found;
1208 }
1209
1210 static void process_fs_features(u64 flags)
1211 {
1212         int i;
1213
1214         for (i = 0; i < ARRAY_SIZE(mkfs_features); i++) {
1215                 if (flags & mkfs_features[i].flag) {
1216                         printf("Turning ON incompat feature '%s': %s\n",
1217                                 mkfs_features[i].name,
1218                                 mkfs_features[i].desc);
1219                 }
1220         }
1221 }
1222
1223
1224 /*
1225  * Return NULL if all features were parsed fine, otherwise return the name of
1226  * the first unparsed.
1227  */
1228 static char* parse_fs_features(char *namelist, u64 *flags)
1229 {
1230         char *this_char;
1231         char *save_ptr = NULL; /* Satisfy static checkers */
1232
1233         for (this_char = strtok_r(namelist, ",", &save_ptr);
1234              this_char != NULL;
1235              this_char = strtok_r(NULL, ",", &save_ptr)) {
1236                 if (parse_one_fs_feature(this_char, flags))
1237                         return this_char;
1238         }
1239
1240         return NULL;
1241 }
1242
1243 int main(int ac, char **av)
1244 {
1245         char *file;
1246         struct btrfs_root *root;
1247         struct btrfs_trans_handle *trans;
1248         char *label = NULL;
1249         char *first_file;
1250         u64 block_count = 0;
1251         u64 dev_block_count = 0;
1252         u64 blocks[7];
1253         u64 alloc_start = 0;
1254         u64 metadata_profile = 0;
1255         u64 data_profile = 0;
1256         u32 leafsize = max_t(u32, sysconf(_SC_PAGESIZE), DEFAULT_MKFS_LEAF_SIZE);
1257         u32 sectorsize = 4096;
1258         u32 nodesize = leafsize;
1259         u32 stripesize = 4096;
1260         int zero_end = 1;
1261         int option_index = 0;
1262         int fd;
1263         int ret;
1264         int i;
1265         int mixed = 0;
1266         int leaf_forced = 0;
1267         int data_profile_opt = 0;
1268         int metadata_profile_opt = 0;
1269         int discard = 1;
1270         int ssd = 0;
1271         int force_overwrite = 0;
1272
1273         char *source_dir = NULL;
1274         int source_dir_set = 0;
1275         u64 num_of_meta_chunks = 0;
1276         u64 size_of_data = 0;
1277         u64 source_dir_size = 0;
1278         int dev_cnt = 0;
1279         int saved_optind;
1280         char estr[100];
1281         char *fs_uuid = NULL;
1282         u64 features = DEFAULT_MKFS_FEATURES;
1283
1284         while(1) {
1285                 int c;
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 }