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