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