btrfs-progs: check: original mode: Check inline extent size
[platform/upstream/btrfs-progs.git] / mkfs / common.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public
4  * License v2 as published by the Free Software Foundation.
5  *
6  * This program is distributed in the hope that it will be useful,
7  * but WITHOUT ANY WARRANTY; without even the implied warranty of
8  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
9  * General Public License for more details.
10  *
11  * You should have received a copy of the GNU General Public
12  * License along with this program; if not, write to the
13  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
14  * Boston, MA 021110-1307, USA.
15  */
16
17 #include <unistd.h>
18 #include <uuid/uuid.h>
19 #include <blkid/blkid.h>
20 #include <fcntl.h>
21 #include <limits.h>
22 #include "ctree.h"
23 #include "disk-io.h"
24 #include "volumes.h"
25 #include "utils.h"
26 #include "mkfs/common.h"
27
28 static u64 reference_root_table[] = {
29         [1] =   BTRFS_ROOT_TREE_OBJECTID,
30         [2] =   BTRFS_EXTENT_TREE_OBJECTID,
31         [3] =   BTRFS_CHUNK_TREE_OBJECTID,
32         [4] =   BTRFS_DEV_TREE_OBJECTID,
33         [5] =   BTRFS_FS_TREE_OBJECTID,
34         [6] =   BTRFS_CSUM_TREE_OBJECTID,
35 };
36
37 static int btrfs_create_tree_root(int fd, struct btrfs_mkfs_config *cfg,
38                         struct extent_buffer *buf)
39 {
40         struct btrfs_root_item root_item;
41         struct btrfs_inode_item *inode_item;
42         struct btrfs_disk_key disk_key;
43         u32 nritems = 0;
44         u32 itemoff;
45         int ret = 0;
46         int blk;
47
48         memset(buf->data + sizeof(struct btrfs_header), 0,
49                 cfg->nodesize - sizeof(struct btrfs_header));
50         memset(&root_item, 0, sizeof(root_item));
51         memset(&disk_key, 0, sizeof(disk_key));
52
53         /* create the items for the root tree */
54         inode_item = &root_item.inode;
55         btrfs_set_stack_inode_generation(inode_item, 1);
56         btrfs_set_stack_inode_size(inode_item, 3);
57         btrfs_set_stack_inode_nlink(inode_item, 1);
58         btrfs_set_stack_inode_nbytes(inode_item, cfg->nodesize);
59         btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
60         btrfs_set_root_refs(&root_item, 1);
61         btrfs_set_root_used(&root_item, cfg->nodesize);
62         btrfs_set_root_generation(&root_item, 1);
63
64         btrfs_set_disk_key_type(&disk_key, BTRFS_ROOT_ITEM_KEY);
65         btrfs_set_disk_key_offset(&disk_key, 0);
66         itemoff = __BTRFS_LEAF_DATA_SIZE(cfg->nodesize) - sizeof(root_item);
67
68         for (blk = 0; blk < MKFS_BLOCK_COUNT; blk++) {
69                 if (blk == MKFS_SUPER_BLOCK || blk == MKFS_ROOT_TREE
70                     || blk == MKFS_CHUNK_TREE)
71                         continue;
72
73                 btrfs_set_root_bytenr(&root_item, cfg->blocks[blk]);
74                 btrfs_set_disk_key_objectid(&disk_key,
75                         reference_root_table[blk]);
76                 btrfs_set_item_key(buf, &disk_key, nritems);
77                 btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
78                 btrfs_set_item_size(buf, btrfs_item_nr(nritems),
79                                 sizeof(root_item));
80                 write_extent_buffer(buf, &root_item,
81                         btrfs_item_ptr_offset(buf, nritems),
82                         sizeof(root_item));
83                 nritems++;
84                 itemoff -= sizeof(root_item);
85         }
86
87         /* generate checksum */
88         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
89
90         /* write back root tree */
91         ret = pwrite(fd, buf->data, cfg->nodesize, cfg->blocks[MKFS_ROOT_TREE]);
92         if (ret != cfg->nodesize)
93                 return (ret < 0 ? -errno : -EIO);
94
95         return ret;
96 }
97
98 /*
99  * @fs_uuid - if NULL, generates a UUID, returns back the new filesystem UUID
100  *
101  * The superblock signature is not valid, denotes a partially created
102  * filesystem, needs to be finalized.
103  *
104  * The temporary fs will have the following chunk layout:
105  * Device extent:
106  * 0            1M                              5M      ......
107  * | Reserved   | dev extent for SYS chunk      |
108  *
109  * And chunk mapping will be:
110  * Chunk mapping:
111  * 0            1M                              5M
112  * |            | System chunk, 1:1 mapped      |
113  *
114  * That's to say, there will only be *ONE* system chunk, mapped to
115  * [1M, 5M) physical offset.
116  * And the only chunk is also in logical address [1M, 5M), containing
117  * all essential tree blocks.
118  */
119 int make_btrfs(int fd, struct btrfs_mkfs_config *cfg)
120 {
121         struct btrfs_super_block super;
122         struct extent_buffer *buf;
123         struct btrfs_disk_key disk_key;
124         struct btrfs_extent_item *extent_item;
125         struct btrfs_chunk *chunk;
126         struct btrfs_dev_item *dev_item;
127         struct btrfs_dev_extent *dev_extent;
128         u8 chunk_tree_uuid[BTRFS_UUID_SIZE];
129         u8 *ptr;
130         int i;
131         int ret;
132         u32 itemoff;
133         u32 nritems = 0;
134         u64 first_free;
135         u64 ref_root;
136         u32 array_size;
137         u32 item_size;
138         int skinny_metadata = !!(cfg->features &
139                                  BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA);
140         u64 num_bytes;
141
142         buf = malloc(sizeof(*buf) + max(cfg->sectorsize, cfg->nodesize));
143         if (!buf)
144                 return -ENOMEM;
145
146         first_free = BTRFS_SUPER_INFO_OFFSET + cfg->sectorsize * 2 - 1;
147         first_free &= ~((u64)cfg->sectorsize - 1);
148
149         memset(&super, 0, sizeof(super));
150
151         num_bytes = (cfg->num_bytes / cfg->sectorsize) * cfg->sectorsize;
152         if (*cfg->fs_uuid) {
153                 if (uuid_parse(cfg->fs_uuid, super.fsid) != 0) {
154                         error("cannot not parse UUID: %s", cfg->fs_uuid);
155                         ret = -EINVAL;
156                         goto out;
157                 }
158                 if (!test_uuid_unique(cfg->fs_uuid)) {
159                         error("non-unique UUID: %s", cfg->fs_uuid);
160                         ret = -EBUSY;
161                         goto out;
162                 }
163         } else {
164                 uuid_generate(super.fsid);
165                 uuid_unparse(super.fsid, cfg->fs_uuid);
166         }
167         uuid_generate(super.dev_item.uuid);
168         uuid_generate(chunk_tree_uuid);
169
170         cfg->blocks[MKFS_SUPER_BLOCK] = BTRFS_SUPER_INFO_OFFSET;
171         for (i = 1; i < MKFS_BLOCK_COUNT; i++) {
172                 cfg->blocks[i] = BTRFS_BLOCK_RESERVED_1M_FOR_SUPER +
173                         cfg->nodesize * (i - 1);
174         }
175
176         btrfs_set_super_bytenr(&super, cfg->blocks[MKFS_SUPER_BLOCK]);
177         btrfs_set_super_num_devices(&super, 1);
178         btrfs_set_super_magic(&super, BTRFS_MAGIC_PARTIAL);
179         btrfs_set_super_generation(&super, 1);
180         btrfs_set_super_root(&super, cfg->blocks[MKFS_ROOT_TREE]);
181         btrfs_set_super_chunk_root(&super, cfg->blocks[MKFS_CHUNK_TREE]);
182         btrfs_set_super_total_bytes(&super, num_bytes);
183         btrfs_set_super_bytes_used(&super, 6 * cfg->nodesize);
184         btrfs_set_super_sectorsize(&super, cfg->sectorsize);
185         super.__unused_leafsize = cpu_to_le32(cfg->nodesize);
186         btrfs_set_super_nodesize(&super, cfg->nodesize);
187         btrfs_set_super_stripesize(&super, cfg->stripesize);
188         btrfs_set_super_csum_type(&super, BTRFS_CSUM_TYPE_CRC32);
189         btrfs_set_super_chunk_root_generation(&super, 1);
190         btrfs_set_super_cache_generation(&super, -1);
191         btrfs_set_super_incompat_flags(&super, cfg->features);
192         if (cfg->label)
193                 __strncpy_null(super.label, cfg->label, BTRFS_LABEL_SIZE - 1);
194
195         /* create the tree of root objects */
196         memset(buf->data, 0, cfg->nodesize);
197         buf->len = cfg->nodesize;
198         btrfs_set_header_bytenr(buf, cfg->blocks[MKFS_ROOT_TREE]);
199         btrfs_set_header_nritems(buf, 4);
200         btrfs_set_header_generation(buf, 1);
201         btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
202         btrfs_set_header_owner(buf, BTRFS_ROOT_TREE_OBJECTID);
203         write_extent_buffer(buf, super.fsid, btrfs_header_fsid(),
204                             BTRFS_FSID_SIZE);
205
206         write_extent_buffer(buf, chunk_tree_uuid,
207                             btrfs_header_chunk_tree_uuid(buf),
208                             BTRFS_UUID_SIZE);
209
210         ret = btrfs_create_tree_root(fd, cfg, buf);
211         if (ret < 0)
212                 goto out;
213
214         /* create the items for the extent tree */
215         memset(buf->data + sizeof(struct btrfs_header), 0,
216                 cfg->nodesize - sizeof(struct btrfs_header));
217         nritems = 0;
218         itemoff = __BTRFS_LEAF_DATA_SIZE(cfg->nodesize);
219         for (i = 1; i < MKFS_BLOCK_COUNT; i++) {
220                 item_size = sizeof(struct btrfs_extent_item);
221                 if (!skinny_metadata)
222                         item_size += sizeof(struct btrfs_tree_block_info);
223
224                 if (cfg->blocks[i] < first_free) {
225                         error("block[%d] below first free: %llu < %llu",
226                                         i, (unsigned long long)cfg->blocks[i],
227                                         (unsigned long long)first_free);
228                         ret = -EINVAL;
229                         goto out;
230                 }
231                 if (cfg->blocks[i] < cfg->blocks[i - 1]) {
232                         error("blocks %d and %d in reverse order: %llu < %llu",
233                                 i, i - 1,
234                                 (unsigned long long)cfg->blocks[i],
235                                 (unsigned long long)cfg->blocks[i - 1]);
236                         ret = -EINVAL;
237                         goto out;
238                 }
239
240                 /* create extent item */
241                 itemoff -= item_size;
242                 btrfs_set_disk_key_objectid(&disk_key, cfg->blocks[i]);
243                 if (skinny_metadata) {
244                         btrfs_set_disk_key_type(&disk_key,
245                                                 BTRFS_METADATA_ITEM_KEY);
246                         btrfs_set_disk_key_offset(&disk_key, 0);
247                 } else {
248                         btrfs_set_disk_key_type(&disk_key,
249                                                 BTRFS_EXTENT_ITEM_KEY);
250                         btrfs_set_disk_key_offset(&disk_key, cfg->nodesize);
251                 }
252                 btrfs_set_item_key(buf, &disk_key, nritems);
253                 btrfs_set_item_offset(buf, btrfs_item_nr(nritems),
254                                       itemoff);
255                 btrfs_set_item_size(buf, btrfs_item_nr(nritems),
256                                     item_size);
257                 extent_item = btrfs_item_ptr(buf, nritems,
258                                              struct btrfs_extent_item);
259                 btrfs_set_extent_refs(buf, extent_item, 1);
260                 btrfs_set_extent_generation(buf, extent_item, 1);
261                 btrfs_set_extent_flags(buf, extent_item,
262                                        BTRFS_EXTENT_FLAG_TREE_BLOCK);
263                 nritems++;
264
265                 /* create extent ref */
266                 ref_root = reference_root_table[i];
267                 btrfs_set_disk_key_objectid(&disk_key, cfg->blocks[i]);
268                 btrfs_set_disk_key_offset(&disk_key, ref_root);
269                 btrfs_set_disk_key_type(&disk_key, BTRFS_TREE_BLOCK_REF_KEY);
270                 btrfs_set_item_key(buf, &disk_key, nritems);
271                 btrfs_set_item_offset(buf, btrfs_item_nr(nritems),
272                                       itemoff);
273                 btrfs_set_item_size(buf, btrfs_item_nr(nritems), 0);
274                 nritems++;
275         }
276         btrfs_set_header_bytenr(buf, cfg->blocks[MKFS_EXTENT_TREE]);
277         btrfs_set_header_owner(buf, BTRFS_EXTENT_TREE_OBJECTID);
278         btrfs_set_header_nritems(buf, nritems);
279         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
280         ret = pwrite(fd, buf->data, cfg->nodesize, cfg->blocks[MKFS_EXTENT_TREE]);
281         if (ret != cfg->nodesize) {
282                 ret = (ret < 0 ? -errno : -EIO);
283                 goto out;
284         }
285
286         /* create the chunk tree */
287         memset(buf->data + sizeof(struct btrfs_header), 0,
288                 cfg->nodesize - sizeof(struct btrfs_header));
289         nritems = 0;
290         item_size = sizeof(*dev_item);
291         itemoff = __BTRFS_LEAF_DATA_SIZE(cfg->nodesize) - item_size;
292
293         /* first device 1 (there is no device 0) */
294         btrfs_set_disk_key_objectid(&disk_key, BTRFS_DEV_ITEMS_OBJECTID);
295         btrfs_set_disk_key_offset(&disk_key, 1);
296         btrfs_set_disk_key_type(&disk_key, BTRFS_DEV_ITEM_KEY);
297         btrfs_set_item_key(buf, &disk_key, nritems);
298         btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
299         btrfs_set_item_size(buf, btrfs_item_nr(nritems), item_size);
300
301         dev_item = btrfs_item_ptr(buf, nritems, struct btrfs_dev_item);
302         btrfs_set_device_id(buf, dev_item, 1);
303         btrfs_set_device_generation(buf, dev_item, 0);
304         btrfs_set_device_total_bytes(buf, dev_item, num_bytes);
305         btrfs_set_device_bytes_used(buf, dev_item,
306                                     BTRFS_MKFS_SYSTEM_GROUP_SIZE);
307         btrfs_set_device_io_align(buf, dev_item, cfg->sectorsize);
308         btrfs_set_device_io_width(buf, dev_item, cfg->sectorsize);
309         btrfs_set_device_sector_size(buf, dev_item, cfg->sectorsize);
310         btrfs_set_device_type(buf, dev_item, 0);
311
312         write_extent_buffer(buf, super.dev_item.uuid,
313                             (unsigned long)btrfs_device_uuid(dev_item),
314                             BTRFS_UUID_SIZE);
315         write_extent_buffer(buf, super.fsid,
316                             (unsigned long)btrfs_device_fsid(dev_item),
317                             BTRFS_UUID_SIZE);
318         read_extent_buffer(buf, &super.dev_item, (unsigned long)dev_item,
319                            sizeof(*dev_item));
320
321         nritems++;
322         item_size = btrfs_chunk_item_size(1);
323         itemoff = itemoff - item_size;
324
325         /* then we have chunk 0 */
326         btrfs_set_disk_key_objectid(&disk_key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
327         btrfs_set_disk_key_offset(&disk_key, BTRFS_BLOCK_RESERVED_1M_FOR_SUPER);
328         btrfs_set_disk_key_type(&disk_key, BTRFS_CHUNK_ITEM_KEY);
329         btrfs_set_item_key(buf, &disk_key, nritems);
330         btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
331         btrfs_set_item_size(buf, btrfs_item_nr(nritems), item_size);
332
333         chunk = btrfs_item_ptr(buf, nritems, struct btrfs_chunk);
334         btrfs_set_chunk_length(buf, chunk, BTRFS_MKFS_SYSTEM_GROUP_SIZE);
335         btrfs_set_chunk_owner(buf, chunk, BTRFS_EXTENT_TREE_OBJECTID);
336         btrfs_set_chunk_stripe_len(buf, chunk, BTRFS_STRIPE_LEN);
337         btrfs_set_chunk_type(buf, chunk, BTRFS_BLOCK_GROUP_SYSTEM);
338         btrfs_set_chunk_io_align(buf, chunk, cfg->sectorsize);
339         btrfs_set_chunk_io_width(buf, chunk, cfg->sectorsize);
340         btrfs_set_chunk_sector_size(buf, chunk, cfg->sectorsize);
341         btrfs_set_chunk_num_stripes(buf, chunk, 1);
342         btrfs_set_stripe_devid_nr(buf, chunk, 0, 1);
343         btrfs_set_stripe_offset_nr(buf, chunk, 0,
344                                    BTRFS_BLOCK_RESERVED_1M_FOR_SUPER);
345         nritems++;
346
347         write_extent_buffer(buf, super.dev_item.uuid,
348                             (unsigned long)btrfs_stripe_dev_uuid(&chunk->stripe),
349                             BTRFS_UUID_SIZE);
350
351         /* copy the key for the chunk to the system array */
352         ptr = super.sys_chunk_array;
353         array_size = sizeof(disk_key);
354
355         memcpy(ptr, &disk_key, sizeof(disk_key));
356         ptr += sizeof(disk_key);
357
358         /* copy the chunk to the system array */
359         read_extent_buffer(buf, ptr, (unsigned long)chunk, item_size);
360         array_size += item_size;
361         ptr += item_size;
362         btrfs_set_super_sys_array_size(&super, array_size);
363
364         btrfs_set_header_bytenr(buf, cfg->blocks[MKFS_CHUNK_TREE]);
365         btrfs_set_header_owner(buf, BTRFS_CHUNK_TREE_OBJECTID);
366         btrfs_set_header_nritems(buf, nritems);
367         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
368         ret = pwrite(fd, buf->data, cfg->nodesize, cfg->blocks[MKFS_CHUNK_TREE]);
369         if (ret != cfg->nodesize) {
370                 ret = (ret < 0 ? -errno : -EIO);
371                 goto out;
372         }
373
374         /* create the device tree */
375         memset(buf->data + sizeof(struct btrfs_header), 0,
376                 cfg->nodesize - sizeof(struct btrfs_header));
377         nritems = 0;
378         itemoff = __BTRFS_LEAF_DATA_SIZE(cfg->nodesize) -
379                 sizeof(struct btrfs_dev_extent);
380
381         btrfs_set_disk_key_objectid(&disk_key, 1);
382         btrfs_set_disk_key_offset(&disk_key, BTRFS_BLOCK_RESERVED_1M_FOR_SUPER);
383         btrfs_set_disk_key_type(&disk_key, BTRFS_DEV_EXTENT_KEY);
384         btrfs_set_item_key(buf, &disk_key, nritems);
385         btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
386         btrfs_set_item_size(buf, btrfs_item_nr(nritems),
387                             sizeof(struct btrfs_dev_extent));
388         dev_extent = btrfs_item_ptr(buf, nritems, struct btrfs_dev_extent);
389         btrfs_set_dev_extent_chunk_tree(buf, dev_extent,
390                                         BTRFS_CHUNK_TREE_OBJECTID);
391         btrfs_set_dev_extent_chunk_objectid(buf, dev_extent,
392                                         BTRFS_FIRST_CHUNK_TREE_OBJECTID);
393         btrfs_set_dev_extent_chunk_offset(buf, dev_extent,
394                                           BTRFS_BLOCK_RESERVED_1M_FOR_SUPER);
395
396         write_extent_buffer(buf, chunk_tree_uuid,
397                     (unsigned long)btrfs_dev_extent_chunk_tree_uuid(dev_extent),
398                     BTRFS_UUID_SIZE);
399
400         btrfs_set_dev_extent_length(buf, dev_extent,
401                                     BTRFS_MKFS_SYSTEM_GROUP_SIZE);
402         nritems++;
403
404         btrfs_set_header_bytenr(buf, cfg->blocks[MKFS_DEV_TREE]);
405         btrfs_set_header_owner(buf, BTRFS_DEV_TREE_OBJECTID);
406         btrfs_set_header_nritems(buf, nritems);
407         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
408         ret = pwrite(fd, buf->data, cfg->nodesize, cfg->blocks[MKFS_DEV_TREE]);
409         if (ret != cfg->nodesize) {
410                 ret = (ret < 0 ? -errno : -EIO);
411                 goto out;
412         }
413
414         /* create the FS root */
415         memset(buf->data + sizeof(struct btrfs_header), 0,
416                 cfg->nodesize - sizeof(struct btrfs_header));
417         btrfs_set_header_bytenr(buf, cfg->blocks[MKFS_FS_TREE]);
418         btrfs_set_header_owner(buf, BTRFS_FS_TREE_OBJECTID);
419         btrfs_set_header_nritems(buf, 0);
420         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
421         ret = pwrite(fd, buf->data, cfg->nodesize, cfg->blocks[MKFS_FS_TREE]);
422         if (ret != cfg->nodesize) {
423                 ret = (ret < 0 ? -errno : -EIO);
424                 goto out;
425         }
426         /* finally create the csum root */
427         memset(buf->data + sizeof(struct btrfs_header), 0,
428                 cfg->nodesize - sizeof(struct btrfs_header));
429         btrfs_set_header_bytenr(buf, cfg->blocks[MKFS_CSUM_TREE]);
430         btrfs_set_header_owner(buf, BTRFS_CSUM_TREE_OBJECTID);
431         btrfs_set_header_nritems(buf, 0);
432         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
433         ret = pwrite(fd, buf->data, cfg->nodesize, cfg->blocks[MKFS_CSUM_TREE]);
434         if (ret != cfg->nodesize) {
435                 ret = (ret < 0 ? -errno : -EIO);
436                 goto out;
437         }
438
439         /* and write out the super block */
440         memset(buf->data, 0, BTRFS_SUPER_INFO_SIZE);
441         memcpy(buf->data, &super, sizeof(super));
442         buf->len = BTRFS_SUPER_INFO_SIZE;
443         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
444         ret = pwrite(fd, buf->data, BTRFS_SUPER_INFO_SIZE,
445                         cfg->blocks[MKFS_SUPER_BLOCK]);
446         if (ret != BTRFS_SUPER_INFO_SIZE) {
447                 ret = (ret < 0 ? -errno : -EIO);
448                 goto out;
449         }
450
451         ret = 0;
452
453 out:
454         free(buf);
455         return ret;
456 }
457
458 /*
459  * Btrfs minimum size calculation is complicated, it should include at least:
460  * 1. system group size
461  * 2. minimum global block reserve
462  * 3. metadata used at mkfs
463  * 4. space reservation to create uuid for first mount.
464  * Also, raid factor should also be taken into consideration.
465  * To avoid the overkill calculation, (system group + global block rsv) * 2
466  * for *EACH* device should be good enough.
467  */
468 static u64 btrfs_min_global_blk_rsv_size(u32 nodesize)
469 {
470         return (u64)nodesize << 10;
471 }
472
473 u64 btrfs_min_dev_size(u32 nodesize, int mixed, u64 meta_profile,
474                        u64 data_profile)
475 {
476         u64 reserved = 0;
477         u64 meta_size;
478         u64 data_size;
479
480         if (mixed)
481                 return 2 * (BTRFS_MKFS_SYSTEM_GROUP_SIZE +
482                             btrfs_min_global_blk_rsv_size(nodesize));
483
484         /*
485          * Minimal size calculation is complex due to several factors:
486          * 0) Reserved 1M range.
487          *
488          * 1) Temporary chunk reuse
489          *    If specified chunk profile is SINGLE, we can reuse
490          *    temporary chunks, no need to allocate new chunks.
491          *
492          * 2) Different minimal chunk size for different profiles:
493          *    For initial sys chunk, chunk size is fixed to 4M.
494          *    For single profile, minimal chunk size is 8M for all.
495          *    For other profiles, minimal chunk and stripe size ranges from 8M
496          *    to 64M.
497          *
498          * To calculate it a little easier, here we assume we don't reuse any
499          * temporary chunk, and calculate the size completely by ourselves.
500          *
501          * Temporary chunks sizes are always fixed:
502          * One initial sys chunk, one SINGLE meta, and one SINGLE data.
503          * The latter two are all 8M, accroding to @calc_size of
504          * btrfs_alloc_chunk().
505          */
506         reserved += BTRFS_BLOCK_RESERVED_1M_FOR_SUPER +
507                     BTRFS_MKFS_SYSTEM_GROUP_SIZE + SZ_8M * 2;
508
509         /*
510          * For real chunks, we need to select different sizes:
511          * For SINGLE, it's still fixed to 8M (@calc_size).
512          * For other profiles, refer to max(@min_stripe_size, @calc_size).
513          *
514          * And use the stripe size to calculate its physical used space.
515          */
516         if (meta_profile & BTRFS_BLOCK_GROUP_PROFILE_MASK)
517                 meta_size = SZ_8M + SZ_32M;
518         else
519                 meta_size = SZ_8M + SZ_8M;
520         /* For DUP/metadata,  2 stripes on one disk */
521         if (meta_profile & BTRFS_BLOCK_GROUP_DUP)
522                 meta_size *= 2;
523         reserved += meta_size;
524
525         if (data_profile & BTRFS_BLOCK_GROUP_PROFILE_MASK)
526                 data_size = SZ_64M;
527         else
528                 data_size = SZ_8M;
529         /* For DUP/data,  2 stripes on one disk */
530         if (data_profile & BTRFS_BLOCK_GROUP_DUP)
531                 data_size *= 2;
532         reserved += data_size;
533
534         return reserved;
535 }
536
537 #define isoctal(c)      (((c) & ~7) == '0')
538
539 static inline void translate(char *f, char *t)
540 {
541         while (*f != '\0') {
542                 if (*f == '\\' &&
543                     isoctal(f[1]) && isoctal(f[2]) && isoctal(f[3])) {
544                         *t++ = 64*(f[1] & 7) + 8*(f[2] & 7) + (f[3] & 7);
545                         f += 4;
546                 } else
547                         *t++ = *f++;
548         }
549         *t = '\0';
550         return;
551 }
552
553 /*
554  * Checks if the swap device.
555  * Returns 1 if swap device, < 0 on error or 0 if not swap device.
556  */
557 static int is_swap_device(const char *file)
558 {
559         FILE    *f;
560         struct stat     st_buf;
561         dev_t   dev;
562         ino_t   ino = 0;
563         char    tmp[PATH_MAX];
564         char    buf[PATH_MAX];
565         char    *cp;
566         int     ret = 0;
567
568         if (stat(file, &st_buf) < 0)
569                 return -errno;
570         if (S_ISBLK(st_buf.st_mode))
571                 dev = st_buf.st_rdev;
572         else if (S_ISREG(st_buf.st_mode)) {
573                 dev = st_buf.st_dev;
574                 ino = st_buf.st_ino;
575         } else
576                 return 0;
577
578         if ((f = fopen("/proc/swaps", "r")) == NULL)
579                 return 0;
580
581         /* skip the first line */
582         if (fgets(tmp, sizeof(tmp), f) == NULL)
583                 goto out;
584
585         while (fgets(tmp, sizeof(tmp), f) != NULL) {
586                 if ((cp = strchr(tmp, ' ')) != NULL)
587                         *cp = '\0';
588                 if ((cp = strchr(tmp, '\t')) != NULL)
589                         *cp = '\0';
590                 translate(tmp, buf);
591                 if (stat(buf, &st_buf) != 0)
592                         continue;
593                 if (S_ISBLK(st_buf.st_mode)) {
594                         if (dev == st_buf.st_rdev) {
595                                 ret = 1;
596                                 break;
597                         }
598                 } else if (S_ISREG(st_buf.st_mode)) {
599                         if (dev == st_buf.st_dev && ino == st_buf.st_ino) {
600                                 ret = 1;
601                                 break;
602                         }
603                 }
604         }
605
606 out:
607         fclose(f);
608
609         return ret;
610 }
611
612 /*
613  * Check for existing filesystem or partition table on device.
614  * Returns:
615  *       1 for existing fs or partition
616  *       0 for nothing found
617  *      -1 for internal error
618  */
619 static int check_overwrite(const char *device)
620 {
621         const char      *type;
622         blkid_probe     pr = NULL;
623         int             ret;
624         blkid_loff_t    size;
625
626         if (!device || !*device)
627                 return 0;
628
629         ret = -1; /* will reset on success of all setup calls */
630
631         pr = blkid_new_probe_from_filename(device);
632         if (!pr)
633                 goto out;
634
635         size = blkid_probe_get_size(pr);
636         if (size < 0)
637                 goto out;
638
639         /* nothing to overwrite on a 0-length device */
640         if (size == 0) {
641                 ret = 0;
642                 goto out;
643         }
644
645         ret = blkid_probe_enable_partitions(pr, 1);
646         if (ret < 0)
647                 goto out;
648
649         ret = blkid_do_fullprobe(pr);
650         if (ret < 0)
651                 goto out;
652
653         /*
654          * Blkid returns 1 for nothing found and 0 when it finds a signature,
655          * but we want the exact opposite, so reverse the return value here.
656          *
657          * In addition print some useful diagnostics about what actually is
658          * on the device.
659          */
660         if (ret) {
661                 ret = 0;
662                 goto out;
663         }
664
665         if (!blkid_probe_lookup_value(pr, "TYPE", &type, NULL)) {
666                 fprintf(stderr,
667                         "%s appears to contain an existing "
668                         "filesystem (%s).\n", device, type);
669         } else if (!blkid_probe_lookup_value(pr, "PTTYPE", &type, NULL)) {
670                 fprintf(stderr,
671                         "%s appears to contain a partition "
672                         "table (%s).\n", device, type);
673         } else {
674                 fprintf(stderr,
675                         "%s appears to contain something weird "
676                         "according to blkid\n", device);
677         }
678         ret = 1;
679
680 out:
681         if (pr)
682                 blkid_free_probe(pr);
683         if (ret == -1)
684                 fprintf(stderr,
685                         "probe of %s failed, cannot detect "
686                           "existing filesystem.\n", device);
687         return ret;
688 }
689
690 /*
691  * Check if a device is suitable for btrfs
692  * returns:
693  *  1: something is wrong, an error is printed
694  *  0: all is fine
695  */
696 int test_dev_for_mkfs(const char *file, int force_overwrite)
697 {
698         int ret, fd;
699         struct stat st;
700
701         ret = is_swap_device(file);
702         if (ret < 0) {
703                 error("checking status of %s: %s", file, strerror(-ret));
704                 return 1;
705         }
706         if (ret == 1) {
707                 error("%s is a swap device", file);
708                 return 1;
709         }
710         ret = test_status_for_mkfs(file, force_overwrite);
711         if (ret)
712                 return 1;
713         /* check if the device is busy */
714         fd = open(file, O_RDWR|O_EXCL);
715         if (fd < 0) {
716                 error("unable to open %s: %m", file);
717                 return 1;
718         }
719         if (fstat(fd, &st)) {
720                 error("unable to stat %s: %m", file);
721                 close(fd);
722                 return 1;
723         }
724         if (!S_ISBLK(st.st_mode)) {
725                 error("%s is not a block device", file);
726                 close(fd);
727                 return 1;
728         }
729         close(fd);
730         return 0;
731 }
732
733 /*
734  * check if the file (device) is formatted or mounted
735  */
736 int test_status_for_mkfs(const char *file, bool force_overwrite)
737 {
738         int ret;
739
740         if (!force_overwrite) {
741                 if (check_overwrite(file)) {
742                         error("use the -f option to force overwrite of %s",
743                                         file);
744                         return 1;
745                 }
746         }
747         ret = check_mounted(file);
748         if (ret < 0) {
749                 error("cannot check mount status of %s: %s", file,
750                                 strerror(-ret));
751                 return 1;
752         }
753         if (ret == 1) {
754                 error("%s is mounted", file);
755                 return 1;
756         }
757
758         return 0;
759 }
760
761 int is_vol_small(const char *file)
762 {
763         int fd = -1;
764         int e;
765         struct stat st;
766         u64 size;
767
768         fd = open(file, O_RDONLY);
769         if (fd < 0)
770                 return -errno;
771         if (fstat(fd, &st) < 0) {
772                 e = -errno;
773                 close(fd);
774                 return e;
775         }
776         size = btrfs_device_size(fd, &st);
777         if (size == 0) {
778                 close(fd);
779                 return -1;
780         }
781         if (size < BTRFS_MKFS_SMALL_VOLUME_SIZE) {
782                 close(fd);
783                 return 1;
784         } else {
785                 close(fd);
786                 return 0;
787         }
788 }
789
790 int test_minimum_size(const char *file, u64 min_dev_size)
791 {
792         int fd;
793         struct stat statbuf;
794
795         fd = open(file, O_RDONLY);
796         if (fd < 0)
797                 return -errno;
798         if (stat(file, &statbuf) < 0) {
799                 close(fd);
800                 return -errno;
801         }
802         if (btrfs_device_size(fd, &statbuf) < min_dev_size) {
803                 close(fd);
804                 return 1;
805         }
806         close(fd);
807         return 0;
808 }
809
810