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