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