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