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