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