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