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