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