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