btrfs-progs: fix error checking in load_device_info
[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
46 static u64 index_cnt = 2;
47 static int verbose = 1;
48
49 struct directory_name_entry {
50         char *dir_name;
51         char *path;
52         ino_t inum;
53         struct list_head list;
54 };
55
56 struct mkfs_allocation {
57         u64 data;
58         u64 metadata;
59         u64 mixed;
60         u64 system;
61 };
62
63 static int create_metadata_block_groups(struct btrfs_root *root, int mixed,
64                                 struct mkfs_allocation *allocation)
65 {
66         struct btrfs_trans_handle *trans;
67         u64 bytes_used;
68         u64 chunk_start = 0;
69         u64 chunk_size = 0;
70         int ret;
71
72         trans = btrfs_start_transaction(root, 1);
73         bytes_used = btrfs_super_bytes_used(root->fs_info->super_copy);
74
75         root->fs_info->system_allocs = 1;
76         ret = btrfs_make_block_group(trans, root, bytes_used,
77                                      BTRFS_BLOCK_GROUP_SYSTEM,
78                                      BTRFS_FIRST_CHUNK_TREE_OBJECTID,
79                                      0, BTRFS_MKFS_SYSTEM_GROUP_SIZE);
80         allocation->system += BTRFS_MKFS_SYSTEM_GROUP_SIZE;
81         BUG_ON(ret);
82
83         if (mixed) {
84                 ret = btrfs_alloc_chunk(trans, root->fs_info->extent_root,
85                                         &chunk_start, &chunk_size,
86                                         BTRFS_BLOCK_GROUP_METADATA |
87                                         BTRFS_BLOCK_GROUP_DATA);
88                 if (ret == -ENOSPC) {
89                         fprintf(stderr,
90                                 "no space to alloc data/metadata chunk\n");
91                         goto err;
92                 }
93                 BUG_ON(ret);
94                 ret = btrfs_make_block_group(trans, root, 0,
95                                              BTRFS_BLOCK_GROUP_METADATA |
96                                              BTRFS_BLOCK_GROUP_DATA,
97                                              BTRFS_FIRST_CHUNK_TREE_OBJECTID,
98                                              chunk_start, chunk_size);
99                 BUG_ON(ret);
100                 allocation->mixed += chunk_size;
101         } else {
102                 ret = btrfs_alloc_chunk(trans, root->fs_info->extent_root,
103                                         &chunk_start, &chunk_size,
104                                         BTRFS_BLOCK_GROUP_METADATA);
105                 if (ret == -ENOSPC) {
106                         fprintf(stderr, "no space to alloc metadata chunk\n");
107                         goto err;
108                 }
109                 BUG_ON(ret);
110                 ret = btrfs_make_block_group(trans, root, 0,
111                                              BTRFS_BLOCK_GROUP_METADATA,
112                                              BTRFS_FIRST_CHUNK_TREE_OBJECTID,
113                                              chunk_start, chunk_size);
114                 allocation->metadata += chunk_size;
115                 BUG_ON(ret);
116         }
117
118         root->fs_info->system_allocs = 0;
119         btrfs_commit_transaction(trans, root);
120
121 err:
122         return ret;
123 }
124
125 static int create_data_block_groups(struct btrfs_trans_handle *trans,
126                 struct btrfs_root *root, int mixed,
127                 struct mkfs_allocation *allocation)
128 {
129         u64 chunk_start = 0;
130         u64 chunk_size = 0;
131         int ret = 0;
132
133         if (!mixed) {
134                 ret = btrfs_alloc_chunk(trans, root->fs_info->extent_root,
135                                         &chunk_start, &chunk_size,
136                                         BTRFS_BLOCK_GROUP_DATA);
137                 if (ret == -ENOSPC) {
138                         fprintf(stderr, "no space to alloc data chunk\n");
139                         goto err;
140                 }
141                 BUG_ON(ret);
142                 ret = btrfs_make_block_group(trans, root, 0,
143                                              BTRFS_BLOCK_GROUP_DATA,
144                                              BTRFS_FIRST_CHUNK_TREE_OBJECTID,
145                                              chunk_start, chunk_size);
146                 allocation->data += chunk_size;
147                 BUG_ON(ret);
148         }
149
150 err:
151         return ret;
152 }
153
154 static int make_root_dir(struct btrfs_trans_handle *trans, struct btrfs_root *root,
155                 int mixed, struct mkfs_allocation *allocation)
156 {
157         struct btrfs_key location;
158         int ret;
159
160         ret = btrfs_make_root_dir(trans, root->fs_info->tree_root,
161                               BTRFS_ROOT_TREE_DIR_OBJECTID);
162         if (ret)
163                 goto err;
164         ret = btrfs_make_root_dir(trans, root, BTRFS_FIRST_FREE_OBJECTID);
165         if (ret)
166                 goto err;
167         memcpy(&location, &root->fs_info->fs_root->root_key, sizeof(location));
168         location.offset = (u64)-1;
169         ret = btrfs_insert_dir_item(trans, root->fs_info->tree_root,
170                         "default", 7,
171                         btrfs_super_root_dir(root->fs_info->super_copy),
172                         &location, BTRFS_FT_DIR, 0);
173         if (ret)
174                 goto err;
175
176         ret = btrfs_insert_inode_ref(trans, root->fs_info->tree_root,
177                              "default", 7, location.objectid,
178                              BTRFS_ROOT_TREE_DIR_OBJECTID, 0);
179         if (ret)
180                 goto err;
181
182 err:
183         return ret;
184 }
185
186 static void __recow_root(struct btrfs_trans_handle *trans,
187                          struct btrfs_root *root)
188 {
189         int ret;
190         struct extent_buffer *tmp;
191
192         if (trans->transid != btrfs_root_generation(&root->root_item)) {
193                 extent_buffer_get(root->node);
194                 ret = __btrfs_cow_block(trans, root, root->node,
195                                         NULL, 0, &tmp, 0, 0);
196                 BUG_ON(ret);
197                 free_extent_buffer(tmp);
198         }
199 }
200
201 static void recow_roots(struct btrfs_trans_handle *trans,
202                        struct btrfs_root *root)
203 {
204         struct btrfs_fs_info *info = root->fs_info;
205
206         __recow_root(trans, info->fs_root);
207         __recow_root(trans, info->tree_root);
208         __recow_root(trans, info->extent_root);
209         __recow_root(trans, info->chunk_root);
210         __recow_root(trans, info->dev_root);
211         __recow_root(trans, info->csum_root);
212 }
213
214 static int create_one_raid_group(struct btrfs_trans_handle *trans,
215                               struct btrfs_root *root, u64 type,
216                               struct mkfs_allocation *allocation)
217
218 {
219         u64 chunk_start;
220         u64 chunk_size;
221         int ret;
222
223         ret = btrfs_alloc_chunk(trans, root->fs_info->extent_root,
224                                 &chunk_start, &chunk_size, type);
225         if (ret == -ENOSPC) {
226                 fprintf(stderr, "not enough free space\n");
227                 exit(1);
228         }
229         BUG_ON(ret);
230         ret = btrfs_make_block_group(trans, root->fs_info->extent_root, 0,
231                                      type, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
232                                      chunk_start, chunk_size);
233         if ((type & BTRFS_BLOCK_GROUP_TYPE_MASK) == BTRFS_BLOCK_GROUP_DATA)
234                 allocation->data += chunk_size;
235         else if ((type & BTRFS_BLOCK_GROUP_TYPE_MASK) == BTRFS_BLOCK_GROUP_METADATA)
236                 allocation->metadata += chunk_size;
237         else if ((type & BTRFS_BLOCK_GROUP_TYPE_MASK) == BTRFS_BLOCK_GROUP_SYSTEM)
238                 allocation->system += chunk_size;
239         else if ((type & BTRFS_BLOCK_GROUP_TYPE_MASK) ==
240                         (BTRFS_BLOCK_GROUP_METADATA|BTRFS_BLOCK_GROUP_DATA))
241                 allocation->mixed += chunk_size;
242         else
243                 BUG_ON(1);
244
245         BUG_ON(ret);
246         return ret;
247 }
248
249 static int create_raid_groups(struct btrfs_trans_handle *trans,
250                               struct btrfs_root *root, u64 data_profile,
251                               u64 metadata_profile, int mixed,
252                               struct mkfs_allocation *allocation)
253 {
254         u64 num_devices = btrfs_super_num_devices(root->fs_info->super_copy);
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 && num_devices > 1 && 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         fprintf(stderr, "%s\n", PACKAGE_STRING);
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                 ret_read = pread64(fd, buffer, st->st_size, bytes_read);
652                 if (ret_read == -1) {
653                         fprintf(stderr, "%s read failed\n", path_name);
654                         free(buffer);
655                         goto end;
656                 }
657
658                 ret = btrfs_insert_inline_extent(trans, root, objectid, 0,
659                                                  buffer, st->st_size);
660                 free(buffer);
661                 goto end;
662         }
663
664         /* round up our st_size to the FS blocksize */
665         total_bytes = (u64)blocks * sectorsize;
666
667         /*
668          * do our IO in extent buffers so it can work
669          * against any raid type
670          */
671         eb = malloc(sizeof(*eb) + sectorsize);
672         if (!eb) {
673                 ret = -ENOMEM;
674                 goto end;
675         }
676         memset(eb, 0, sizeof(*eb) + sectorsize);
677
678 again:
679
680         /*
681          * keep our extent size at 1MB max, this makes it easier to work inside
682          * the tiny block groups created during mkfs
683          */
684         cur_bytes = min(total_bytes, 1024ULL * 1024);
685         ret = btrfs_reserve_extent(trans, root, cur_bytes, 0, 0, (u64)-1,
686                                    &key, 1);
687         if (ret)
688                 goto end;
689
690         first_block = key.objectid;
691         bytes_read = 0;
692
693         while (bytes_read < cur_bytes) {
694
695                 memset(eb->data, 0, sectorsize);
696
697                 ret_read = pread64(fd, eb->data, sectorsize, file_pos + bytes_read);
698                 if (ret_read == -1) {
699                         fprintf(stderr, "%s read failed\n", path_name);
700                         goto end;
701                 }
702
703                 eb->start = first_block + bytes_read;
704                 eb->len = sectorsize;
705
706                 /*
707                  * we're doing the csum before we record the extent, but
708                  * that's ok
709                  */
710                 ret = btrfs_csum_file_block(trans, root->fs_info->csum_root,
711                                             first_block + bytes_read + sectorsize,
712                                             first_block + bytes_read,
713                                             eb->data, sectorsize);
714                 if (ret)
715                         goto end;
716
717                 ret = write_and_map_eb(trans, root, eb);
718                 if (ret) {
719                         fprintf(stderr, "output file write failed\n");
720                         goto end;
721                 }
722
723                 bytes_read += sectorsize;
724         }
725
726         if (bytes_read) {
727                 ret = btrfs_record_file_extent(trans, root, objectid, btrfs_inode,
728                                                file_pos, first_block, cur_bytes);
729                 if (ret)
730                         goto end;
731
732         }
733
734         file_pos += cur_bytes;
735         total_bytes -= cur_bytes;
736
737         if (total_bytes)
738                 goto again;
739
740 end:
741         free(eb);
742         close(fd);
743         return ret;
744 }
745
746 static char *make_path(char *dir, char *name)
747 {
748         char *path;
749
750         path = malloc(strlen(dir) + strlen(name) + 2);
751         if (!path)
752                 return NULL;
753         strcpy(path, dir);
754         if (dir[strlen(dir) - 1] != '/')
755                 strcat(path, "/");
756         strcat(path, name);
757         return path;
758 }
759
760 static int traverse_directory(struct btrfs_trans_handle *trans,
761                               struct btrfs_root *root, char *dir_name,
762                               struct directory_name_entry *dir_head, int out_fd)
763 {
764         int ret = 0;
765
766         struct btrfs_inode_item cur_inode;
767         struct btrfs_inode_item *inode_item;
768         int count, i, dir_index_cnt;
769         struct direct **files;
770         struct stat st;
771         struct directory_name_entry *dir_entry, *parent_dir_entry;
772         struct direct *cur_file;
773         ino_t parent_inum, cur_inum;
774         ino_t highest_inum = 0;
775         char *parent_dir_name;
776         char real_path[PATH_MAX];
777         struct btrfs_path path;
778         struct extent_buffer *leaf;
779         struct btrfs_key root_dir_key;
780         u64 root_dir_inode_size = 0;
781
782         /* Add list for source directory */
783         dir_entry = malloc(sizeof(struct directory_name_entry));
784         dir_entry->dir_name = dir_name;
785         dir_entry->path = realpath(dir_name, real_path);
786         if (!dir_entry->path) {
787                 fprintf(stderr, "get directory real path error\n");
788                 ret = -1;
789                 goto fail_no_dir;
790         }
791
792         parent_inum = highest_inum + BTRFS_FIRST_FREE_OBJECTID;
793         dir_entry->inum = parent_inum;
794         list_add_tail(&dir_entry->list, &dir_head->list);
795
796         btrfs_init_path(&path);
797
798         root_dir_key.objectid = btrfs_root_dirid(&root->root_item);
799         root_dir_key.offset = 0;
800         btrfs_set_key_type(&root_dir_key, BTRFS_INODE_ITEM_KEY);
801         ret = btrfs_lookup_inode(trans, root, &path, &root_dir_key, 1);
802         if (ret) {
803                 fprintf(stderr, "root dir lookup error\n");
804                 goto fail_no_dir;
805         }
806
807         leaf = path.nodes[0];
808         inode_item = btrfs_item_ptr(leaf, path.slots[0],
809                                     struct btrfs_inode_item);
810
811         root_dir_inode_size = calculate_dir_inode_size(dir_name);
812         btrfs_set_inode_size(leaf, inode_item, root_dir_inode_size);
813         btrfs_mark_buffer_dirty(leaf);
814
815         btrfs_release_path(&path);
816
817         do {
818                 parent_dir_entry = list_entry(dir_head->list.next,
819                                               struct directory_name_entry,
820                                               list);
821                 list_del(&parent_dir_entry->list);
822
823                 parent_inum = parent_dir_entry->inum;
824                 parent_dir_name = parent_dir_entry->dir_name;
825                 if (chdir(parent_dir_entry->path)) {
826                         fprintf(stderr, "chdir error for %s\n",
827                                 parent_dir_name);
828                         ret = -1;
829                         goto fail_no_files;
830                 }
831
832                 count = scandir(parent_dir_entry->path, &files,
833                                 directory_select, NULL);
834                 if (count == -1)
835                 {
836                         fprintf(stderr, "scandir for %s failed: %s\n",
837                                 parent_dir_name, strerror (errno));
838                         ret = -1;
839                         goto fail;
840                 }
841
842                 for (i = 0; i < count; i++) {
843                         cur_file = files[i];
844
845                         if (lstat(cur_file->d_name, &st) == -1) {
846                                 fprintf(stderr, "lstat failed for file %s\n",
847                                         cur_file->d_name);
848                                 ret = -1;
849                                 goto fail;
850                         }
851
852                         cur_inum = st.st_ino;
853                         ret = add_directory_items(trans, root,
854                                                   cur_inum, parent_inum,
855                                                   cur_file->d_name,
856                                                   &st, &dir_index_cnt);
857                         if (ret) {
858                                 fprintf(stderr, "add_directory_items failed\n");
859                                 goto fail;
860                         }
861
862                         ret = add_inode_items(trans, root, &st,
863                                               cur_file->d_name, cur_inum,
864                                               parent_inum, dir_index_cnt,
865                                               &cur_inode);
866                         if (ret == -EEXIST) {
867                                 BUG_ON(st.st_nlink <= 1);
868                                 continue;
869                         }
870                         if (ret) {
871                                 fprintf(stderr, "add_inode_items failed\n");
872                                 goto fail;
873                         }
874
875                         ret = add_xattr_item(trans, root,
876                                              cur_inum, cur_file->d_name);
877                         if (ret) {
878                                 fprintf(stderr, "add_xattr_item failed\n");
879                                 if(ret != -ENOTSUP)
880                                         goto fail;
881                         }
882
883                         if (S_ISDIR(st.st_mode)) {
884                                 dir_entry = malloc(sizeof(struct directory_name_entry));
885                                 dir_entry->dir_name = cur_file->d_name;
886                                 dir_entry->path = make_path(parent_dir_entry->path,
887                                                             cur_file->d_name);
888                                 dir_entry->inum = cur_inum;
889                                 list_add_tail(&dir_entry->list, &dir_head->list);
890                         } else if (S_ISREG(st.st_mode)) {
891                                 ret = add_file_items(trans, root, &cur_inode,
892                                                      cur_inum, parent_inum, &st,
893                                                      cur_file->d_name, out_fd);
894                                 if (ret) {
895                                         fprintf(stderr, "add_file_items failed\n");
896                                         goto fail;
897                                 }
898                         } else if (S_ISLNK(st.st_mode)) {
899                                 ret = add_symbolic_link(trans, root,
900                                                         cur_inum, cur_file->d_name);
901                                 if (ret) {
902                                         fprintf(stderr, "add_symbolic_link failed\n");
903                                         goto fail;
904                                 }
905                         }
906                 }
907
908                 free_namelist(files, count);
909                 free(parent_dir_entry);
910
911                 index_cnt = 2;
912
913         } while (!list_empty(&dir_head->list));
914
915 out:
916         return !!ret;
917 fail:
918         free_namelist(files, count);
919 fail_no_files:
920         free(parent_dir_entry);
921         goto out;
922 fail_no_dir:
923         free(dir_entry);
924         goto out;
925 }
926
927 static int open_target(char *output_name)
928 {
929         int output_fd;
930         output_fd = open(output_name, O_CREAT | O_RDWR | O_TRUNC,
931                          S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
932
933         return output_fd;
934 }
935
936 static int create_chunks(struct btrfs_trans_handle *trans,
937                          struct btrfs_root *root, u64 num_of_meta_chunks,
938                          u64 size_of_data,
939                          struct mkfs_allocation *allocation)
940 {
941         u64 chunk_start;
942         u64 chunk_size;
943         u64 meta_type = BTRFS_BLOCK_GROUP_METADATA;
944         u64 data_type = BTRFS_BLOCK_GROUP_DATA;
945         u64 minimum_data_chunk_size = 8 * 1024 * 1024;
946         u64 i;
947         int ret;
948
949         for (i = 0; i < num_of_meta_chunks; i++) {
950                 ret = btrfs_alloc_chunk(trans, root->fs_info->extent_root,
951                                         &chunk_start, &chunk_size, meta_type);
952                 BUG_ON(ret);
953                 ret = btrfs_make_block_group(trans, root->fs_info->extent_root, 0,
954                                              meta_type, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
955                                              chunk_start, chunk_size);
956                 allocation->metadata += chunk_size;
957                 BUG_ON(ret);
958                 set_extent_dirty(&root->fs_info->free_space_cache,
959                                  chunk_start, chunk_start + chunk_size - 1, 0);
960         }
961
962         if (size_of_data < minimum_data_chunk_size)
963                 size_of_data = minimum_data_chunk_size;
964
965         ret = btrfs_alloc_data_chunk(trans, root->fs_info->extent_root,
966                                      &chunk_start, size_of_data, data_type);
967         BUG_ON(ret);
968         ret = btrfs_make_block_group(trans, root->fs_info->extent_root, 0,
969                                      data_type, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
970                                      chunk_start, size_of_data);
971         allocation->data += size_of_data;
972         BUG_ON(ret);
973         set_extent_dirty(&root->fs_info->free_space_cache,
974                          chunk_start, chunk_start + size_of_data - 1, 0);
975         return ret;
976 }
977
978 static int make_image(char *source_dir, struct btrfs_root *root, int out_fd)
979 {
980         int ret;
981         struct btrfs_trans_handle *trans;
982
983         struct stat root_st;
984
985         struct directory_name_entry dir_head;
986
987         struct directory_name_entry *dir_entry = NULL;
988
989         ret = lstat(source_dir, &root_st);
990         if (ret) {
991                 fprintf(stderr, "unable to lstat the %s\n", source_dir);
992                 goto out;
993         }
994
995         INIT_LIST_HEAD(&dir_head.list);
996
997         trans = btrfs_start_transaction(root, 1);
998         ret = traverse_directory(trans, root, source_dir, &dir_head, out_fd);
999         if (ret) {
1000                 fprintf(stderr, "unable to traverse_directory\n");
1001                 goto fail;
1002         }
1003         btrfs_commit_transaction(trans, root);
1004
1005         if (verbose)
1006                 printf("Making image is completed.\n");
1007         return 0;
1008 fail:
1009         while (!list_empty(&dir_head.list)) {
1010                 dir_entry = list_entry(dir_head.list.next,
1011                                        struct directory_name_entry, list);
1012                 list_del(&dir_entry->list);
1013                 free(dir_entry);
1014         }
1015 out:
1016         fprintf(stderr, "Making image is aborted.\n");
1017         return -1;
1018 }
1019
1020 /*
1021  * This ignores symlinks with unreadable targets and subdirs that can't
1022  * be read.  It's a best-effort to give a rough estimate of the size of
1023  * a subdir.  It doesn't guarantee that prepopulating btrfs from this
1024  * tree won't still run out of space. 
1025  *
1026  * The rounding up to 4096 is questionable.  Previous code used du -B 4096.
1027  */
1028 static u64 global_total_size;
1029 static int ftw_add_entry_size(const char *fpath, const struct stat *st,
1030                               int type)
1031 {
1032         if (type == FTW_F || type == FTW_D)
1033                 global_total_size += round_up(st->st_size, 4096);
1034
1035         return 0;
1036 }
1037
1038 static u64 size_sourcedir(char *dir_name, u64 sectorsize,
1039                           u64 *num_of_meta_chunks_ret, u64 *size_of_data_ret)
1040 {
1041         u64 dir_size = 0;
1042         u64 total_size = 0;
1043         int ret;
1044         u64 default_chunk_size = 8 * 1024 * 1024;       /* 8MB */
1045         u64 allocated_meta_size = 8 * 1024 * 1024;      /* 8MB */
1046         u64 allocated_total_size = 20 * 1024 * 1024;    /* 20MB */
1047         u64 num_of_meta_chunks = 0;
1048         u64 num_of_data_chunks = 0;
1049         u64 num_of_allocated_meta_chunks =
1050                         allocated_meta_size / default_chunk_size;
1051
1052         global_total_size = 0;
1053         ret = ftw(dir_name, ftw_add_entry_size, 10);
1054         dir_size = global_total_size;
1055         if (ret < 0) {
1056                 fprintf(stderr, "ftw subdir walk of '%s' failed: %s\n",
1057                         dir_name, strerror(errno));
1058                 exit(1);
1059         }
1060
1061         num_of_data_chunks = (dir_size + default_chunk_size - 1) /
1062                 default_chunk_size;
1063
1064         num_of_meta_chunks = (dir_size / 2) / default_chunk_size;
1065         if (((dir_size / 2) % default_chunk_size) != 0)
1066                 num_of_meta_chunks++;
1067         if (num_of_meta_chunks <= num_of_allocated_meta_chunks)
1068                 num_of_meta_chunks = 0;
1069         else
1070                 num_of_meta_chunks -= num_of_allocated_meta_chunks;
1071
1072         total_size = allocated_total_size +
1073                      (num_of_data_chunks * default_chunk_size) +
1074                      (num_of_meta_chunks * default_chunk_size);
1075
1076         *num_of_meta_chunks_ret = num_of_meta_chunks;
1077         *size_of_data_ret = num_of_data_chunks * default_chunk_size;
1078         return total_size;
1079 }
1080
1081 static int zero_output_file(int out_fd, u64 size, u32 sectorsize)
1082 {
1083         int len = sectorsize;
1084         int loop_num = size / sectorsize;
1085         u64 location = 0;
1086         char *buf = malloc(len);
1087         int ret = 0, i;
1088         ssize_t written;
1089
1090         if (!buf)
1091                 return -ENOMEM;
1092         memset(buf, 0, len);
1093         for (i = 0; i < loop_num; i++) {
1094                 written = pwrite64(out_fd, buf, len, location);
1095                 if (written != len)
1096                         ret = -EIO;
1097                 location += sectorsize;
1098         }
1099         free(buf);
1100         return ret;
1101 }
1102
1103 static int is_ssd(const char *file)
1104 {
1105         blkid_probe probe;
1106         char wholedisk[32];
1107         char sysfs_path[PATH_MAX];
1108         dev_t devno;
1109         int fd;
1110         char rotational;
1111         int ret;
1112
1113         probe = blkid_new_probe_from_filename(file);
1114         if (!probe)
1115                 return 0;
1116
1117         /* Device number of this disk (possibly a partition) */
1118         devno = blkid_probe_get_devno(probe);
1119         if (!devno) {
1120                 blkid_free_probe(probe);
1121                 return 0;
1122         }
1123
1124         /* Get whole disk name (not full path) for this devno */
1125         ret = blkid_devno_to_wholedisk(devno,
1126                         wholedisk, sizeof(wholedisk), NULL);
1127         if (ret) {
1128                 blkid_free_probe(probe);
1129                 return 0;
1130         }
1131
1132         snprintf(sysfs_path, PATH_MAX, "/sys/block/%s/queue/rotational",
1133                  wholedisk);
1134
1135         blkid_free_probe(probe);
1136
1137         fd = open(sysfs_path, O_RDONLY);
1138         if (fd < 0) {
1139                 return 0;
1140         }
1141
1142         if (read(fd, &rotational, sizeof(char)) < sizeof(char)) {
1143                 close(fd);
1144                 return 0;
1145         }
1146         close(fd);
1147
1148         return !atoi((const char *)&rotational);
1149 }
1150
1151 static void list_all_devices(struct btrfs_root *root)
1152 {
1153         struct btrfs_fs_devices *fs_devices;
1154         struct btrfs_device *device;
1155         int number_of_devices = 0;
1156         u64 total_block_count = 0;
1157
1158         fs_devices = root->fs_info->fs_devices;
1159
1160         list_for_each_entry(device, &fs_devices->devices, dev_list)
1161                 number_of_devices++;
1162
1163         printf("Number of devices:  %d\n", number_of_devices);
1164         /* printf("Total devices size: %10s\n", */
1165                 /* pretty_size(total_block_count)); */
1166         printf("Devices:\n");
1167         printf("   ID        SIZE  PATH\n");
1168         list_for_each_entry_reverse(device, &fs_devices->devices, dev_list) {
1169                 char dev_uuid[BTRFS_UUID_UNPARSED_SIZE];
1170
1171                 uuid_unparse(device->uuid, dev_uuid);
1172                 printf("  %3llu  %10s  %s\n",
1173                         device->devid,
1174                         pretty_size(device->total_bytes),
1175                         device->name);
1176                 total_block_count += device->total_bytes;
1177         }
1178
1179         printf("\n");
1180 }
1181
1182 static int is_temp_block_group(struct extent_buffer *node,
1183                                struct btrfs_block_group_item *bgi,
1184                                u64 data_profile, u64 meta_profile,
1185                                u64 sys_profile)
1186 {
1187         u64 flag = btrfs_disk_block_group_flags(node, bgi);
1188         u64 flag_type = flag & BTRFS_BLOCK_GROUP_TYPE_MASK;
1189         u64 flag_profile = flag & BTRFS_BLOCK_GROUP_PROFILE_MASK;
1190         u64 used = btrfs_disk_block_group_used(node, bgi);
1191
1192         /*
1193          * Chunks meets all the following conditions is a temp chunk
1194          * 1) Empty chunk
1195          * Temp chunk is always empty.
1196          *
1197          * 2) profile dismatch with mkfs profile.
1198          * Temp chunk is always in SINGLE
1199          *
1200          * 3) Size differs with mkfs_alloc
1201          * Special case for SINGLE/SINGLE btrfs.
1202          * In that case, temp data chunk and real data chunk are always empty.
1203          * So we need to use mkfs_alloc to be sure which chunk is the newly
1204          * allocated.
1205          *
1206          * Normally, new chunk size is equal to mkfs one (One chunk)
1207          * If it has multiple chunks, we just refuse to delete any one.
1208          * As they are all single, so no real problem will happen.
1209          * So only use condition 1) and 2) to judge them.
1210          */
1211         if (used != 0)
1212                 return 0;
1213         switch (flag_type) {
1214         case BTRFS_BLOCK_GROUP_DATA:
1215         case BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA:
1216                 data_profile &= BTRFS_BLOCK_GROUP_PROFILE_MASK;
1217                 if (flag_profile != data_profile)
1218                         return 1;
1219                 break;
1220         case BTRFS_BLOCK_GROUP_METADATA:
1221                 meta_profile &= BTRFS_BLOCK_GROUP_PROFILE_MASK;
1222                 if (flag_profile != meta_profile)
1223                         return 1;
1224                 break;
1225         case BTRFS_BLOCK_GROUP_SYSTEM:
1226                 sys_profile &= BTRFS_BLOCK_GROUP_PROFILE_MASK;
1227                 if (flag_profile != sys_profile)
1228                         return 1;
1229                 break;
1230         }
1231         return 0;
1232 }
1233
1234 /* Note: if current is a block group, it will skip it anyway */
1235 static int next_block_group(struct btrfs_root *root,
1236                             struct btrfs_path *path)
1237 {
1238         struct btrfs_key key;
1239         int ret = 0;
1240
1241         while (1) {
1242                 ret = btrfs_next_item(root, path);
1243                 if (ret)
1244                         goto out;
1245
1246                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1247                 if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY)
1248                         goto out;
1249         }
1250 out:
1251         return ret;
1252 }
1253
1254 /* This function will cleanup  */
1255 static int cleanup_temp_chunks(struct btrfs_fs_info *fs_info,
1256                                struct mkfs_allocation *alloc,
1257                                u64 data_profile, u64 meta_profile,
1258                                u64 sys_profile)
1259 {
1260         struct btrfs_trans_handle *trans = NULL;
1261         struct btrfs_block_group_item *bgi;
1262         struct btrfs_root *root = fs_info->extent_root;
1263         struct btrfs_key key;
1264         struct btrfs_key found_key;
1265         struct btrfs_path *path;
1266         int ret = 0;
1267
1268         path = btrfs_alloc_path();
1269         if (!path) {
1270                 ret = -ENOMEM;
1271                 goto out;
1272         }
1273
1274         trans = btrfs_start_transaction(root, 1);
1275
1276         key.objectid = 0;
1277         key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
1278         key.offset = 0;
1279
1280         while (1) {
1281                 /*
1282                  * as the rest of the loop may modify the tree, we need to
1283                  * start a new search each time.
1284                  */
1285                 ret = btrfs_search_slot(trans, root, &key, path, 0, 0);
1286                 if (ret < 0)
1287                         goto out;
1288
1289                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1290                                       path->slots[0]);
1291                 if (found_key.objectid < key.objectid)
1292                         goto out;
1293                 if (found_key.type != BTRFS_BLOCK_GROUP_ITEM_KEY) {
1294                         ret = next_block_group(root, path);
1295                         if (ret < 0)
1296                                 goto out;
1297                         if (ret > 0) {
1298                                 ret = 0;
1299                                 goto out;
1300                         }
1301                         btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1302                                               path->slots[0]);
1303                 }
1304
1305                 bgi = btrfs_item_ptr(path->nodes[0], path->slots[0],
1306                                      struct btrfs_block_group_item);
1307                 if (is_temp_block_group(path->nodes[0], bgi,
1308                                         data_profile, meta_profile,
1309                                         sys_profile)) {
1310                         ret = btrfs_free_block_group(trans, fs_info,
1311                                         found_key.objectid, found_key.offset);
1312                         if (ret < 0)
1313                                 goto out;
1314                 }
1315                 btrfs_release_path(path);
1316                 key.objectid = found_key.objectid + found_key.offset;
1317         }
1318 out:
1319         if (trans)
1320                 btrfs_commit_transaction(trans, root);
1321         btrfs_free_path(path);
1322         return ret;
1323 }
1324
1325 int main(int ac, char **av)
1326 {
1327         char *file;
1328         struct btrfs_root *root;
1329         struct btrfs_trans_handle *trans;
1330         char *label = NULL;
1331         u64 block_count = 0;
1332         u64 dev_block_count = 0;
1333         u64 blocks[7];
1334         u64 alloc_start = 0;
1335         u64 metadata_profile = 0;
1336         u64 data_profile = 0;
1337         u32 nodesize = max_t(u32, sysconf(_SC_PAGESIZE),
1338                         BTRFS_MKFS_DEFAULT_NODE_SIZE);
1339         u32 sectorsize = 4096;
1340         u32 stripesize = 4096;
1341         int zero_end = 1;
1342         int fd;
1343         int ret;
1344         int i;
1345         int mixed = 0;
1346         int nodesize_forced = 0;
1347         int data_profile_opt = 0;
1348         int metadata_profile_opt = 0;
1349         int discard = 1;
1350         int ssd = 0;
1351         int force_overwrite = 0;
1352         char *source_dir = NULL;
1353         int source_dir_set = 0;
1354         u64 num_of_meta_chunks = 0;
1355         u64 size_of_data = 0;
1356         u64 source_dir_size = 0;
1357         int dev_cnt = 0;
1358         int saved_optind;
1359         char fs_uuid[BTRFS_UUID_UNPARSED_SIZE] = { 0 };
1360         u64 features = BTRFS_MKFS_DEFAULT_FEATURES;
1361         struct mkfs_allocation allocation = { 0 };
1362         struct btrfs_mkfs_config mkfs_cfg;
1363
1364         while(1) {
1365                 int c;
1366                 static const struct option long_options[] = {
1367                         { "alloc-start", required_argument, NULL, 'A'},
1368                         { "byte-count", required_argument, NULL, 'b' },
1369                         { "force", no_argument, NULL, 'f' },
1370                         { "leafsize", required_argument, NULL, 'l' },
1371                         { "label", required_argument, NULL, 'L'},
1372                         { "metadata", required_argument, NULL, 'm' },
1373                         { "mixed", no_argument, NULL, 'M' },
1374                         { "nodesize", required_argument, NULL, 'n' },
1375                         { "sectorsize", required_argument, NULL, 's' },
1376                         { "data", required_argument, NULL, 'd' },
1377                         { "version", no_argument, NULL, 'V' },
1378                         { "rootdir", required_argument, NULL, 'r' },
1379                         { "nodiscard", no_argument, NULL, 'K' },
1380                         { "features", required_argument, NULL, 'O' },
1381                         { "uuid", required_argument, NULL, 'U' },
1382                         { "quiet", 0, NULL, 'q' },
1383                         { "help", no_argument, NULL, GETOPT_VAL_HELP },
1384                         { NULL, 0, NULL, 0}
1385                 };
1386
1387                 c = getopt_long(ac, av, "A:b:fl:n:s:m:d:L:O:r:U:VMKq",
1388                                 long_options, NULL);
1389                 if (c < 0)
1390                         break;
1391                 switch(c) {
1392                         case 'A':
1393                                 alloc_start = parse_size(optarg);
1394                                 break;
1395                         case 'f':
1396                                 force_overwrite = 1;
1397                                 break;
1398                         case 'd':
1399                                 data_profile = parse_profile(optarg);
1400                                 data_profile_opt = 1;
1401                                 break;
1402                         case 'l':
1403                                 fprintf(stderr,
1404                         "WARNING: --leafsize is deprecated, use --nodesize\n");
1405                         case 'n':
1406                                 nodesize = parse_size(optarg);
1407                                 nodesize_forced = 1;
1408                                 break;
1409                         case 'L':
1410                                 label = parse_label(optarg);
1411                                 break;
1412                         case 'm':
1413                                 metadata_profile = parse_profile(optarg);
1414                                 metadata_profile_opt = 1;
1415                                 break;
1416                         case 'M':
1417                                 mixed = 1;
1418                                 break;
1419                         case 'O': {
1420                                 char *orig = strdup(optarg);
1421                                 char *tmp = orig;
1422
1423                                 tmp = btrfs_parse_fs_features(tmp, &features);
1424                                 if (tmp) {
1425                                         fprintf(stderr,
1426                                                 "Unrecognized filesystem feature '%s'\n",
1427                                                         tmp);
1428                                         free(orig);
1429                                         exit(1);
1430                                 }
1431                                 free(orig);
1432                                 if (features & BTRFS_FEATURE_LIST_ALL) {
1433                                         btrfs_list_all_fs_features(0);
1434                                         exit(0);
1435                                 }
1436                                 break;
1437                                 }
1438                         case 's':
1439                                 sectorsize = parse_size(optarg);
1440                                 break;
1441                         case 'b':
1442                                 block_count = parse_size(optarg);
1443                                 if (block_count <= BTRFS_MKFS_SMALL_VOLUME_SIZE)
1444                                         mixed = 1;
1445                                 zero_end = 0;
1446                                 break;
1447                         case 'V':
1448                                 print_version();
1449                                 break;
1450                         case 'r':
1451                                 source_dir = optarg;
1452                                 source_dir_set = 1;
1453                                 break;
1454                         case 'U':
1455                                 strncpy(fs_uuid, optarg,
1456                                         BTRFS_UUID_UNPARSED_SIZE - 1);
1457                                 break;
1458                         case 'K':
1459                                 discard = 0;
1460                                 break;
1461                         case 'q':
1462                                 verbose = 0;
1463                                 break;
1464                         case GETOPT_VAL_HELP:
1465                         default:
1466                                 print_usage(c != GETOPT_VAL_HELP);
1467                 }
1468         }
1469
1470         sectorsize = max(sectorsize, (u32)sysconf(_SC_PAGESIZE));
1471         saved_optind = optind;
1472         dev_cnt = ac - optind;
1473         if (dev_cnt == 0)
1474                 print_usage(1);
1475
1476         if (source_dir_set && dev_cnt > 1) {
1477                 fprintf(stderr,
1478                         "The -r option is limited to a single device\n");
1479                 exit(1);
1480         }
1481
1482         if (*fs_uuid) {
1483                 uuid_t dummy_uuid;
1484
1485                 if (uuid_parse(fs_uuid, dummy_uuid) != 0) {
1486                         fprintf(stderr, "could not parse UUID: %s\n", fs_uuid);
1487                         exit(1);
1488                 }
1489                 if (!test_uuid_unique(fs_uuid)) {
1490                         fprintf(stderr, "non-unique UUID: %s\n", fs_uuid);
1491                         exit(1);
1492                 }
1493         }
1494         
1495         while (dev_cnt-- > 0) {
1496                 file = av[optind++];
1497                 if (is_block_device(file) == 1)
1498                         if (test_dev_for_mkfs(file, force_overwrite))
1499                                 exit(1);
1500         }
1501
1502         optind = saved_optind;
1503         dev_cnt = ac - optind;
1504
1505         file = av[optind++];
1506         ssd = is_ssd(file);
1507
1508         if (is_vol_small(file) || mixed) {
1509                 if (verbose)
1510                         printf("SMALL VOLUME: forcing mixed metadata/data groups\n");
1511                 mixed = 1;
1512         }
1513
1514         /*
1515         * Set default profiles according to number of added devices.
1516         * For mixed groups defaults are single/single.
1517         */
1518         if (!mixed) {
1519                 if (!metadata_profile_opt) {
1520                         if (dev_cnt == 1 && ssd && verbose)
1521                                 printf("Detected a SSD, turning off metadata "
1522                                 "duplication.  Mkfs with -m dup if you want to "
1523                                 "force metadata duplication.\n");
1524
1525                         metadata_profile = (dev_cnt > 1) ?
1526                                         BTRFS_BLOCK_GROUP_RAID1 : (ssd) ?
1527                                         0: BTRFS_BLOCK_GROUP_DUP;
1528                 }
1529                 if (!data_profile_opt) {
1530                         data_profile = (dev_cnt > 1) ?
1531                                 BTRFS_BLOCK_GROUP_RAID0 : 0; /* raid0 or single */
1532                 }
1533         } else {
1534                 u32 best_nodesize = max_t(u32, sysconf(_SC_PAGESIZE), sectorsize);
1535
1536                 if (metadata_profile_opt || data_profile_opt) {
1537                         if (metadata_profile != data_profile) {
1538                                 fprintf(stderr,
1539         "ERROR: With mixed block groups data and metadata profiles must be the same\n");
1540                                 exit(1);
1541                         }
1542                 }
1543
1544                 if (!nodesize_forced)
1545                         nodesize = best_nodesize;
1546         }
1547         if (btrfs_check_nodesize(nodesize, sectorsize,
1548                                  features))
1549                 exit(1);
1550
1551         /* Check device/block_count after the nodesize is determined */
1552         if (block_count && block_count < btrfs_min_dev_size(nodesize)) {
1553                 fprintf(stderr,
1554                         "Size '%llu' is too small to make a usable filesystem\n",
1555                         block_count);
1556                 fprintf(stderr,
1557                         "Minimum size for btrfs filesystem is %llu\n",
1558                         btrfs_min_dev_size(nodesize));
1559                 exit(1);
1560         }
1561         for (i = saved_optind; i < saved_optind + dev_cnt; i++) {
1562                 char *path;
1563
1564                 path = av[i];
1565                 ret = test_minimum_size(path, nodesize);
1566                 if (ret < 0) {
1567                         fprintf(stderr, "Failed to check size for '%s': %s\n",
1568                                 path, strerror(-ret));
1569                         exit (1);
1570                 }
1571                 if (ret > 0) {
1572                         fprintf(stderr,
1573                                 "'%s' is too small to make a usable filesystem\n",
1574                                 path);
1575                         fprintf(stderr,
1576                                 "Minimum size for each btrfs device is %llu.\n",
1577                                 btrfs_min_dev_size(nodesize));
1578                         exit(1);
1579                 }
1580         }
1581         ret = test_num_disk_vs_raid(metadata_profile, data_profile,
1582                         dev_cnt, mixed);
1583         if (ret)
1584                 exit(1);
1585
1586         /* if we are here that means all devs are good to btrfsify */
1587         if (verbose) {
1588                 printf("%s\n", PACKAGE_STRING);
1589                 printf("See %s for more information.\n\n", PACKAGE_URL);
1590         }
1591
1592         dev_cnt--;
1593
1594         if (!source_dir_set) {
1595                 /*
1596                  * open without O_EXCL so that the problem should not
1597                  * occur by the following processing.
1598                  * (btrfs_register_one_device() fails if O_EXCL is on)
1599                  */
1600                 fd = open(file, O_RDWR);
1601                 if (fd < 0) {
1602                         fprintf(stderr, "unable to open %s: %s\n", file,
1603                                 strerror(errno));
1604                         exit(1);
1605                 }
1606                 ret = btrfs_prepare_device(fd, file, zero_end, &dev_block_count,
1607                                            block_count, &mixed, discard);
1608                 if (ret) {
1609                         close(fd);
1610                         exit(1);
1611                 }
1612                 if (block_count && block_count > dev_block_count) {
1613                         fprintf(stderr, "%s is smaller than requested size\n", file);
1614                         exit(1);
1615                 }
1616         } else {
1617                 fd = open_target(file);
1618                 if (fd < 0) {
1619                         fprintf(stderr, "unable to open the %s\n", file);
1620                         exit(1);
1621                 }
1622
1623                 source_dir_size = size_sourcedir(source_dir, sectorsize,
1624                                              &num_of_meta_chunks, &size_of_data);
1625                 if(block_count < source_dir_size)
1626                         block_count = source_dir_size;
1627                 ret = zero_output_file(fd, block_count, sectorsize);
1628                 if (ret) {
1629                         fprintf(stderr, "unable to zero the output file\n");
1630                         exit(1);
1631                 }
1632                 /* our "device" is the new image file */
1633                 dev_block_count = block_count;
1634         }
1635
1636         /* To create the first block group and chunk 0 in make_btrfs */
1637         if (dev_block_count < BTRFS_MKFS_SYSTEM_GROUP_SIZE) {
1638                 fprintf(stderr, "device is too small to make filesystem\n");
1639                 exit(1);
1640         }
1641
1642         blocks[0] = BTRFS_SUPER_INFO_OFFSET;
1643         for (i = 1; i < 7; i++) {
1644                 blocks[i] = BTRFS_SUPER_INFO_OFFSET + 1024 * 1024 +
1645                         nodesize * i;
1646         }
1647
1648         if (group_profile_max_safe_loss(metadata_profile) <
1649                 group_profile_max_safe_loss(data_profile)){
1650                 fprintf(stderr,
1651                         "WARNING: metatdata has lower redundancy than data!\n\n");
1652         }
1653
1654         /*
1655          * FS features that can be set by other means than -O
1656          * just set the bit here
1657          */
1658         if (mixed)
1659                 features |= BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS;
1660
1661         if ((data_profile | metadata_profile) &
1662             (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6)) {
1663                 features |= BTRFS_FEATURE_INCOMPAT_RAID56;
1664         }
1665
1666         mkfs_cfg.label = label;
1667         mkfs_cfg.fs_uuid = fs_uuid;
1668         memcpy(mkfs_cfg.blocks, blocks, sizeof(blocks));
1669         mkfs_cfg.num_bytes = dev_block_count;
1670         mkfs_cfg.nodesize = nodesize;
1671         mkfs_cfg.sectorsize = sectorsize;
1672         mkfs_cfg.stripesize = stripesize;
1673         mkfs_cfg.features = features;
1674
1675         ret = make_btrfs(fd, &mkfs_cfg);
1676         if (ret) {
1677                 fprintf(stderr, "error during mkfs: %s\n", strerror(-ret));
1678                 exit(1);
1679         }
1680
1681         root = open_ctree(file, 0, OPEN_CTREE_WRITES);
1682         if (!root) {
1683                 fprintf(stderr, "Open ctree failed\n");
1684                 close(fd);
1685                 exit(1);
1686         }
1687         root->fs_info->alloc_start = alloc_start;
1688
1689         ret = create_metadata_block_groups(root, mixed, &allocation);
1690         if (ret) {
1691                 fprintf(stderr, "failed to create default block groups\n");
1692                 exit(1);
1693         }
1694
1695         trans = btrfs_start_transaction(root, 1);
1696         if (!trans) {
1697                 fprintf(stderr, "failed to start transaction\n");
1698                 exit(1);
1699         }
1700
1701         ret = create_data_block_groups(trans, root, mixed, &allocation);
1702         if (ret) {
1703                 fprintf(stderr, "failed to create default data block groups\n");
1704                 exit(1);
1705         }
1706
1707         ret = make_root_dir(trans, root, mixed, &allocation);
1708         if (ret) {
1709                 fprintf(stderr, "failed to setup the root directory\n");
1710                 exit(1);
1711         }
1712
1713         btrfs_commit_transaction(trans, root);
1714
1715         trans = btrfs_start_transaction(root, 1);
1716         if (!trans) {
1717                 fprintf(stderr, "failed to start transaction\n");
1718                 exit(1);
1719         }
1720
1721         if (is_block_device(file) == 1)
1722                 btrfs_register_one_device(file);
1723
1724         if (dev_cnt == 0)
1725                 goto raid_groups;
1726
1727         while (dev_cnt-- > 0) {
1728                 int old_mixed = mixed;
1729
1730                 file = av[optind++];
1731
1732                 /*
1733                  * open without O_EXCL so that the problem should not
1734                  * occur by the following processing.
1735                  * (btrfs_register_one_device() fails if O_EXCL is on)
1736                  */
1737                 fd = open(file, O_RDWR);
1738                 if (fd < 0) {
1739                         fprintf(stderr, "unable to open %s: %s\n", file,
1740                                 strerror(errno));
1741                         exit(1);
1742                 }
1743                 ret = btrfs_device_already_in_root(root, fd,
1744                                                    BTRFS_SUPER_INFO_OFFSET);
1745                 if (ret) {
1746                         fprintf(stderr, "skipping duplicate device %s in FS\n",
1747                                 file);
1748                         close(fd);
1749                         continue;
1750                 }
1751                 ret = btrfs_prepare_device(fd, file, zero_end, &dev_block_count,
1752                                            block_count, &mixed, discard);
1753                 if (ret) {
1754                         close(fd);
1755                         exit(1);
1756                 }
1757                 mixed = old_mixed;
1758
1759                 ret = btrfs_add_to_fsid(trans, root, fd, file, dev_block_count,
1760                                         sectorsize, sectorsize, sectorsize);
1761                 BUG_ON(ret);
1762                 if (verbose >= 2) {
1763                         struct btrfs_device *device;
1764
1765                         device = container_of(root->fs_info->fs_devices->devices.next,
1766                                         struct btrfs_device, dev_list);
1767                         printf("adding device %s id %llu\n", file,
1768                                 (unsigned long long)device->devid);
1769                 }
1770
1771                 if (is_block_device(file) == 1)
1772                         btrfs_register_one_device(file);
1773         }
1774
1775 raid_groups:
1776         if (!source_dir_set) {
1777                 ret = create_raid_groups(trans, root, data_profile,
1778                                  metadata_profile, mixed, &allocation);
1779                 BUG_ON(ret);
1780         }
1781
1782         ret = create_data_reloc_tree(trans, root);
1783         BUG_ON(ret);
1784
1785         btrfs_commit_transaction(trans, root);
1786
1787         if (source_dir_set) {
1788                 trans = btrfs_start_transaction(root, 1);
1789                 ret = create_chunks(trans, root,
1790                                     num_of_meta_chunks, size_of_data,
1791                                     &allocation);
1792                 BUG_ON(ret);
1793                 btrfs_commit_transaction(trans, root);
1794
1795                 ret = make_image(source_dir, root, fd);
1796                 BUG_ON(ret);
1797         }
1798         ret = cleanup_temp_chunks(root->fs_info, &allocation, data_profile,
1799                                   metadata_profile, metadata_profile);
1800         if (ret < 0) {
1801                 fprintf(stderr, "Failed to cleanup temporary chunks\n");
1802                 goto out;
1803         }
1804
1805         if (verbose) {
1806                 char features_buf[64];
1807
1808                 printf("Label:              %s\n", label);
1809                 printf("UUID:               %s\n", fs_uuid);
1810                 printf("Node size:          %u\n", nodesize);
1811                 printf("Sector size:        %u\n", sectorsize);
1812                 printf("Filesystem size:    %s\n",
1813                         pretty_size(btrfs_super_total_bytes(root->fs_info->super_copy)));
1814                 printf("Block group profiles:\n");
1815                 if (allocation.data)
1816                         printf("  Data:             %-8s %16s\n",
1817                                 btrfs_group_profile_str(data_profile),
1818                                 pretty_size(allocation.data));
1819                 if (allocation.metadata)
1820                         printf("  Metadata:         %-8s %16s\n",
1821                                 btrfs_group_profile_str(metadata_profile),
1822                                 pretty_size(allocation.metadata));
1823                 if (allocation.mixed)
1824                         printf("  Data+Metadata:    %-8s %16s\n",
1825                                 btrfs_group_profile_str(data_profile),
1826                                 pretty_size(allocation.mixed));
1827                 printf("  System:           %-8s %16s\n",
1828                         btrfs_group_profile_str(metadata_profile),
1829                         pretty_size(allocation.system));
1830                 printf("SSD detected:       %s\n", ssd ? "yes" : "no");
1831                 btrfs_parse_features_to_string(features_buf, features);
1832                 printf("Incompat features:  %s", features_buf);
1833                 printf("\n");
1834
1835                 list_all_devices(root);
1836         }
1837
1838 out:
1839         ret = close_ctree(root);
1840         BUG_ON(ret);
1841         btrfs_close_all_devices();
1842         free(label);
1843         return 0;
1844 }