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