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