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