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