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