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