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