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