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