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