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