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