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