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