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