Btrfs-progs: clean up reduplicate parse_qgroupid() and replace atoi with strtoull
[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 #define _XOPEN_SOURCE 500
20 #define _GNU_SOURCE
21
22 #include "kerncompat.h"
23
24 #ifndef __CHECKER__
25 #include <sys/ioctl.h>
26 #include <sys/mount.h>
27 #include "ioctl.h"
28 #endif
29
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <sys/dir.h>
35 #include <fcntl.h>
36 #include <unistd.h>
37 #include <getopt.h>
38 #include <uuid/uuid.h>
39 #include <linux/fs.h>
40 #include <ctype.h>
41 #include <attr/xattr.h>
42 #include "ctree.h"
43 #include "disk-io.h"
44 #include "volumes.h"
45 #include "transaction.h"
46 #include "utils.h"
47 #include "version.h"
48
49 static u64 index_cnt = 2;
50
51 struct directory_name_entry {
52         char *dir_name;
53         char *path;
54         ino_t inum;
55         struct list_head list;
56 };
57
58 static int make_root_dir(struct btrfs_root *root, int mixed)
59 {
60         struct btrfs_trans_handle *trans;
61         struct btrfs_key location;
62         u64 bytes_used;
63         u64 chunk_start = 0;
64         u64 chunk_size = 0;
65         int ret;
66
67         trans = btrfs_start_transaction(root, 1);
68         bytes_used = btrfs_super_bytes_used(&root->fs_info->super_copy);
69
70         root->fs_info->system_allocs = 1;
71         ret = btrfs_make_block_group(trans, root, bytes_used,
72                                      BTRFS_BLOCK_GROUP_SYSTEM,
73                                      BTRFS_FIRST_CHUNK_TREE_OBJECTID,
74                                      0, BTRFS_MKFS_SYSTEM_GROUP_SIZE);
75         BUG_ON(ret);
76
77         if (mixed) {
78                 ret = btrfs_alloc_chunk(trans, root->fs_info->extent_root,
79                                         &chunk_start, &chunk_size,
80                                         BTRFS_BLOCK_GROUP_METADATA |
81                                         BTRFS_BLOCK_GROUP_DATA);
82                 BUG_ON(ret);
83                 ret = btrfs_make_block_group(trans, root, 0,
84                                              BTRFS_BLOCK_GROUP_METADATA |
85                                              BTRFS_BLOCK_GROUP_DATA,
86                                              BTRFS_FIRST_CHUNK_TREE_OBJECTID,
87                                              chunk_start, chunk_size);
88                 BUG_ON(ret);
89                 printf("Created a data/metadata chunk of size %llu\n", chunk_size);
90         } else {
91                 ret = btrfs_alloc_chunk(trans, root->fs_info->extent_root,
92                                         &chunk_start, &chunk_size,
93                                         BTRFS_BLOCK_GROUP_METADATA);
94                 BUG_ON(ret);
95                 ret = btrfs_make_block_group(trans, root, 0,
96                                              BTRFS_BLOCK_GROUP_METADATA,
97                                              BTRFS_FIRST_CHUNK_TREE_OBJECTID,
98                                              chunk_start, chunk_size);
99                 BUG_ON(ret);
100         }
101
102         root->fs_info->system_allocs = 0;
103         btrfs_commit_transaction(trans, root);
104         trans = btrfs_start_transaction(root, 1);
105         BUG_ON(!trans);
106
107         if (!mixed) {
108                 ret = btrfs_alloc_chunk(trans, root->fs_info->extent_root,
109                                         &chunk_start, &chunk_size,
110                                         BTRFS_BLOCK_GROUP_DATA);
111                 BUG_ON(ret);
112                 ret = btrfs_make_block_group(trans, root, 0,
113                                              BTRFS_BLOCK_GROUP_DATA,
114                                              BTRFS_FIRST_CHUNK_TREE_OBJECTID,
115                                              chunk_start, chunk_size);
116                 BUG_ON(ret);
117         }
118
119         ret = btrfs_make_root_dir(trans, root->fs_info->tree_root,
120                               BTRFS_ROOT_TREE_DIR_OBJECTID);
121         if (ret)
122                 goto err;
123         ret = btrfs_make_root_dir(trans, root, BTRFS_FIRST_FREE_OBJECTID);
124         if (ret)
125                 goto err;
126         memcpy(&location, &root->fs_info->fs_root->root_key, sizeof(location));
127         location.offset = (u64)-1;
128         ret = btrfs_insert_dir_item(trans, root->fs_info->tree_root,
129                         "default", 7,
130                         btrfs_super_root_dir(&root->fs_info->super_copy),
131                         &location, BTRFS_FT_DIR, 0);
132         if (ret)
133                 goto err;
134
135         ret = btrfs_insert_inode_ref(trans, root->fs_info->tree_root,
136                              "default", 7, location.objectid,
137                              BTRFS_ROOT_TREE_DIR_OBJECTID, 0);
138         if (ret)
139                 goto err;
140
141         btrfs_commit_transaction(trans, root);
142 err:
143         return ret;
144 }
145
146 static int recow_roots(struct btrfs_trans_handle *trans,
147                        struct btrfs_root *root)
148 {
149         int ret;
150         struct extent_buffer *tmp;
151         struct btrfs_fs_info *info = root->fs_info;
152
153         ret = __btrfs_cow_block(trans, info->fs_root, info->fs_root->node,
154                                 NULL, 0, &tmp, 0, 0);
155         BUG_ON(ret);
156         free_extent_buffer(tmp);
157
158         ret = __btrfs_cow_block(trans, info->tree_root, info->tree_root->node,
159                                 NULL, 0, &tmp, 0, 0);
160         BUG_ON(ret);
161         free_extent_buffer(tmp);
162
163         ret = __btrfs_cow_block(trans, info->extent_root,
164                                 info->extent_root->node, NULL, 0, &tmp, 0, 0);
165         BUG_ON(ret);
166         free_extent_buffer(tmp);
167
168         ret = __btrfs_cow_block(trans, info->chunk_root, info->chunk_root->node,
169                                 NULL, 0, &tmp, 0, 0);
170         BUG_ON(ret);
171         free_extent_buffer(tmp);
172
173
174         ret = __btrfs_cow_block(trans, info->dev_root, info->dev_root->node,
175                                 NULL, 0, &tmp, 0, 0);
176         BUG_ON(ret);
177         free_extent_buffer(tmp);
178
179         ret = __btrfs_cow_block(trans, info->csum_root, info->csum_root->node,
180                                 NULL, 0, &tmp, 0, 0);
181         BUG_ON(ret);
182         free_extent_buffer(tmp);
183
184         return 0;
185 }
186
187 static int create_one_raid_group(struct btrfs_trans_handle *trans,
188                               struct btrfs_root *root, u64 type)
189 {
190         u64 chunk_start;
191         u64 chunk_size;
192         int ret;
193
194         ret = btrfs_alloc_chunk(trans, root->fs_info->extent_root,
195                                 &chunk_start, &chunk_size, type);
196         BUG_ON(ret);
197         ret = btrfs_make_block_group(trans, root->fs_info->extent_root, 0,
198                                      type, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
199                                      chunk_start, chunk_size);
200         BUG_ON(ret);
201         return ret;
202 }
203
204 static int create_raid_groups(struct btrfs_trans_handle *trans,
205                               struct btrfs_root *root, u64 data_profile,
206                               int data_profile_opt, u64 metadata_profile,
207                               int metadata_profile_opt, int mixed)
208 {
209         u64 num_devices = btrfs_super_num_devices(&root->fs_info->super_copy);
210         u64 allowed;
211         int ret;
212
213         /*
214          * Set default profiles according to number of added devices.
215          * For mixed groups defaults are single/single.
216          */
217         if (!metadata_profile_opt && !mixed) {
218                 metadata_profile = (num_devices > 1) ?
219                         BTRFS_BLOCK_GROUP_RAID1 : BTRFS_BLOCK_GROUP_DUP;
220         }
221         if (!data_profile_opt && !mixed) {
222                 data_profile = (num_devices > 1) ?
223                         BTRFS_BLOCK_GROUP_RAID0 : 0; /* raid0 or single */
224         }
225
226         if (num_devices == 1)
227                 allowed = BTRFS_BLOCK_GROUP_DUP;
228         else if (num_devices >= 4) {
229                 allowed = BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
230                         BTRFS_BLOCK_GROUP_RAID10;
231         } else
232                 allowed = BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1;
233
234         if (metadata_profile & ~allowed) {
235                 fprintf(stderr, "unable to create FS with metadata "
236                         "profile %llu (have %llu devices)\n", metadata_profile,
237                         num_devices);
238                 exit(1);
239         }
240         if (data_profile & ~allowed) {
241                 fprintf(stderr, "unable to create FS with data "
242                         "profile %llu (have %llu devices)\n", data_profile,
243                         num_devices);
244                 exit(1);
245         }
246
247         /* allow dup'ed data chunks only in mixed mode */
248         if (!mixed && (data_profile & BTRFS_BLOCK_GROUP_DUP)) {
249                 fprintf(stderr, "dup for data is allowed only in mixed mode\n");
250                 exit(1);
251         }
252
253         if (allowed & metadata_profile) {
254                 u64 meta_flags = BTRFS_BLOCK_GROUP_METADATA;
255
256                 ret = create_one_raid_group(trans, root,
257                                             BTRFS_BLOCK_GROUP_SYSTEM |
258                                             (allowed & metadata_profile));
259                 BUG_ON(ret);
260
261                 if (mixed)
262                         meta_flags |= BTRFS_BLOCK_GROUP_DATA;
263
264                 ret = create_one_raid_group(trans, root, meta_flags |
265                                             (allowed & metadata_profile));
266                 BUG_ON(ret);
267
268                 ret = recow_roots(trans, root);
269                 BUG_ON(ret);
270         }
271         if (!mixed && num_devices > 1 && (allowed & data_profile)) {
272                 ret = create_one_raid_group(trans, root,
273                                             BTRFS_BLOCK_GROUP_DATA |
274                                             (allowed & data_profile));
275                 BUG_ON(ret);
276         }
277         return 0;
278 }
279
280 static int create_data_reloc_tree(struct btrfs_trans_handle *trans,
281                                   struct btrfs_root *root)
282 {
283         struct btrfs_key location;
284         struct btrfs_root_item root_item;
285         struct extent_buffer *tmp;
286         u64 objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
287         int ret;
288
289         ret = btrfs_copy_root(trans, root, root->node, &tmp, objectid);
290         BUG_ON(ret);
291
292         memcpy(&root_item, &root->root_item, sizeof(root_item));
293         btrfs_set_root_bytenr(&root_item, tmp->start);
294         btrfs_set_root_level(&root_item, btrfs_header_level(tmp));
295         btrfs_set_root_generation(&root_item, trans->transid);
296         free_extent_buffer(tmp);
297
298         location.objectid = objectid;
299         location.type = BTRFS_ROOT_ITEM_KEY;
300         location.offset = 0;
301         ret = btrfs_insert_root(trans, root->fs_info->tree_root,
302                                 &location, &root_item);
303         BUG_ON(ret);
304         return 0;
305 }
306
307 static void print_usage(void)
308 {
309         fprintf(stderr, "usage: mkfs.btrfs [options] dev [ dev ... ]\n");
310         fprintf(stderr, "options:\n");
311         fprintf(stderr, "\t -A --alloc-start the offset to start the FS\n");
312         fprintf(stderr, "\t -b --byte-count total number of bytes in the FS\n");
313         fprintf(stderr, "\t -d --data data profile, raid0, raid1, raid10, dup or single\n");
314         fprintf(stderr, "\t -l --leafsize size of btree leaves\n");
315         fprintf(stderr, "\t -L --label set a label\n");
316         fprintf(stderr, "\t -m --metadata metadata profile, values like data profile\n");
317         fprintf(stderr, "\t -M --mixed mix metadata and data together\n");
318         fprintf(stderr, "\t -n --nodesize size of btree nodes\n");
319         fprintf(stderr, "\t -s --sectorsize min block allocation\n");
320         fprintf(stderr, "\t -r --rootdir the source directory\n");
321         fprintf(stderr, "\t -K --nodiscard do not perform whole device TRIM\n");
322         fprintf(stderr, "\t -V --version print the mkfs.btrfs version and exit\n");
323         fprintf(stderr, "%s\n", BTRFS_BUILD_VERSION);
324         exit(1);
325 }
326
327 static void print_version(void)
328 {
329         fprintf(stderr, "mkfs.btrfs, part of %s\n", BTRFS_BUILD_VERSION);
330         exit(0);
331 }
332
333 static u64 parse_profile(char *s)
334 {
335         if (strcmp(s, "raid0") == 0) {
336                 return BTRFS_BLOCK_GROUP_RAID0;
337         } else if (strcmp(s, "raid1") == 0) {
338                 return BTRFS_BLOCK_GROUP_RAID1;
339         } else if (strcmp(s, "raid10") == 0) {
340                 return BTRFS_BLOCK_GROUP_RAID10;
341         } else if (strcmp(s, "dup") == 0) {
342                 return BTRFS_BLOCK_GROUP_DUP;
343         } else if (strcmp(s, "single") == 0) {
344                 return 0;
345         } else {
346                 fprintf(stderr, "Unknown profile %s\n", s);
347                 print_usage();
348         }
349         /* not reached */
350         return 0;
351 }
352
353 static char *parse_label(char *input)
354 {
355         int i;
356         int len = strlen(input);
357
358         if (len >= BTRFS_LABEL_SIZE) {
359                 fprintf(stderr, "Label %s is too long (max %d)\n", input,
360                         BTRFS_LABEL_SIZE - 1);
361                 exit(1);
362         }
363         for (i = 0; i < len; i++) {
364                 if (input[i] == '/' || input[i] == '\\') {
365                         fprintf(stderr, "invalid label %s\n", input);
366                         exit(1);
367                 }
368         }
369         return strdup(input);
370 }
371
372 static struct option long_options[] = {
373         { "alloc-start", 1, NULL, 'A'},
374         { "byte-count", 1, NULL, 'b' },
375         { "leafsize", 1, NULL, 'l' },
376         { "label", 1, NULL, 'L'},
377         { "metadata", 1, NULL, 'm' },
378         { "mixed", 0, NULL, 'M' },
379         { "nodesize", 1, NULL, 'n' },
380         { "sectorsize", 1, NULL, 's' },
381         { "data", 1, NULL, 'd' },
382         { "version", 0, NULL, 'V' },
383         { "rootdir", 1, NULL, 'r' },
384         { "nodiscard", 0, NULL, 'K' },
385         { 0, 0, 0, 0}
386 };
387
388 static int add_directory_items(struct btrfs_trans_handle *trans,
389                                struct btrfs_root *root, u64 objectid,
390                                ino_t parent_inum, const char *name,
391                                struct stat *st, int *dir_index_cnt)
392 {
393         int ret;
394         int name_len;
395         struct btrfs_key location;
396         u8 filetype = 0;
397
398         name_len = strlen(name);
399
400         location.objectid = objectid;
401         location.offset = 0;
402         btrfs_set_key_type(&location, BTRFS_INODE_ITEM_KEY);
403
404         if (S_ISDIR(st->st_mode))
405                 filetype = BTRFS_FT_DIR;
406         if (S_ISREG(st->st_mode))
407                 filetype = BTRFS_FT_REG_FILE;
408         if (S_ISLNK(st->st_mode))
409                 filetype = BTRFS_FT_SYMLINK;
410
411         ret = btrfs_insert_dir_item(trans, root, name, name_len,
412                                     parent_inum, &location,
413                                     filetype, index_cnt);
414
415         *dir_index_cnt = index_cnt;
416         index_cnt++;
417
418         return ret;
419 }
420
421 static int fill_inode_item(struct btrfs_trans_handle *trans,
422                            struct btrfs_root *root,
423                            struct btrfs_inode_item *dst, struct stat *src)
424 {
425         u64 blocks = 0;
426         u64 sectorsize = root->sectorsize;
427
428         /*
429          * btrfs_inode_item has some reserved fields
430          * and represents on-disk inode entry, so
431          * zero everything to prevent information leak
432          */
433         memset(dst, 0, sizeof (*dst));
434
435         btrfs_set_stack_inode_generation(dst, trans->transid);
436         btrfs_set_stack_inode_size(dst, src->st_size);
437         btrfs_set_stack_inode_nbytes(dst, 0);
438         btrfs_set_stack_inode_block_group(dst, 0);
439         btrfs_set_stack_inode_nlink(dst, src->st_nlink);
440         btrfs_set_stack_inode_uid(dst, src->st_uid);
441         btrfs_set_stack_inode_gid(dst, src->st_gid);
442         btrfs_set_stack_inode_mode(dst, src->st_mode);
443         btrfs_set_stack_inode_rdev(dst, 0);
444         btrfs_set_stack_inode_flags(dst, 0);
445         btrfs_set_stack_timespec_sec(&dst->atime, src->st_atime);
446         btrfs_set_stack_timespec_nsec(&dst->atime, 0);
447         btrfs_set_stack_timespec_sec(&dst->ctime, src->st_ctime);
448         btrfs_set_stack_timespec_nsec(&dst->ctime, 0);
449         btrfs_set_stack_timespec_sec(&dst->mtime, src->st_mtime);
450         btrfs_set_stack_timespec_nsec(&dst->mtime, 0);
451         btrfs_set_stack_timespec_sec(&dst->otime, 0);
452         btrfs_set_stack_timespec_nsec(&dst->otime, 0);
453
454         if (S_ISDIR(src->st_mode)) {
455                 btrfs_set_stack_inode_size(dst, 0);
456                 btrfs_set_stack_inode_nlink(dst, 1);
457         }
458         if (S_ISREG(src->st_mode)) {
459                 btrfs_set_stack_inode_size(dst, (u64)src->st_size);
460                 if (src->st_size <= BTRFS_MAX_INLINE_DATA_SIZE(root))
461                         btrfs_set_stack_inode_nbytes(dst, src->st_size);
462                 else {
463                         blocks = src->st_size / sectorsize;
464                         if (src->st_size % sectorsize)
465                                 blocks += 1;
466                         blocks *= sectorsize;
467                         btrfs_set_stack_inode_nbytes(dst, blocks);
468                 }
469         }
470         if (S_ISLNK(src->st_mode))
471                 btrfs_set_stack_inode_nbytes(dst, src->st_size + 1);
472
473         return 0;
474 }
475
476 static int directory_select(const struct direct *entry)
477 {
478         if ((strncmp(entry->d_name, ".", entry->d_reclen) == 0) ||
479                 (strncmp(entry->d_name, "..", entry->d_reclen) == 0))
480                 return 0;
481         else
482                 return 1;
483 }
484
485 static void free_namelist(struct direct **files, int count)
486 {
487         int i;
488
489         if (count < 0)
490                 return;
491
492         for (i = 0; i < count; ++i)
493                 free(files[i]);
494         free(files);
495 }
496
497 static u64 calculate_dir_inode_size(char *dirname)
498 {
499         int count, i;
500         struct direct **files, *cur_file;
501         u64 dir_inode_size = 0;
502
503         count = scandir(dirname, &files, directory_select, NULL);
504
505         for (i = 0; i < count; i++) {
506                 cur_file = files[i];
507                 dir_inode_size += strlen(cur_file->d_name);
508         }
509
510         free_namelist(files, count);
511
512         dir_inode_size *= 2;
513         return dir_inode_size;
514 }
515
516 static int add_inode_items(struct btrfs_trans_handle *trans,
517                            struct btrfs_root *root,
518                            struct stat *st, char *name,
519                            u64 self_objectid, ino_t parent_inum,
520                            int dir_index_cnt, struct btrfs_inode_item *inode_ret)
521 {
522         int ret;
523         struct btrfs_key inode_key;
524         struct btrfs_inode_item btrfs_inode;
525         u64 objectid;
526         u64 inode_size = 0;
527         int name_len;
528
529         name_len = strlen(name);
530         fill_inode_item(trans, root, &btrfs_inode, st);
531         objectid = self_objectid;
532
533         if (S_ISDIR(st->st_mode)) {
534                 inode_size = calculate_dir_inode_size(name);
535                 btrfs_set_stack_inode_size(&btrfs_inode, inode_size);
536         }
537
538         inode_key.objectid = objectid;
539         inode_key.offset = 0;
540         btrfs_set_key_type(&inode_key, BTRFS_INODE_ITEM_KEY);
541
542         ret = btrfs_insert_inode(trans, root, objectid, &btrfs_inode);
543         if (ret)
544                 goto fail;
545
546         ret = btrfs_insert_inode_ref(trans, root, name, name_len,
547                                      objectid, parent_inum, dir_index_cnt);
548         if (ret)
549                 goto fail;
550
551         *inode_ret = btrfs_inode;
552 fail:
553         return ret;
554 }
555
556 static int add_xattr_item(struct btrfs_trans_handle *trans,
557                           struct btrfs_root *root, u64 objectid,
558                           const char *file_name)
559 {
560         int ret;
561         int cur_name_len;
562         char xattr_list[XATTR_LIST_MAX];
563         char *cur_name;
564         char cur_value[XATTR_SIZE_MAX];
565         char delimiter = '\0';
566         char *next_location = xattr_list;
567
568         ret = llistxattr(file_name, xattr_list, XATTR_LIST_MAX);
569         if (ret < 0) {
570                 if(errno == ENOTSUP)
571                         return 0;
572                 fprintf(stderr, "get a list of xattr failed for %s\n",
573                         file_name);
574                 return ret;
575         }
576         if (ret == 0)
577                 return ret;
578
579         cur_name = strtok(xattr_list, &delimiter);
580         while (cur_name != NULL) {
581                 cur_name_len = strlen(cur_name);
582                 next_location += cur_name_len + 1;
583
584                 ret = getxattr(file_name, cur_name, cur_value, XATTR_SIZE_MAX);
585                 if (ret < 0) {
586                         if(errno == ENOTSUP)
587                                 return 0;
588                         fprintf(stderr, "get a xattr value failed for %s attr %s\n",
589                                 file_name, cur_name);
590                         return ret;
591                 }
592
593                 ret = btrfs_insert_xattr_item(trans, root, cur_name,
594                                               cur_name_len, cur_value,
595                                               ret, objectid);
596                 if (ret) {
597                         fprintf(stderr, "insert a xattr item failed for %s\n",
598                                 file_name);
599                 }
600
601                 cur_name = strtok(next_location, &delimiter);
602         }
603
604         return ret;
605 }
606 static int custom_alloc_extent(struct btrfs_root *root, u64 num_bytes,
607                                u64 hint_byte, struct btrfs_key *ins)
608 {
609         u64 start;
610         u64 end;
611         u64 last = hint_byte;
612         int ret;
613         int wrapped = 0;
614         struct btrfs_block_group_cache *cache;
615
616         while (1) {
617                 ret = find_first_extent_bit(&root->fs_info->free_space_cache,
618                                             last, &start, &end, EXTENT_DIRTY);
619                 if (ret) {
620                         if (wrapped++ == 0) {
621                                 last = 0;
622                                 continue;
623                         } else {
624                                 goto fail;
625                         }
626                 }
627
628                 start = max(last, start);
629                 last = end + 1;
630                 if (last - start < num_bytes)
631                         continue;
632
633                 last = start + num_bytes;
634                 if (test_range_bit(&root->fs_info->pinned_extents,
635                                    start, last - 1, EXTENT_DIRTY, 0))
636                         continue;
637
638                 cache = btrfs_lookup_block_group(root->fs_info, start);
639                 BUG_ON(!cache);
640                 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM ||
641                     last > cache->key.objectid + cache->key.offset) {
642                         last = cache->key.objectid + cache->key.offset;
643                         continue;
644                 }
645
646                 if (cache->flags & (BTRFS_BLOCK_GROUP_SYSTEM |
647                             BTRFS_BLOCK_GROUP_METADATA)) {
648                         last = cache->key.objectid + cache->key.offset;
649                         continue;
650                 }
651
652                 clear_extent_dirty(&root->fs_info->free_space_cache,
653                                    start, start + num_bytes - 1, 0);
654
655                 ins->objectid = start;
656                 ins->offset = num_bytes;
657                 ins->type = BTRFS_EXTENT_ITEM_KEY;
658                 return 0;
659         }
660 fail:
661         fprintf(stderr, "not enough free space\n");
662         return -ENOSPC;
663 }
664
665 static int record_file_extent(struct btrfs_trans_handle *trans,
666                               struct btrfs_root *root, u64 objectid,
667                               struct btrfs_inode_item *inode,
668                               u64 file_pos, u64 disk_bytenr,
669                               u64 num_bytes)
670 {
671         int ret;
672         struct btrfs_fs_info *info = root->fs_info;
673         struct btrfs_root *extent_root = info->extent_root;
674         struct extent_buffer *leaf;
675         struct btrfs_file_extent_item *fi;
676         struct btrfs_key ins_key;
677         struct btrfs_path path;
678         struct btrfs_extent_item *ei;
679
680         btrfs_init_path(&path);
681
682         ins_key.objectid = objectid;
683         ins_key.offset = 0;
684         btrfs_set_key_type(&ins_key, BTRFS_EXTENT_DATA_KEY);
685         ret = btrfs_insert_empty_item(trans, root, &path, &ins_key,
686                                       sizeof(*fi));
687         if (ret)
688                 goto fail;
689         leaf = path.nodes[0];
690         fi = btrfs_item_ptr(leaf, path.slots[0],
691                             struct btrfs_file_extent_item);
692         btrfs_set_file_extent_generation(leaf, fi, trans->transid);
693         btrfs_set_file_extent_type(leaf, fi, BTRFS_FILE_EXTENT_REG);
694         btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
695         btrfs_set_file_extent_disk_num_bytes(leaf, fi, num_bytes);
696         btrfs_set_file_extent_offset(leaf, fi, 0);
697         btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
698         btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
699         btrfs_set_file_extent_compression(leaf, fi, 0);
700         btrfs_set_file_extent_encryption(leaf, fi, 0);
701         btrfs_set_file_extent_other_encoding(leaf, fi, 0);
702         btrfs_mark_buffer_dirty(leaf);
703
704         btrfs_release_path(root, &path);
705
706         ins_key.objectid = disk_bytenr;
707         ins_key.offset = num_bytes;
708         ins_key.type = BTRFS_EXTENT_ITEM_KEY;
709
710         ret = btrfs_insert_empty_item(trans, extent_root, &path,
711                                 &ins_key, sizeof(*ei));
712         if (ret == 0) {
713                 leaf = path.nodes[0];
714                 ei = btrfs_item_ptr(leaf, path.slots[0],
715                                     struct btrfs_extent_item);
716
717                 btrfs_set_extent_refs(leaf, ei, 0);
718                 btrfs_set_extent_generation(leaf, ei, trans->transid);
719                 btrfs_set_extent_flags(leaf, ei, BTRFS_EXTENT_FLAG_DATA);
720
721                 btrfs_mark_buffer_dirty(leaf);
722                 ret = btrfs_update_block_group(trans, root, disk_bytenr,
723                                                num_bytes, 1, 0);
724                 if (ret)
725                         goto fail;
726         } else if (ret != -EEXIST) {
727                 goto fail;
728         }
729
730         ret = btrfs_inc_extent_ref(trans, root, disk_bytenr, num_bytes, 0,
731                                    root->root_key.objectid,
732                                    objectid, 0);
733 fail:
734         btrfs_release_path(root, &path);
735         return ret;
736 }
737
738 static int add_symbolic_link(struct btrfs_trans_handle *trans,
739                              struct btrfs_root *root,
740                              u64 objectid, const char *path_name)
741 {
742         int ret;
743         u64 sectorsize = root->sectorsize;
744         char *buf = malloc(sectorsize);
745
746         ret = readlink(path_name, buf, sectorsize);
747         if (ret <= 0) {
748                 fprintf(stderr, "readlink failed for %s\n", path_name);
749                 goto fail;
750         }
751         if (ret >= sectorsize) {
752                 fprintf(stderr, "symlink too long for %s", path_name);
753                 ret = -1;
754                 goto fail;
755         }
756
757         buf[ret] = '\0'; /* readlink does not do it for us */
758         ret = btrfs_insert_inline_extent(trans, root, objectid, 0,
759                                          buf, ret + 1);
760 fail:
761         free(buf);
762         return ret;
763 }
764
765 static int add_file_items(struct btrfs_trans_handle *trans,
766                           struct btrfs_root *root,
767                           struct btrfs_inode_item *btrfs_inode, u64 objectid,
768                           ino_t parent_inum, struct stat *st,
769                           const char *path_name, int out_fd)
770 {
771         int ret = -1;
772         ssize_t ret_read;
773         u64 bytes_read = 0;
774         char *buffer = NULL;
775         struct btrfs_key key;
776         int blocks;
777         u32 sectorsize = root->sectorsize;
778         u64 first_block = 0;
779         u64 num_blocks = 0;
780         int fd;
781
782         fd = open(path_name, O_RDONLY);
783         if (fd == -1) {
784                 fprintf(stderr, "%s open failed\n", path_name);
785                 goto end;
786         }
787
788         blocks = st->st_size / sectorsize;
789         if (st->st_size % sectorsize)
790                 blocks += 1;
791
792         if (st->st_size <= BTRFS_MAX_INLINE_DATA_SIZE(root)) {
793                 buffer = malloc(st->st_size);
794                 ret_read = pread64(fd, buffer, st->st_size, bytes_read);
795                 if (ret_read == -1) {
796                         fprintf(stderr, "%s read failed\n", path_name);
797                         goto end;
798                 }
799
800                 ret = btrfs_insert_inline_extent(trans, root, objectid, 0,
801                                                  buffer, st->st_size);
802                 goto end;
803         }
804
805         ret = custom_alloc_extent(root, blocks * sectorsize, 0, &key);
806         if (ret)
807                 goto end;
808
809         first_block = key.objectid;
810         bytes_read = 0;
811         buffer = malloc(sectorsize);
812
813         do {
814                 memset(buffer, 0, sectorsize);
815                 ret_read = pread64(fd, buffer, sectorsize, bytes_read);
816                 if (ret_read == -1) {
817                         fprintf(stderr, "%s read failed\n", path_name);
818                         goto end;
819                 }
820
821                 ret = pwrite64(out_fd, buffer, sectorsize,
822                                first_block + bytes_read);
823                 if (ret != sectorsize) {
824                         fprintf(stderr, "output file write failed\n");
825                         goto end;
826                 }
827
828                 /* checksum for file data */
829                 ret = btrfs_csum_file_block(trans, root->fs_info->csum_root,
830                                 first_block + (blocks * sectorsize),
831                                 first_block + bytes_read,
832                                 buffer, sectorsize);
833                 if (ret) {
834                         fprintf(stderr, "%s checksum failed\n", path_name);
835                         goto end;
836                 }
837
838                 bytes_read += ret_read;
839                 num_blocks++;
840         } while (ret_read == sectorsize);
841
842         if (num_blocks > 0) {
843                 ret = record_file_extent(trans, root, objectid, btrfs_inode,
844                                          first_block, first_block,
845                                          blocks * sectorsize);
846                 if (ret)
847                         goto end;
848         }
849
850 end:
851         if (buffer)
852                 free(buffer);
853         close(fd);
854         return ret;
855 }
856
857 static char *make_path(char *dir, char *name)
858 {
859         char *path;
860
861         path = malloc(strlen(dir) + strlen(name) + 2);
862         if (!path)
863                 return NULL;
864         strcpy(path, dir);
865         if (dir[strlen(dir) - 1] != '/')
866                 strcat(path, "/");
867         strcat(path, name);
868         return path;
869 }
870
871 static int traverse_directory(struct btrfs_trans_handle *trans,
872                               struct btrfs_root *root, char *dir_name,
873                               struct directory_name_entry *dir_head, int out_fd)
874 {
875         int ret = 0;
876
877         struct btrfs_inode_item cur_inode;
878         struct btrfs_inode_item *inode_item;
879         int count, i, dir_index_cnt;
880         struct direct **files;
881         struct stat st;
882         struct directory_name_entry *dir_entry, *parent_dir_entry;
883         struct direct *cur_file;
884         ino_t parent_inum, cur_inum;
885         ino_t highest_inum = 0;
886         char *parent_dir_name;
887         struct btrfs_path path;
888         struct extent_buffer *leaf;
889         struct btrfs_key root_dir_key;
890         u64 root_dir_inode_size = 0;
891
892         /* Add list for source directory */
893         dir_entry = malloc(sizeof(struct directory_name_entry));
894         dir_entry->dir_name = dir_name;
895         dir_entry->path = strdup(dir_name);
896
897         parent_inum = highest_inum + BTRFS_FIRST_FREE_OBJECTID;
898         dir_entry->inum = parent_inum;
899         list_add_tail(&dir_entry->list, &dir_head->list);
900
901         btrfs_init_path(&path);
902
903         root_dir_key.objectid = btrfs_root_dirid(&root->root_item);
904         root_dir_key.offset = 0;
905         btrfs_set_key_type(&root_dir_key, BTRFS_INODE_ITEM_KEY);
906         ret = btrfs_lookup_inode(trans, root, &path, &root_dir_key, 1);
907         if (ret) {
908                 fprintf(stderr, "root dir lookup error\n");
909                 return -1;
910         }
911
912         leaf = path.nodes[0];
913         inode_item = btrfs_item_ptr(leaf, path.slots[0],
914                                     struct btrfs_inode_item);
915
916         root_dir_inode_size = calculate_dir_inode_size(dir_name);
917         btrfs_set_inode_size(leaf, inode_item, root_dir_inode_size);
918         btrfs_mark_buffer_dirty(leaf);
919
920         btrfs_release_path(root, &path);
921
922         do {
923                 parent_dir_entry = list_entry(dir_head->list.next,
924                                               struct directory_name_entry,
925                                               list);
926                 list_del(&parent_dir_entry->list);
927
928                 parent_inum = parent_dir_entry->inum;
929                 parent_dir_name = parent_dir_entry->dir_name;
930                 if (chdir(parent_dir_entry->path)) {
931                         fprintf(stderr, "chdir error for %s\n",
932                                 parent_dir_name);
933                         goto fail_no_files;
934                 }
935
936                 count = scandir(parent_dir_entry->path, &files,
937                                 directory_select, NULL);
938                 if (count == -1)
939                 {
940                         fprintf(stderr, "scandir for %s failed: %s\n",
941                                 parent_dir_name, strerror (errno));
942                         goto fail;
943                 }
944
945                 for (i = 0; i < count; i++) {
946                         cur_file = files[i];
947
948                         if (lstat(cur_file->d_name, &st) == -1) {
949                                 fprintf(stderr, "lstat failed for file %s\n",
950                                         cur_file->d_name);
951                                 goto fail;
952                         }
953
954                         cur_inum = ++highest_inum + BTRFS_FIRST_FREE_OBJECTID;
955                         ret = add_directory_items(trans, root,
956                                                   cur_inum, parent_inum,
957                                                   cur_file->d_name,
958                                                   &st, &dir_index_cnt);
959                         if (ret) {
960                                 fprintf(stderr, "add_directory_items failed\n");
961                                 goto fail;
962                         }
963
964                         ret = add_inode_items(trans, root, &st,
965                                               cur_file->d_name, cur_inum,
966                                               parent_inum, dir_index_cnt,
967                                               &cur_inode);
968                         if (ret) {
969                                 fprintf(stderr, "add_inode_items failed\n");
970                                 goto fail;
971                         }
972
973                         ret = add_xattr_item(trans, root,
974                                              cur_inum, cur_file->d_name);
975                         if (ret) {
976                                 fprintf(stderr, "add_xattr_item failed\n");
977                                 if(ret != -ENOTSUP)
978                                         goto fail;
979                         }
980
981                         if (S_ISDIR(st.st_mode)) {
982                                 dir_entry = malloc(sizeof(struct directory_name_entry));
983                                 dir_entry->dir_name = cur_file->d_name;
984                                 dir_entry->path = make_path(parent_dir_entry->path,
985                                                             cur_file->d_name);
986                                 dir_entry->inum = cur_inum;
987                                 list_add_tail(&dir_entry->list, &dir_head->list);
988                         } else if (S_ISREG(st.st_mode)) {
989                                 ret = add_file_items(trans, root, &cur_inode,
990                                                      cur_inum, parent_inum, &st,
991                                                      cur_file->d_name, out_fd);
992                                 if (ret) {
993                                         fprintf(stderr, "add_file_items failed\n");
994                                         goto fail;
995                                 }
996                         } else if (S_ISLNK(st.st_mode)) {
997                                 ret = add_symbolic_link(trans, root,
998                                                         cur_inum, cur_file->d_name);
999                                 if (ret) {
1000                                         fprintf(stderr, "add_symbolic_link failed\n");
1001                                         goto fail;
1002                                 }
1003                         }
1004                 }
1005
1006                 free_namelist(files, count);
1007                 free(parent_dir_entry->path);
1008                 free(parent_dir_entry);
1009
1010                 index_cnt = 2;
1011
1012         } while (!list_empty(&dir_head->list));
1013
1014         return 0;
1015 fail:
1016         free_namelist(files, count);
1017 fail_no_files:
1018         free(parent_dir_entry->path);
1019         free(parent_dir_entry);
1020         return -1;
1021 }
1022
1023 static int open_target(char *output_name)
1024 {
1025         int output_fd;
1026         output_fd = open(output_name, O_CREAT | O_RDWR | O_TRUNC,
1027                          S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
1028
1029         return output_fd;
1030 }
1031
1032 static int create_chunks(struct btrfs_trans_handle *trans,
1033                          struct btrfs_root *root, u64 num_of_meta_chunks,
1034                          u64 size_of_data)
1035 {
1036         u64 chunk_start;
1037         u64 chunk_size;
1038         u64 meta_type = BTRFS_BLOCK_GROUP_METADATA;
1039         u64 data_type = BTRFS_BLOCK_GROUP_DATA;
1040         u64 minimum_data_chunk_size = 8 * 1024 * 1024;
1041         u64 i;
1042         int ret;
1043
1044         for (i = 0; i < num_of_meta_chunks; i++) {
1045                 ret = btrfs_alloc_chunk(trans, root->fs_info->extent_root,
1046                                         &chunk_start, &chunk_size, meta_type);
1047                 BUG_ON(ret);
1048                 ret = btrfs_make_block_group(trans, root->fs_info->extent_root, 0,
1049                                              meta_type, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
1050                                              chunk_start, chunk_size);
1051                 BUG_ON(ret);
1052                 set_extent_dirty(&root->fs_info->free_space_cache,
1053                                  chunk_start, chunk_start + chunk_size - 1, 0);
1054         }
1055
1056         if (size_of_data < minimum_data_chunk_size)
1057                 size_of_data = minimum_data_chunk_size;
1058         ret = btrfs_alloc_data_chunk(trans, root->fs_info->extent_root,
1059                                      &chunk_start, size_of_data, data_type);
1060         BUG_ON(ret);
1061         ret = btrfs_make_block_group(trans, root->fs_info->extent_root, 0,
1062                                      data_type, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
1063                                      chunk_start, size_of_data);
1064         BUG_ON(ret);
1065         set_extent_dirty(&root->fs_info->free_space_cache,
1066                          chunk_start, chunk_start + size_of_data - 1, 0);
1067         return ret;
1068 }
1069
1070 static int make_image(char *source_dir, struct btrfs_root *root, int out_fd)
1071 {
1072         int ret;
1073         struct btrfs_trans_handle *trans;
1074
1075         struct stat root_st;
1076
1077         struct directory_name_entry dir_head;
1078
1079         ret = lstat(source_dir, &root_st);
1080         if (ret) {
1081                 fprintf(stderr, "unable to lstat the %s\n", source_dir);
1082                 goto fail;
1083         }
1084
1085         INIT_LIST_HEAD(&dir_head.list);
1086
1087         trans = btrfs_start_transaction(root, 1);
1088         ret = traverse_directory(trans, root, source_dir, &dir_head, out_fd);
1089         if (ret) {
1090                 fprintf(stderr, "unable to traverse_directory\n");
1091                 goto fail;
1092         }
1093         btrfs_commit_transaction(trans, root);
1094
1095         printf("Making image is completed.\n");
1096         return 0;
1097 fail:
1098         fprintf(stderr, "Making image is aborted.\n");
1099         return -1;
1100 }
1101
1102 static u64 size_sourcedir(char *dir_name, u64 sectorsize,
1103                           u64 *num_of_meta_chunks_ret, u64 *size_of_data_ret)
1104 {
1105         u64 dir_size = 0;
1106         u64 total_size = 0;
1107         int ret;
1108         char command[1024];
1109         char path[512];
1110         char *file_name = "temp_file";
1111         FILE *file;
1112         u64 default_chunk_size = 8 * 1024 * 1024;       /* 8MB */
1113         u64 allocated_meta_size = 8 * 1024 * 1024;      /* 8MB */
1114         u64 allocated_total_size = 20 * 1024 * 1024;    /* 20MB */
1115         u64 num_of_meta_chunks = 0;
1116         u64 num_of_allocated_meta_chunks =
1117                         allocated_meta_size / default_chunk_size;
1118
1119         ret = sprintf(command, "du -B 4096 -s ");
1120         if (ret < 0) {
1121                 fprintf(stderr, "error executing sprintf for du command\n");
1122                 return -1;
1123         }
1124         strcat(command, dir_name);
1125         strcat(command, " > ");
1126         strcat(command, file_name);
1127         ret = system(command);
1128
1129         file = fopen(file_name, "r");
1130         ret = fscanf(file, "%lld %s\n", &dir_size, path);
1131         fclose(file);
1132         remove(file_name);
1133
1134         dir_size *= sectorsize;
1135         *size_of_data_ret = dir_size;
1136
1137         num_of_meta_chunks = (dir_size / 2) / default_chunk_size;
1138         if (((dir_size / 2) % default_chunk_size) != 0)
1139                 num_of_meta_chunks++;
1140         if (num_of_meta_chunks <= num_of_allocated_meta_chunks)
1141                 num_of_meta_chunks = 0;
1142         else
1143                 num_of_meta_chunks -= num_of_allocated_meta_chunks;
1144
1145         total_size = allocated_total_size + dir_size +
1146                      (num_of_meta_chunks * default_chunk_size);
1147
1148         *num_of_meta_chunks_ret = num_of_meta_chunks;
1149
1150         return total_size;
1151 }
1152
1153 static int zero_output_file(int out_fd, u64 size, u32 sectorsize)
1154 {
1155         int len = sectorsize;
1156         int loop_num = size / sectorsize;
1157         u64 location = 0;
1158         char *buf = malloc(len);
1159         int ret = 0, i;
1160         ssize_t written;
1161
1162         if (!buf)
1163                 return -ENOMEM;
1164         memset(buf, 0, len);
1165         for (i = 0; i < loop_num; i++) {
1166                 written = pwrite64(out_fd, buf, len, location);
1167                 if (written != len)
1168                         ret = -EIO;
1169                 location += sectorsize;
1170         }
1171         free(buf);
1172         return ret;
1173 }
1174
1175 static int check_leaf_or_node_size(u32 size, u32 sectorsize)
1176 {
1177         if (size < sectorsize) {
1178                 fprintf(stderr,
1179                         "Illegal leafsize (or nodesize) %u (smaller than %u)\n",
1180                         size, sectorsize);
1181                 return -1;
1182         } else if (size > BTRFS_MAX_METADATA_BLOCKSIZE) {
1183                 fprintf(stderr,
1184                         "Illegal leafsize (or nodesize) %u (larger than %u)\n",
1185                         size, BTRFS_MAX_METADATA_BLOCKSIZE);
1186                 return -1;
1187         } else if (size & (sectorsize - 1)) {
1188                 fprintf(stderr,
1189                         "Illegal leafsize (or nodesize) %u (not align to %u)\n",
1190                         size, sectorsize);
1191                 return -1;
1192         }
1193         return 0;
1194 }
1195
1196 int main(int ac, char **av)
1197 {
1198         char *file;
1199         struct btrfs_root *root;
1200         struct btrfs_trans_handle *trans;
1201         char *label = NULL;
1202         char *first_file;
1203         u64 block_count = 0;
1204         u64 dev_block_count = 0;
1205         u64 blocks[7];
1206         u64 alloc_start = 0;
1207         u64 metadata_profile = 0;
1208         u64 data_profile = 0;
1209         u32 leafsize = getpagesize();
1210         u32 sectorsize = 4096;
1211         u32 nodesize = leafsize;
1212         u32 stripesize = 4096;
1213         int zero_end = 1;
1214         int option_index = 0;
1215         int fd;
1216         int ret;
1217         int i;
1218         int mixed = 0;
1219         int data_profile_opt = 0;
1220         int metadata_profile_opt = 0;
1221         int nodiscard = 0;
1222
1223         char *source_dir = NULL;
1224         int source_dir_set = 0;
1225         u64 num_of_meta_chunks = 0;
1226         u64 size_of_data = 0;
1227         u64 source_dir_size = 0;
1228         char *pretty_buf;
1229
1230         while(1) {
1231                 int c;
1232                 c = getopt_long(ac, av, "A:b:l:n:s:m:d:L:r:VMK", long_options,
1233                                 &option_index);
1234                 if (c < 0)
1235                         break;
1236                 switch(c) {
1237                         case 'A':
1238                                 alloc_start = parse_size(optarg);
1239                                 break;
1240                         case 'd':
1241                                 data_profile = parse_profile(optarg);
1242                                 data_profile_opt = 1;
1243                                 break;
1244                         case 'l':
1245                         case 'n':
1246                                 nodesize = parse_size(optarg);
1247                                 leafsize = parse_size(optarg);
1248                                 break;
1249                         case 'L':
1250                                 label = parse_label(optarg);
1251                                 break;
1252                         case 'm':
1253                                 metadata_profile = parse_profile(optarg);
1254                                 metadata_profile_opt = 1;
1255                                 break;
1256                         case 'M':
1257                                 mixed = 1;
1258                                 break;
1259                         case 's':
1260                                 sectorsize = parse_size(optarg);
1261                                 break;
1262                         case 'b':
1263                                 block_count = parse_size(optarg);
1264                                 if (block_count <= 1024*1024*1024) {
1265                                         printf("SMALL VOLUME: forcing mixed "
1266                                                "metadata/data groups\n");
1267                                         mixed = 1;
1268                                 }
1269                                 zero_end = 0;
1270                                 break;
1271                         case 'V':
1272                                 print_version();
1273                                 break;
1274                         case 'r':
1275                                 source_dir = optarg;
1276                                 source_dir_set = 1;
1277                                 break;
1278                         case 'K':
1279                                 nodiscard=1;
1280                                 break;
1281                         default:
1282                                 print_usage();
1283                 }
1284         }
1285         sectorsize = max(sectorsize, (u32)getpagesize());
1286         if (check_leaf_or_node_size(leafsize, sectorsize))
1287                 exit(1);
1288         if (check_leaf_or_node_size(nodesize, sectorsize))
1289                 exit(1);
1290         ac = ac - optind;
1291         if (ac == 0)
1292                 print_usage();
1293
1294         printf("\nWARNING! - %s IS EXPERIMENTAL\n", BTRFS_BUILD_VERSION);
1295         printf("WARNING! - see http://btrfs.wiki.kernel.org before using\n\n");
1296
1297         if (source_dir == 0) {
1298                 file = av[optind++];
1299                 ret = check_mounted(file);
1300                 if (ret < 0) {
1301                         fprintf(stderr, "error checking %s mount status\n", file);
1302                         exit(1);
1303                 }
1304                 if (ret == 1) {
1305                         fprintf(stderr, "%s is mounted\n", file);
1306                         exit(1);
1307                 }
1308                 ac--;
1309                 fd = open(file, O_RDWR);
1310                 if (fd < 0) {
1311                         fprintf(stderr, "unable to open %s\n", file);
1312                         exit(1);
1313                 }
1314                 first_file = file;
1315                 ret = btrfs_prepare_device(fd, file, zero_end, &dev_block_count,
1316                                            block_count, &mixed, nodiscard);
1317                 if (block_count && block_count > dev_block_count) {
1318                         fprintf(stderr, "%s is smaller than requested size\n", file);
1319                         exit(1);
1320                 }
1321         } else {
1322                 ac = 0;
1323                 file = av[optind++];
1324                 fd = open_target(file);
1325                 if (fd < 0) {
1326                         fprintf(stderr, "unable to open the %s\n", file);
1327                         exit(1);
1328                 }
1329
1330                 first_file = file;
1331                 source_dir_size = size_sourcedir(source_dir, sectorsize,
1332                                              &num_of_meta_chunks, &size_of_data);
1333                 if(block_count < source_dir_size)
1334                         block_count = source_dir_size;
1335                 ret = zero_output_file(fd, block_count, sectorsize);
1336                 if (ret) {
1337                         fprintf(stderr, "unable to zero the output file\n");
1338                         exit(1);
1339                 }
1340         }
1341         if (mixed) {
1342                 if (metadata_profile != data_profile) {
1343                         fprintf(stderr, "With mixed block groups data and metadata "
1344                                 "profiles must be the same\n");
1345                         exit(1);
1346                 }
1347         }
1348
1349         blocks[0] = BTRFS_SUPER_INFO_OFFSET;
1350         for (i = 1; i < 7; i++) {
1351                 blocks[i] = BTRFS_SUPER_INFO_OFFSET + 1024 * 1024 +
1352                         leafsize * i;
1353         }
1354
1355         ret = make_btrfs(fd, file, label, blocks, dev_block_count,
1356                          nodesize, leafsize,
1357                          sectorsize, stripesize);
1358         if (ret) {
1359                 fprintf(stderr, "error during mkfs %d\n", ret);
1360                 exit(1);
1361         }
1362
1363         root = open_ctree(file, 0, O_RDWR);
1364         if (!root) {
1365                 fprintf(stderr, "Open ctree failed\n");
1366                 close(fd);
1367                 exit(1);
1368         }
1369         root->fs_info->alloc_start = alloc_start;
1370
1371         ret = make_root_dir(root, mixed);
1372         if (ret) {
1373                 fprintf(stderr, "failed to setup the root directory\n");
1374                 exit(1);
1375         }
1376
1377         trans = btrfs_start_transaction(root, 1);
1378
1379         if (ac == 0)
1380                 goto raid_groups;
1381
1382         btrfs_register_one_device(file);
1383
1384         zero_end = 1;
1385         while(ac-- > 0) {
1386                 int old_mixed = mixed;
1387
1388                 file = av[optind++];
1389                 ret = check_mounted(file);
1390                 if (ret < 0) {
1391                         fprintf(stderr, "error checking %s mount status\n",
1392                                 file);
1393                         exit(1);
1394                 }
1395                 if (ret == 1) {
1396                         fprintf(stderr, "%s is mounted\n", file);
1397                         exit(1);
1398                 }
1399                 fd = open(file, O_RDWR);
1400                 if (fd < 0) {
1401                         fprintf(stderr, "unable to open %s\n", file);
1402                         exit(1);
1403                 }
1404                 ret = btrfs_device_already_in_root(root, fd,
1405                                                    BTRFS_SUPER_INFO_OFFSET);
1406                 if (ret) {
1407                         fprintf(stderr, "skipping duplicate device %s in FS\n",
1408                                 file);
1409                         close(fd);
1410                         continue;
1411                 }
1412                 ret = btrfs_prepare_device(fd, file, zero_end, &dev_block_count,
1413                                            block_count, &mixed, nodiscard);
1414                 mixed = old_mixed;
1415                 BUG_ON(ret);
1416
1417                 ret = btrfs_add_to_fsid(trans, root, fd, file, dev_block_count,
1418                                         sectorsize, sectorsize, sectorsize);
1419                 BUG_ON(ret);
1420                 btrfs_register_one_device(file);
1421         }
1422
1423 raid_groups:
1424         if (!source_dir_set) {
1425                 ret = create_raid_groups(trans, root, data_profile,
1426                                  data_profile_opt, metadata_profile,
1427                                  metadata_profile_opt, mixed);
1428                 BUG_ON(ret);
1429         }
1430
1431         ret = create_data_reloc_tree(trans, root);
1432         BUG_ON(ret);
1433
1434         if (mixed) {
1435                 struct btrfs_super_block *super = &root->fs_info->super_copy;
1436                 u64 flags = btrfs_super_incompat_flags(super);
1437
1438                 flags |= BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS;
1439                 btrfs_set_super_incompat_flags(super, flags);
1440         }
1441
1442         printf("fs created label %s on %s\n\tnodesize %u leafsize %u "
1443             "sectorsize %u size %s\n",
1444             label, first_file, nodesize, leafsize, sectorsize,
1445             pretty_buf = pretty_sizes(btrfs_super_total_bytes(&root->fs_info->super_copy)));
1446         free(pretty_buf);
1447
1448         printf("%s\n", BTRFS_BUILD_VERSION);
1449         btrfs_commit_transaction(trans, root);
1450
1451         if (source_dir_set) {
1452                 trans = btrfs_start_transaction(root, 1);
1453                 ret = create_chunks(trans, root,
1454                                     num_of_meta_chunks, size_of_data);
1455                 BUG_ON(ret);
1456                 btrfs_commit_transaction(trans, root);
1457
1458                 ret = make_image(source_dir, root, fd);
1459                 BUG_ON(ret);
1460         }
1461
1462         ret = close_ctree(root);
1463         BUG_ON(ret);
1464
1465         free(label);
1466         return 0;
1467 }
1468