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