2 * Copyright (C) 2007 Oracle. All rights reserved.
3 * Copyright (C) 2008 Morey Roof. All rights reserved.
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public
7 * License v2 as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public
15 * License along with this program; if not, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 021110-1307, USA.
23 #include <sys/ioctl.h>
24 #include <sys/mount.h>
25 #include <sys/types.h>
27 #include <uuid/uuid.h>
32 #include <linux/loop.h>
33 #include <linux/major.h>
34 #include <linux/kdev_t.h>
36 #include <blkid/blkid.h>
38 #include <sys/statfs.h>
39 #include <linux/magic.h>
40 #include <sys/utsname.h>
41 #include <linux/version.h>
43 #include "kerncompat.h"
44 #include "radix-tree.h"
47 #include "transaction.h"
53 #include "mkfs/common.h"
54 #include "convert/common.h"
57 #define BLKDISCARD _IO(0x12,119)
60 static int btrfs_scan_done = 0;
62 static int rand_seed_initlized = 0;
63 static unsigned short rand_seed[3];
65 struct btrfs_config bconf;
68 * Discard the given range in one go
70 static int discard_range(int fd, u64 start, u64 len)
72 u64 range[2] = { start, len };
74 if (ioctl(fd, BLKDISCARD, &range) < 0)
80 * Discard blocks in the given range in 1G chunks, the process is interruptible
82 static int discard_blocks(int fd, u64 start, u64 len)
86 u64 chunk_size = min_t(u64, len, SZ_1G);
89 ret = discard_range(fd, start, chunk_size);
99 int test_uuid_unique(char *fs_uuid)
102 blkid_dev_iterate iter = NULL;
103 blkid_dev dev = NULL;
104 blkid_cache cache = NULL;
106 if (blkid_get_cache(&cache, NULL) < 0) {
107 printf("ERROR: lblkid cache get failed\n");
110 blkid_probe_all(cache);
111 iter = blkid_dev_iterate_begin(cache);
112 blkid_dev_set_search(iter, "UUID", fs_uuid);
114 while (blkid_dev_next(iter, &dev) == 0) {
115 dev = blkid_verify(cache, dev);
122 blkid_dev_iterate_end(iter);
123 blkid_put_cache(cache);
129 * Reserve space from free_tree.
130 * The algorithm is very simple, find the first cache_extent with enough space
131 * and allocate from its beginning.
133 static int reserve_free_space(struct cache_tree *free_tree, u64 len,
136 struct cache_extent *cache;
139 ASSERT(ret_start != NULL);
140 cache = first_cache_extent(free_tree);
142 if (cache->size > len) {
144 *ret_start = cache->start;
147 if (cache->size == 0) {
148 remove_cache_extent(free_tree, cache);
155 cache = next_cache_extent(cache);
162 static inline int write_temp_super(int fd, struct btrfs_super_block *sb,
168 crc = btrfs_csum_data(NULL, (char *)sb + BTRFS_CSUM_SIZE, crc,
169 BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
170 btrfs_csum_final(crc, &sb->csum[0]);
171 ret = pwrite(fd, sb, BTRFS_SUPER_INFO_SIZE, sb_bytenr);
172 if (ret < BTRFS_SUPER_INFO_SIZE)
173 ret = (ret < 0 ? -errno : -EIO);
180 * Setup temporary superblock at cfg->super_bynter
181 * Needed info are extracted from cfg, and root_bytenr, chunk_bytenr
183 * For now sys chunk array will be empty and dev_item is empty too.
184 * They will be re-initialized at temp chunk tree setup.
186 * The superblock signature is not valid, denotes a partially created
187 * filesystem, needs to be finalized.
189 static int setup_temp_super(int fd, struct btrfs_mkfs_config *cfg,
190 u64 root_bytenr, u64 chunk_bytenr)
192 unsigned char chunk_uuid[BTRFS_UUID_SIZE];
193 char super_buf[BTRFS_SUPER_INFO_SIZE];
194 struct btrfs_super_block *super = (struct btrfs_super_block *)super_buf;
197 memset(super_buf, 0, BTRFS_SUPER_INFO_SIZE);
198 cfg->num_bytes = round_down(cfg->num_bytes, cfg->sectorsize);
201 if (uuid_parse(cfg->fs_uuid, super->fsid) != 0) {
202 error("cound not parse UUID: %s", cfg->fs_uuid);
206 if (!test_uuid_unique(cfg->fs_uuid)) {
207 error("non-unique UUID: %s", cfg->fs_uuid);
212 uuid_generate(super->fsid);
213 uuid_unparse(super->fsid, cfg->fs_uuid);
215 uuid_generate(chunk_uuid);
216 uuid_unparse(chunk_uuid, cfg->chunk_uuid);
218 btrfs_set_super_bytenr(super, cfg->super_bytenr);
219 btrfs_set_super_num_devices(super, 1);
220 btrfs_set_super_magic(super, BTRFS_MAGIC_PARTIAL);
221 btrfs_set_super_generation(super, 1);
222 btrfs_set_super_root(super, root_bytenr);
223 btrfs_set_super_chunk_root(super, chunk_bytenr);
224 btrfs_set_super_total_bytes(super, cfg->num_bytes);
226 * Temporary filesystem will only have 6 tree roots:
227 * chunk tree, root tree, extent_tree, device tree, fs tree
230 btrfs_set_super_bytes_used(super, 6 * cfg->nodesize);
231 btrfs_set_super_sectorsize(super, cfg->sectorsize);
232 btrfs_set_super_leafsize(super, cfg->nodesize);
233 btrfs_set_super_nodesize(super, cfg->nodesize);
234 btrfs_set_super_stripesize(super, cfg->stripesize);
235 btrfs_set_super_csum_type(super, BTRFS_CSUM_TYPE_CRC32);
236 btrfs_set_super_chunk_root(super, chunk_bytenr);
237 btrfs_set_super_cache_generation(super, -1);
238 btrfs_set_super_incompat_flags(super, cfg->features);
240 __strncpy_null(super->label, cfg->label, BTRFS_LABEL_SIZE - 1);
242 /* Sys chunk array will be re-initialized at chunk tree init time */
243 super->sys_chunk_array_size = 0;
245 ret = write_temp_super(fd, super, cfg->super_bytenr);
251 * Setup an extent buffer for tree block.
253 static int setup_temp_extent_buffer(struct extent_buffer *buf,
254 struct btrfs_mkfs_config *cfg,
255 u64 bytenr, u64 owner)
257 unsigned char fsid[BTRFS_FSID_SIZE];
258 unsigned char chunk_uuid[BTRFS_UUID_SIZE];
261 ret = uuid_parse(cfg->fs_uuid, fsid);
264 ret = uuid_parse(cfg->chunk_uuid, chunk_uuid);
268 memset(buf->data, 0, cfg->nodesize);
269 buf->len = cfg->nodesize;
270 btrfs_set_header_bytenr(buf, bytenr);
271 btrfs_set_header_generation(buf, 1);
272 btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
273 btrfs_set_header_owner(buf, owner);
274 btrfs_set_header_flags(buf, BTRFS_HEADER_FLAG_WRITTEN);
275 write_extent_buffer(buf, chunk_uuid, btrfs_header_chunk_tree_uuid(buf),
277 write_extent_buffer(buf, fsid, btrfs_header_fsid(), BTRFS_FSID_SIZE);
281 static inline int write_temp_extent_buffer(int fd, struct extent_buffer *buf,
286 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
288 /* Temporary extent buffer is always mapped 1:1 on disk */
289 ret = pwrite(fd, buf->data, buf->len, bytenr);
291 ret = (ret < 0 ? ret : -EIO);
298 * Insert a root item for temporary tree root
300 * Only used in make_btrfs_v2().
302 static void insert_temp_root_item(struct extent_buffer *buf,
303 struct btrfs_mkfs_config *cfg,
304 int *slot, u32 *itemoff, u64 objectid,
307 struct btrfs_root_item root_item;
308 struct btrfs_inode_item *inode_item;
309 struct btrfs_disk_key disk_key;
311 btrfs_set_header_nritems(buf, *slot + 1);
312 (*itemoff) -= sizeof(root_item);
313 memset(&root_item, 0, sizeof(root_item));
314 inode_item = &root_item.inode;
315 btrfs_set_stack_inode_generation(inode_item, 1);
316 btrfs_set_stack_inode_size(inode_item, 3);
317 btrfs_set_stack_inode_nlink(inode_item, 1);
318 btrfs_set_stack_inode_nbytes(inode_item, cfg->nodesize);
319 btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
320 btrfs_set_root_refs(&root_item, 1);
321 btrfs_set_root_used(&root_item, cfg->nodesize);
322 btrfs_set_root_generation(&root_item, 1);
323 btrfs_set_root_bytenr(&root_item, bytenr);
325 memset(&disk_key, 0, sizeof(disk_key));
326 btrfs_set_disk_key_type(&disk_key, BTRFS_ROOT_ITEM_KEY);
327 btrfs_set_disk_key_objectid(&disk_key, objectid);
328 btrfs_set_disk_key_offset(&disk_key, 0);
330 btrfs_set_item_key(buf, &disk_key, *slot);
331 btrfs_set_item_offset(buf, btrfs_item_nr(*slot), *itemoff);
332 btrfs_set_item_size(buf, btrfs_item_nr(*slot), sizeof(root_item));
333 write_extent_buffer(buf, &root_item,
334 btrfs_item_ptr_offset(buf, *slot),
339 static int setup_temp_root_tree(int fd, struct btrfs_mkfs_config *cfg,
340 u64 root_bytenr, u64 extent_bytenr,
341 u64 dev_bytenr, u64 fs_bytenr, u64 csum_bytenr)
343 struct extent_buffer *buf = NULL;
344 u32 itemoff = __BTRFS_LEAF_DATA_SIZE(cfg->nodesize);
349 * Provided bytenr must in ascending order, or tree root will have a
352 if (!(root_bytenr < extent_bytenr && extent_bytenr < dev_bytenr &&
353 dev_bytenr < fs_bytenr && fs_bytenr < csum_bytenr)) {
354 error("bad tree bytenr order: "
355 "root < extent %llu < %llu, "
356 "extent < dev %llu < %llu, "
357 "dev < fs %llu < %llu, "
358 "fs < csum %llu < %llu",
359 (unsigned long long)root_bytenr,
360 (unsigned long long)extent_bytenr,
361 (unsigned long long)extent_bytenr,
362 (unsigned long long)dev_bytenr,
363 (unsigned long long)dev_bytenr,
364 (unsigned long long)fs_bytenr,
365 (unsigned long long)fs_bytenr,
366 (unsigned long long)csum_bytenr);
369 buf = malloc(sizeof(*buf) + cfg->nodesize);
373 ret = setup_temp_extent_buffer(buf, cfg, root_bytenr,
374 BTRFS_ROOT_TREE_OBJECTID);
378 insert_temp_root_item(buf, cfg, &slot, &itemoff,
379 BTRFS_EXTENT_TREE_OBJECTID, extent_bytenr);
380 insert_temp_root_item(buf, cfg, &slot, &itemoff,
381 BTRFS_DEV_TREE_OBJECTID, dev_bytenr);
382 insert_temp_root_item(buf, cfg, &slot, &itemoff,
383 BTRFS_FS_TREE_OBJECTID, fs_bytenr);
384 insert_temp_root_item(buf, cfg, &slot, &itemoff,
385 BTRFS_CSUM_TREE_OBJECTID, csum_bytenr);
387 ret = write_temp_extent_buffer(fd, buf, root_bytenr);
393 static int insert_temp_dev_item(int fd, struct extent_buffer *buf,
394 struct btrfs_mkfs_config *cfg,
395 int *slot, u32 *itemoff)
397 struct btrfs_disk_key disk_key;
398 struct btrfs_dev_item *dev_item;
399 char super_buf[BTRFS_SUPER_INFO_SIZE];
400 unsigned char dev_uuid[BTRFS_UUID_SIZE];
401 unsigned char fsid[BTRFS_FSID_SIZE];
402 struct btrfs_super_block *super = (struct btrfs_super_block *)super_buf;
405 ret = pread(fd, super_buf, BTRFS_SUPER_INFO_SIZE, cfg->super_bytenr);
406 if (ret < BTRFS_SUPER_INFO_SIZE) {
407 ret = (ret < 0 ? -errno : -EIO);
411 btrfs_set_header_nritems(buf, *slot + 1);
412 (*itemoff) -= sizeof(*dev_item);
413 /* setup device item 1, 0 is for replace case */
414 btrfs_set_disk_key_type(&disk_key, BTRFS_DEV_ITEM_KEY);
415 btrfs_set_disk_key_objectid(&disk_key, BTRFS_DEV_ITEMS_OBJECTID);
416 btrfs_set_disk_key_offset(&disk_key, 1);
417 btrfs_set_item_key(buf, &disk_key, *slot);
418 btrfs_set_item_offset(buf, btrfs_item_nr(*slot), *itemoff);
419 btrfs_set_item_size(buf, btrfs_item_nr(*slot), sizeof(*dev_item));
421 dev_item = btrfs_item_ptr(buf, *slot, struct btrfs_dev_item);
422 /* Generate device uuid */
423 uuid_generate(dev_uuid);
424 write_extent_buffer(buf, dev_uuid,
425 (unsigned long)btrfs_device_uuid(dev_item),
427 uuid_parse(cfg->fs_uuid, fsid);
428 write_extent_buffer(buf, fsid,
429 (unsigned long)btrfs_device_fsid(dev_item),
431 btrfs_set_device_id(buf, dev_item, 1);
432 btrfs_set_device_generation(buf, dev_item, 0);
433 btrfs_set_device_total_bytes(buf, dev_item, cfg->num_bytes);
435 * The number must match the initial SYSTEM and META chunk size
437 btrfs_set_device_bytes_used(buf, dev_item,
438 BTRFS_MKFS_SYSTEM_GROUP_SIZE +
439 BTRFS_CONVERT_META_GROUP_SIZE);
440 btrfs_set_device_io_align(buf, dev_item, cfg->sectorsize);
441 btrfs_set_device_io_width(buf, dev_item, cfg->sectorsize);
442 btrfs_set_device_sector_size(buf, dev_item, cfg->sectorsize);
443 btrfs_set_device_type(buf, dev_item, 0);
445 /* Super dev_item is not complete, copy the complete one to sb */
446 read_extent_buffer(buf, &super->dev_item, (unsigned long)dev_item,
448 ret = write_temp_super(fd, super, cfg->super_bytenr);
454 static int insert_temp_chunk_item(int fd, struct extent_buffer *buf,
455 struct btrfs_mkfs_config *cfg,
456 int *slot, u32 *itemoff, u64 start, u64 len,
459 struct btrfs_chunk *chunk;
460 struct btrfs_disk_key disk_key;
461 char super_buf[BTRFS_SUPER_INFO_SIZE];
462 struct btrfs_super_block *sb = (struct btrfs_super_block *)super_buf;
465 ret = pread(fd, super_buf, BTRFS_SUPER_INFO_SIZE,
467 if (ret < BTRFS_SUPER_INFO_SIZE) {
468 ret = (ret < 0 ? ret : -EIO);
472 btrfs_set_header_nritems(buf, *slot + 1);
473 (*itemoff) -= btrfs_chunk_item_size(1);
474 btrfs_set_disk_key_type(&disk_key, BTRFS_CHUNK_ITEM_KEY);
475 btrfs_set_disk_key_objectid(&disk_key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
476 btrfs_set_disk_key_offset(&disk_key, start);
477 btrfs_set_item_key(buf, &disk_key, *slot);
478 btrfs_set_item_offset(buf, btrfs_item_nr(*slot), *itemoff);
479 btrfs_set_item_size(buf, btrfs_item_nr(*slot),
480 btrfs_chunk_item_size(1));
482 chunk = btrfs_item_ptr(buf, *slot, struct btrfs_chunk);
483 btrfs_set_chunk_length(buf, chunk, len);
484 btrfs_set_chunk_owner(buf, chunk, BTRFS_EXTENT_TREE_OBJECTID);
485 btrfs_set_chunk_stripe_len(buf, chunk, BTRFS_STRIPE_LEN);
486 btrfs_set_chunk_type(buf, chunk, type);
487 btrfs_set_chunk_io_align(buf, chunk, cfg->sectorsize);
488 btrfs_set_chunk_io_width(buf, chunk, cfg->sectorsize);
489 btrfs_set_chunk_sector_size(buf, chunk, cfg->sectorsize);
490 btrfs_set_chunk_num_stripes(buf, chunk, 1);
491 /* TODO: Support DUP profile for system chunk */
492 btrfs_set_stripe_devid_nr(buf, chunk, 0, 1);
493 /* We are doing 1:1 mapping, so start is its dev offset */
494 btrfs_set_stripe_offset_nr(buf, chunk, 0, start);
495 write_extent_buffer(buf, &sb->dev_item.uuid,
496 (unsigned long)btrfs_stripe_dev_uuid_nr(chunk, 0),
501 * If it's system chunk, also copy it to super block.
503 if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
507 cur = (char *)sb->sys_chunk_array
508 + btrfs_super_sys_array_size(sb);
509 memcpy(cur, &disk_key, sizeof(disk_key));
510 cur += sizeof(disk_key);
511 read_extent_buffer(buf, cur, (unsigned long int)chunk,
512 btrfs_chunk_item_size(1));
513 array_size = btrfs_super_sys_array_size(sb);
514 array_size += btrfs_chunk_item_size(1) +
516 btrfs_set_super_sys_array_size(sb, array_size);
518 ret = write_temp_super(fd, sb, cfg->super_bytenr);
523 static int setup_temp_chunk_tree(int fd, struct btrfs_mkfs_config *cfg,
524 u64 sys_chunk_start, u64 meta_chunk_start,
527 struct extent_buffer *buf = NULL;
528 u32 itemoff = __BTRFS_LEAF_DATA_SIZE(cfg->nodesize);
532 /* Must ensure SYS chunk starts before META chunk */
533 if (meta_chunk_start < sys_chunk_start) {
534 error("wrong chunk order: meta < system %llu < %llu",
535 (unsigned long long)meta_chunk_start,
536 (unsigned long long)sys_chunk_start);
539 buf = malloc(sizeof(*buf) + cfg->nodesize);
542 ret = setup_temp_extent_buffer(buf, cfg, chunk_bytenr,
543 BTRFS_CHUNK_TREE_OBJECTID);
547 ret = insert_temp_dev_item(fd, buf, cfg, &slot, &itemoff);
550 ret = insert_temp_chunk_item(fd, buf, cfg, &slot, &itemoff,
552 BTRFS_MKFS_SYSTEM_GROUP_SIZE,
553 BTRFS_BLOCK_GROUP_SYSTEM);
556 ret = insert_temp_chunk_item(fd, buf, cfg, &slot, &itemoff,
558 BTRFS_CONVERT_META_GROUP_SIZE,
559 BTRFS_BLOCK_GROUP_METADATA);
562 ret = write_temp_extent_buffer(fd, buf, chunk_bytenr);
569 static void insert_temp_dev_extent(struct extent_buffer *buf,
570 int *slot, u32 *itemoff, u64 start, u64 len)
572 struct btrfs_dev_extent *dev_extent;
573 struct btrfs_disk_key disk_key;
575 btrfs_set_header_nritems(buf, *slot + 1);
576 (*itemoff) -= sizeof(*dev_extent);
577 btrfs_set_disk_key_type(&disk_key, BTRFS_DEV_EXTENT_KEY);
578 btrfs_set_disk_key_objectid(&disk_key, 1);
579 btrfs_set_disk_key_offset(&disk_key, start);
580 btrfs_set_item_key(buf, &disk_key, *slot);
581 btrfs_set_item_offset(buf, btrfs_item_nr(*slot), *itemoff);
582 btrfs_set_item_size(buf, btrfs_item_nr(*slot), sizeof(*dev_extent));
584 dev_extent = btrfs_item_ptr(buf, *slot, struct btrfs_dev_extent);
585 btrfs_set_dev_extent_chunk_objectid(buf, dev_extent,
586 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
587 btrfs_set_dev_extent_length(buf, dev_extent, len);
588 btrfs_set_dev_extent_chunk_offset(buf, dev_extent, start);
589 btrfs_set_dev_extent_chunk_tree(buf, dev_extent,
590 BTRFS_CHUNK_TREE_OBJECTID);
594 static int setup_temp_dev_tree(int fd, struct btrfs_mkfs_config *cfg,
595 u64 sys_chunk_start, u64 meta_chunk_start,
598 struct extent_buffer *buf = NULL;
599 u32 itemoff = __BTRFS_LEAF_DATA_SIZE(cfg->nodesize);
603 /* Must ensure SYS chunk starts before META chunk */
604 if (meta_chunk_start < sys_chunk_start) {
605 error("wrong chunk order: meta < system %llu < %llu",
606 (unsigned long long)meta_chunk_start,
607 (unsigned long long)sys_chunk_start);
610 buf = malloc(sizeof(*buf) + cfg->nodesize);
613 ret = setup_temp_extent_buffer(buf, cfg, dev_bytenr,
614 BTRFS_DEV_TREE_OBJECTID);
617 insert_temp_dev_extent(buf, &slot, &itemoff, sys_chunk_start,
618 BTRFS_MKFS_SYSTEM_GROUP_SIZE);
619 insert_temp_dev_extent(buf, &slot, &itemoff, meta_chunk_start,
620 BTRFS_CONVERT_META_GROUP_SIZE);
621 ret = write_temp_extent_buffer(fd, buf, dev_bytenr);
627 static int setup_temp_fs_tree(int fd, struct btrfs_mkfs_config *cfg,
630 struct extent_buffer *buf = NULL;
633 buf = malloc(sizeof(*buf) + cfg->nodesize);
636 ret = setup_temp_extent_buffer(buf, cfg, fs_bytenr,
637 BTRFS_FS_TREE_OBJECTID);
641 * Temporary fs tree is completely empty.
643 ret = write_temp_extent_buffer(fd, buf, fs_bytenr);
649 static int setup_temp_csum_tree(int fd, struct btrfs_mkfs_config *cfg,
652 struct extent_buffer *buf = NULL;
655 buf = malloc(sizeof(*buf) + cfg->nodesize);
658 ret = setup_temp_extent_buffer(buf, cfg, csum_bytenr,
659 BTRFS_CSUM_TREE_OBJECTID);
663 * Temporary csum tree is completely empty.
665 ret = write_temp_extent_buffer(fd, buf, csum_bytenr);
672 * Insert one temporary extent item.
674 * NOTE: if skinny_metadata is not enabled, this function must be called
675 * after all other trees are initialized.
676 * Or fs without skinny-metadata will be screwed up.
678 static int insert_temp_extent_item(int fd, struct extent_buffer *buf,
679 struct btrfs_mkfs_config *cfg,
680 int *slot, u32 *itemoff, u64 bytenr,
683 struct extent_buffer *tmp;
684 struct btrfs_extent_item *ei;
685 struct btrfs_extent_inline_ref *iref;
686 struct btrfs_disk_key disk_key;
687 struct btrfs_disk_key tree_info_key;
688 struct btrfs_tree_block_info *info;
690 int skinny_metadata = cfg->features &
691 BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA;
695 itemsize = sizeof(*ei) + sizeof(*iref);
697 itemsize = sizeof(*ei) + sizeof(*iref) +
698 sizeof(struct btrfs_tree_block_info);
700 btrfs_set_header_nritems(buf, *slot + 1);
701 *(itemoff) -= itemsize;
703 if (skinny_metadata) {
704 btrfs_set_disk_key_type(&disk_key, BTRFS_METADATA_ITEM_KEY);
705 btrfs_set_disk_key_offset(&disk_key, 0);
707 btrfs_set_disk_key_type(&disk_key, BTRFS_EXTENT_ITEM_KEY);
708 btrfs_set_disk_key_offset(&disk_key, cfg->nodesize);
710 btrfs_set_disk_key_objectid(&disk_key, bytenr);
712 btrfs_set_item_key(buf, &disk_key, *slot);
713 btrfs_set_item_offset(buf, btrfs_item_nr(*slot), *itemoff);
714 btrfs_set_item_size(buf, btrfs_item_nr(*slot), itemsize);
716 ei = btrfs_item_ptr(buf, *slot, struct btrfs_extent_item);
717 btrfs_set_extent_refs(buf, ei, 1);
718 btrfs_set_extent_generation(buf, ei, 1);
719 btrfs_set_extent_flags(buf, ei, BTRFS_EXTENT_FLAG_TREE_BLOCK);
721 if (skinny_metadata) {
722 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
724 info = (struct btrfs_tree_block_info *)(ei + 1);
725 iref = (struct btrfs_extent_inline_ref *)(info + 1);
727 btrfs_set_extent_inline_ref_type(buf, iref,
728 BTRFS_TREE_BLOCK_REF_KEY);
729 btrfs_set_extent_inline_ref_offset(buf, iref, ref_root);
736 * Lastly, check the tree block key by read the tree block
737 * Since we do 1:1 mapping for convert case, we can directly
738 * read the bytenr from disk
740 tmp = malloc(sizeof(*tmp) + cfg->nodesize);
743 ret = setup_temp_extent_buffer(tmp, cfg, bytenr, ref_root);
746 ret = pread(fd, tmp->data, cfg->nodesize, bytenr);
747 if (ret < cfg->nodesize) {
748 ret = (ret < 0 ? -errno : -EIO);
751 if (btrfs_header_nritems(tmp) == 0) {
752 btrfs_set_disk_key_type(&tree_info_key, 0);
753 btrfs_set_disk_key_objectid(&tree_info_key, 0);
754 btrfs_set_disk_key_offset(&tree_info_key, 0);
756 btrfs_item_key(tmp, &tree_info_key, 0);
758 btrfs_set_tree_block_key(buf, info, &tree_info_key);
765 static void insert_temp_block_group(struct extent_buffer *buf,
766 struct btrfs_mkfs_config *cfg,
767 int *slot, u32 *itemoff,
768 u64 bytenr, u64 len, u64 used, u64 flag)
770 struct btrfs_block_group_item bgi;
771 struct btrfs_disk_key disk_key;
773 btrfs_set_header_nritems(buf, *slot + 1);
774 (*itemoff) -= sizeof(bgi);
775 btrfs_set_disk_key_type(&disk_key, BTRFS_BLOCK_GROUP_ITEM_KEY);
776 btrfs_set_disk_key_objectid(&disk_key, bytenr);
777 btrfs_set_disk_key_offset(&disk_key, len);
778 btrfs_set_item_key(buf, &disk_key, *slot);
779 btrfs_set_item_offset(buf, btrfs_item_nr(*slot), *itemoff);
780 btrfs_set_item_size(buf, btrfs_item_nr(*slot), sizeof(bgi));
782 btrfs_set_block_group_flags(&bgi, flag);
783 btrfs_set_block_group_used(&bgi, used);
784 btrfs_set_block_group_chunk_objectid(&bgi,
785 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
786 write_extent_buffer(buf, &bgi, btrfs_item_ptr_offset(buf, *slot),
791 static int setup_temp_extent_tree(int fd, struct btrfs_mkfs_config *cfg,
792 u64 chunk_bytenr, u64 root_bytenr,
793 u64 extent_bytenr, u64 dev_bytenr,
794 u64 fs_bytenr, u64 csum_bytenr)
796 struct extent_buffer *buf = NULL;
797 u32 itemoff = __BTRFS_LEAF_DATA_SIZE(cfg->nodesize);
802 * We must ensure provided bytenr are in ascending order,
803 * or extent tree key order will be broken.
805 if (!(chunk_bytenr < root_bytenr && root_bytenr < extent_bytenr &&
806 extent_bytenr < dev_bytenr && dev_bytenr < fs_bytenr &&
807 fs_bytenr < csum_bytenr)) {
808 error("bad tree bytenr order: "
809 "chunk < root %llu < %llu, "
810 "root < extent %llu < %llu, "
811 "extent < dev %llu < %llu, "
812 "dev < fs %llu < %llu, "
813 "fs < csum %llu < %llu",
814 (unsigned long long)chunk_bytenr,
815 (unsigned long long)root_bytenr,
816 (unsigned long long)root_bytenr,
817 (unsigned long long)extent_bytenr,
818 (unsigned long long)extent_bytenr,
819 (unsigned long long)dev_bytenr,
820 (unsigned long long)dev_bytenr,
821 (unsigned long long)fs_bytenr,
822 (unsigned long long)fs_bytenr,
823 (unsigned long long)csum_bytenr);
826 buf = malloc(sizeof(*buf) + cfg->nodesize);
830 ret = setup_temp_extent_buffer(buf, cfg, extent_bytenr,
831 BTRFS_EXTENT_TREE_OBJECTID);
835 ret = insert_temp_extent_item(fd, buf, cfg, &slot, &itemoff,
836 chunk_bytenr, BTRFS_CHUNK_TREE_OBJECTID);
840 insert_temp_block_group(buf, cfg, &slot, &itemoff, chunk_bytenr,
841 BTRFS_MKFS_SYSTEM_GROUP_SIZE, cfg->nodesize,
842 BTRFS_BLOCK_GROUP_SYSTEM);
844 ret = insert_temp_extent_item(fd, buf, cfg, &slot, &itemoff,
845 root_bytenr, BTRFS_ROOT_TREE_OBJECTID);
849 /* 5 tree block used, root, extent, dev, fs and csum*/
850 insert_temp_block_group(buf, cfg, &slot, &itemoff, root_bytenr,
851 BTRFS_CONVERT_META_GROUP_SIZE, cfg->nodesize * 5,
852 BTRFS_BLOCK_GROUP_METADATA);
854 ret = insert_temp_extent_item(fd, buf, cfg, &slot, &itemoff,
855 extent_bytenr, BTRFS_EXTENT_TREE_OBJECTID);
858 ret = insert_temp_extent_item(fd, buf, cfg, &slot, &itemoff,
859 dev_bytenr, BTRFS_DEV_TREE_OBJECTID);
862 ret = insert_temp_extent_item(fd, buf, cfg, &slot, &itemoff,
863 fs_bytenr, BTRFS_FS_TREE_OBJECTID);
866 ret = insert_temp_extent_item(fd, buf, cfg, &slot, &itemoff,
867 csum_bytenr, BTRFS_CSUM_TREE_OBJECTID);
871 ret = write_temp_extent_buffer(fd, buf, extent_bytenr);
878 * Improved version of make_btrfs().
881 * 1) Do chunk allocation to avoid used data
882 * And after this function, extent type matches chunk type
883 * 2) Better structured code
884 * No super long hand written codes to initialized all tree blocks
885 * Split into small blocks and reuse codes.
886 * TODO: Reuse tree operation facilities by introducing new flags
888 int make_convert_btrfs(int fd, struct btrfs_mkfs_config *cfg,
889 struct btrfs_convert_context *cctx)
891 struct cache_tree *free = &cctx->free;
892 struct cache_tree *used = &cctx->used;
894 u64 meta_chunk_start;
895 /* chunk tree bytenr, in system chunk */
897 /* metadata trees bytenr, in metadata chunk */
905 /* Shouldn't happen */
906 BUG_ON(cache_tree_empty(used));
909 * reserve space for temporary superblock first
910 * Here we allocate a little larger space, to keep later
911 * free space will be STRIPE_LEN aligned
913 ret = reserve_free_space(free, BTRFS_STRIPE_LEN,
919 * Then reserve system chunk space
920 * TODO: Change system group size depending on cctx->total_bytes.
921 * If using current 4M, it can only handle less than one TB for
922 * worst case and then run out of sys space.
924 ret = reserve_free_space(free, BTRFS_MKFS_SYSTEM_GROUP_SIZE,
928 ret = reserve_free_space(free, BTRFS_CONVERT_META_GROUP_SIZE,
934 * Allocated meta/sys chunks will be mapped 1:1 with device offset.
936 * Inside the allocated metadata chunk, the layout will be:
937 * | offset | contents |
938 * -------------------------------------
940 * | +nodesize | extent root |
941 * | +nodesize * 2 | device root |
942 * | +nodesize * 3 | fs tree |
943 * | +nodesize * 4 | csum tree |
944 * -------------------------------------
945 * Inside the allocated system chunk, the layout will be:
946 * | offset | contents |
947 * -------------------------------------
948 * | +0 | chunk root |
949 * -------------------------------------
951 chunk_bytenr = sys_chunk_start;
952 root_bytenr = meta_chunk_start;
953 extent_bytenr = meta_chunk_start + cfg->nodesize;
954 dev_bytenr = meta_chunk_start + cfg->nodesize * 2;
955 fs_bytenr = meta_chunk_start + cfg->nodesize * 3;
956 csum_bytenr = meta_chunk_start + cfg->nodesize * 4;
958 ret = setup_temp_super(fd, cfg, root_bytenr, chunk_bytenr);
962 ret = setup_temp_root_tree(fd, cfg, root_bytenr, extent_bytenr,
963 dev_bytenr, fs_bytenr, csum_bytenr);
966 ret = setup_temp_chunk_tree(fd, cfg, sys_chunk_start, meta_chunk_start,
970 ret = setup_temp_dev_tree(fd, cfg, sys_chunk_start, meta_chunk_start,
974 ret = setup_temp_fs_tree(fd, cfg, fs_bytenr);
977 ret = setup_temp_csum_tree(fd, cfg, csum_bytenr);
981 * Setup extent tree last, since it may need to read tree block key
982 * for non-skinny metadata case.
984 ret = setup_temp_extent_tree(fd, cfg, chunk_bytenr, root_bytenr,
985 extent_bytenr, dev_bytenr, fs_bytenr,
991 #define VERSION_TO_STRING3(a,b,c) #a "." #b "." #c, KERNEL_VERSION(a,b,c)
992 #define VERSION_TO_STRING2(a,b) #a "." #b, KERNEL_VERSION(a,b,0)
995 * Feature stability status and versions: compat <= safe <= default
997 static const struct btrfs_fs_feature {
1000 const char *sysfs_name;
1002 * Compatibility with kernel of given version. Filesystem can be
1005 const char *compat_str;
1008 * Considered safe for use, but is not on by default, even if the
1009 * kernel supports the feature.
1011 const char *safe_str;
1014 * Considered safe for use and will be turned on by default if
1015 * supported by the running kernel.
1017 const char *default_str;
1020 } mkfs_features[] = {
1021 { "mixed-bg", BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS,
1023 VERSION_TO_STRING3(2,6,37),
1024 VERSION_TO_STRING3(2,6,37),
1026 "mixed data and metadata block groups" },
1027 { "extref", BTRFS_FEATURE_INCOMPAT_EXTENDED_IREF,
1029 VERSION_TO_STRING2(3,7),
1030 VERSION_TO_STRING2(3,12),
1031 VERSION_TO_STRING2(3,12),
1032 "increased hardlink limit per file to 65536" },
1033 { "raid56", BTRFS_FEATURE_INCOMPAT_RAID56,
1035 VERSION_TO_STRING2(3,9),
1038 "raid56 extended format" },
1039 { "skinny-metadata", BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA,
1041 VERSION_TO_STRING2(3,10),
1042 VERSION_TO_STRING2(3,18),
1043 VERSION_TO_STRING2(3,18),
1044 "reduced-size metadata extent refs" },
1045 { "no-holes", BTRFS_FEATURE_INCOMPAT_NO_HOLES,
1047 VERSION_TO_STRING2(3,14),
1048 VERSION_TO_STRING2(4,0),
1050 "no explicit hole extents for files" },
1051 /* Keep this one last */
1052 { "list-all", BTRFS_FEATURE_LIST_ALL, NULL }
1055 static int parse_one_fs_feature(const char *name, u64 *flags)
1060 for (i = 0; i < ARRAY_SIZE(mkfs_features); i++) {
1061 if (name[0] == '^' &&
1062 !strcmp(mkfs_features[i].name, name + 1)) {
1063 *flags &= ~ mkfs_features[i].flag;
1065 } else if (!strcmp(mkfs_features[i].name, name)) {
1066 *flags |= mkfs_features[i].flag;
1074 void btrfs_parse_features_to_string(char *buf, u64 flags)
1080 for (i = 0; i < ARRAY_SIZE(mkfs_features); i++) {
1081 if (flags & mkfs_features[i].flag) {
1084 strcat(buf, mkfs_features[i].name);
1089 void btrfs_process_fs_features(u64 flags)
1093 for (i = 0; i < ARRAY_SIZE(mkfs_features); i++) {
1094 if (flags & mkfs_features[i].flag) {
1095 printf("Turning ON incompat feature '%s': %s\n",
1096 mkfs_features[i].name,
1097 mkfs_features[i].desc);
1102 void btrfs_list_all_fs_features(u64 mask_disallowed)
1106 fprintf(stderr, "Filesystem features available:\n");
1107 for (i = 0; i < ARRAY_SIZE(mkfs_features) - 1; i++) {
1108 const struct btrfs_fs_feature *feat = &mkfs_features[i];
1110 if (feat->flag & mask_disallowed)
1112 fprintf(stderr, "%-20s- %s (0x%llx", feat->name, feat->desc,
1114 if (feat->compat_ver)
1115 fprintf(stderr, ", compat=%s", feat->compat_str);
1117 fprintf(stderr, ", safe=%s", feat->safe_str);
1118 if (feat->default_ver)
1119 fprintf(stderr, ", default=%s", feat->default_str);
1120 fprintf(stderr, ")\n");
1125 * Return NULL if all features were parsed fine, otherwise return the name of
1126 * the first unparsed.
1128 char* btrfs_parse_fs_features(char *namelist, u64 *flags)
1131 char *save_ptr = NULL; /* Satisfy static checkers */
1133 for (this_char = strtok_r(namelist, ",", &save_ptr);
1135 this_char = strtok_r(NULL, ",", &save_ptr)) {
1136 if (parse_one_fs_feature(this_char, flags))
1143 void print_kernel_version(FILE *stream, u32 version)
1147 v[0] = version & 0xFF;
1148 v[1] = (version >> 8) & 0xFF;
1149 v[2] = version >> 16;
1150 fprintf(stream, "%u.%u", v[2], v[1]);
1152 fprintf(stream, ".%u", v[0]);
1155 u32 get_running_kernel_version(void)
1157 struct utsname utsbuf;
1159 char *saveptr = NULL;
1163 if (strcmp(utsbuf.sysname, "Linux") != 0) {
1164 error("unsupported system: %s", utsbuf.sysname);
1168 tmp = strchr(utsbuf.release, '-');
1172 tmp = strtok_r(utsbuf.release, ".", &saveptr);
1173 if (!string_is_numerical(tmp))
1175 version = atoi(tmp) << 16;
1176 tmp = strtok_r(NULL, ".", &saveptr);
1177 if (!string_is_numerical(tmp))
1179 version |= atoi(tmp) << 8;
1180 tmp = strtok_r(NULL, ".", &saveptr);
1182 if (!string_is_numerical(tmp))
1184 version |= atoi(tmp);
1190 u64 btrfs_device_size(int fd, struct stat *st)
1193 if (S_ISREG(st->st_mode)) {
1196 if (!S_ISBLK(st->st_mode)) {
1199 if (ioctl(fd, BLKGETSIZE64, &size) >= 0) {
1205 static int zero_blocks(int fd, off_t start, size_t len)
1207 char *buf = malloc(len);
1213 memset(buf, 0, len);
1214 written = pwrite(fd, buf, len, start);
1221 #define ZERO_DEV_BYTES SZ_2M
1223 /* don't write outside the device by clamping the region to the device size */
1224 static int zero_dev_clamped(int fd, off_t start, ssize_t len, u64 dev_size)
1226 off_t end = max(start, start + len);
1229 /* and don't overwrite the disk labels on sparc */
1230 start = max(start, 1024);
1231 end = max(end, 1024);
1234 start = min_t(u64, start, dev_size);
1235 end = min_t(u64, end, dev_size);
1237 return zero_blocks(fd, start, end - start);
1240 int btrfs_add_to_fsid(struct btrfs_trans_handle *trans,
1241 struct btrfs_root *root, int fd, const char *path,
1242 u64 device_total_bytes, u32 io_width, u32 io_align,
1245 struct btrfs_super_block *disk_super;
1246 struct btrfs_super_block *super = root->fs_info->super_copy;
1247 struct btrfs_device *device;
1248 struct btrfs_dev_item *dev_item;
1254 device_total_bytes = (device_total_bytes / sectorsize) * sectorsize;
1256 device = calloc(1, sizeof(*device));
1261 buf = calloc(1, sectorsize);
1267 disk_super = (struct btrfs_super_block *)buf;
1268 dev_item = &disk_super->dev_item;
1270 uuid_generate(device->uuid);
1273 device->io_width = io_width;
1274 device->io_align = io_align;
1275 device->sector_size = sectorsize;
1277 device->writeable = 1;
1278 device->total_bytes = device_total_bytes;
1279 device->bytes_used = 0;
1280 device->total_ios = 0;
1281 device->dev_root = root->fs_info->dev_root;
1282 device->name = strdup(path);
1283 if (!device->name) {
1288 INIT_LIST_HEAD(&device->dev_list);
1289 ret = btrfs_add_device(trans, root, device);
1293 fs_total_bytes = btrfs_super_total_bytes(super) + device_total_bytes;
1294 btrfs_set_super_total_bytes(super, fs_total_bytes);
1296 num_devs = btrfs_super_num_devices(super) + 1;
1297 btrfs_set_super_num_devices(super, num_devs);
1299 memcpy(disk_super, super, sizeof(*disk_super));
1301 btrfs_set_super_bytenr(disk_super, BTRFS_SUPER_INFO_OFFSET);
1302 btrfs_set_stack_device_id(dev_item, device->devid);
1303 btrfs_set_stack_device_type(dev_item, device->type);
1304 btrfs_set_stack_device_io_align(dev_item, device->io_align);
1305 btrfs_set_stack_device_io_width(dev_item, device->io_width);
1306 btrfs_set_stack_device_sector_size(dev_item, device->sector_size);
1307 btrfs_set_stack_device_total_bytes(dev_item, device->total_bytes);
1308 btrfs_set_stack_device_bytes_used(dev_item, device->bytes_used);
1309 memcpy(&dev_item->uuid, device->uuid, BTRFS_UUID_SIZE);
1311 ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
1312 BUG_ON(ret != sectorsize);
1315 list_add(&device->dev_list, &root->fs_info->fs_devices->devices);
1316 device->fs_devices = root->fs_info->fs_devices;
1325 static int btrfs_wipe_existing_sb(int fd)
1327 const char *off = NULL;
1332 blkid_probe pr = NULL;
1334 pr = blkid_new_probe();
1338 if (blkid_probe_set_device(pr, fd, 0, 0)) {
1343 ret = blkid_probe_lookup_value(pr, "SBMAGIC_OFFSET", &off, NULL);
1345 ret = blkid_probe_lookup_value(pr, "SBMAGIC", NULL, &len);
1347 if (ret || len == 0 || off == NULL) {
1349 * If lookup fails, the probe did not find any values, eg. for
1350 * a file image or a loop device. Soft error.
1356 offset = strtoll(off, NULL, 10);
1357 if (len > sizeof(buf))
1360 memset(buf, 0, len);
1361 ret = pwrite(fd, buf, len, offset);
1363 error("cannot wipe existing superblock: %s", strerror(errno));
1365 } else if (ret != len) {
1366 error("cannot wipe existing superblock: wrote %d of %zd", ret, len);
1372 blkid_free_probe(pr);
1376 int btrfs_prepare_device(int fd, const char *file, u64 *block_count_ret,
1377 u64 max_block_count, unsigned opflags)
1383 ret = fstat(fd, &st);
1385 error("unable to stat %s: %s", file, strerror(errno));
1389 block_count = btrfs_device_size(fd, &st);
1390 if (block_count == 0) {
1391 error("unable to determine size of %s", file);
1394 if (max_block_count)
1395 block_count = min(block_count, max_block_count);
1397 if (opflags & PREP_DEVICE_DISCARD) {
1399 * We intentionally ignore errors from the discard ioctl. It
1400 * is not necessary for the mkfs functionality but just an
1403 if (discard_range(fd, 0, 0) == 0) {
1404 if (opflags & PREP_DEVICE_VERBOSE)
1405 printf("Performing full device TRIM %s (%s) ...\n",
1406 file, pretty_size(block_count));
1407 discard_blocks(fd, 0, block_count);
1411 ret = zero_dev_clamped(fd, 0, ZERO_DEV_BYTES, block_count);
1412 for (i = 0 ; !ret && i < BTRFS_SUPER_MIRROR_MAX; i++)
1413 ret = zero_dev_clamped(fd, btrfs_sb_offset(i),
1414 BTRFS_SUPER_INFO_SIZE, block_count);
1415 if (!ret && (opflags & PREP_DEVICE_ZERO_END))
1416 ret = zero_dev_clamped(fd, block_count - ZERO_DEV_BYTES,
1417 ZERO_DEV_BYTES, block_count);
1420 error("failed to zero device '%s': %s", file, strerror(-ret));
1424 ret = btrfs_wipe_existing_sb(fd);
1426 error("cannot wipe superblocks on %s", file);
1430 *block_count_ret = block_count;
1434 int btrfs_make_root_dir(struct btrfs_trans_handle *trans,
1435 struct btrfs_root *root, u64 objectid)
1438 struct btrfs_inode_item inode_item;
1439 time_t now = time(NULL);
1441 memset(&inode_item, 0, sizeof(inode_item));
1442 btrfs_set_stack_inode_generation(&inode_item, trans->transid);
1443 btrfs_set_stack_inode_size(&inode_item, 0);
1444 btrfs_set_stack_inode_nlink(&inode_item, 1);
1445 btrfs_set_stack_inode_nbytes(&inode_item, root->nodesize);
1446 btrfs_set_stack_inode_mode(&inode_item, S_IFDIR | 0755);
1447 btrfs_set_stack_timespec_sec(&inode_item.atime, now);
1448 btrfs_set_stack_timespec_nsec(&inode_item.atime, 0);
1449 btrfs_set_stack_timespec_sec(&inode_item.ctime, now);
1450 btrfs_set_stack_timespec_nsec(&inode_item.ctime, 0);
1451 btrfs_set_stack_timespec_sec(&inode_item.mtime, now);
1452 btrfs_set_stack_timespec_nsec(&inode_item.mtime, 0);
1453 btrfs_set_stack_timespec_sec(&inode_item.otime, now);
1454 btrfs_set_stack_timespec_nsec(&inode_item.otime, 0);
1456 if (root->fs_info->tree_root == root)
1457 btrfs_set_super_root_dir(root->fs_info->super_copy, objectid);
1459 ret = btrfs_insert_inode(trans, root, objectid, &inode_item);
1463 ret = btrfs_insert_inode_ref(trans, root, "..", 2, objectid, objectid, 0);
1467 btrfs_set_root_dirid(&root->root_item, objectid);
1474 * checks if a path is a block device node
1475 * Returns negative errno on failure, otherwise
1476 * returns 1 for blockdev, 0 for not-blockdev
1478 int is_block_device(const char *path)
1480 struct stat statbuf;
1482 if (stat(path, &statbuf) < 0)
1485 return !!S_ISBLK(statbuf.st_mode);
1489 * check if given path is a mount point
1490 * return 1 if yes. 0 if no. -1 for error
1492 int is_mount_point(const char *path)
1498 f = setmntent("/proc/self/mounts", "r");
1502 while ((mnt = getmntent(f)) != NULL) {
1503 if (strcmp(mnt->mnt_dir, path))
1512 static int is_reg_file(const char *path)
1514 struct stat statbuf;
1516 if (stat(path, &statbuf) < 0)
1518 return S_ISREG(statbuf.st_mode);
1522 * This function checks if the given input parameter is
1524 * return <0 : some error in the given input
1525 * return BTRFS_ARG_UNKNOWN: unknown input
1526 * return BTRFS_ARG_UUID: given input is uuid
1527 * return BTRFS_ARG_MNTPOINT: given input is path
1528 * return BTRFS_ARG_REG: given input is regular file
1529 * return BTRFS_ARG_BLKDEV: given input is block device
1531 int check_arg_type(const char *input)
1534 char path[PATH_MAX];
1539 if (realpath(input, path)) {
1540 if (is_block_device(path) == 1)
1541 return BTRFS_ARG_BLKDEV;
1543 if (is_mount_point(path) == 1)
1544 return BTRFS_ARG_MNTPOINT;
1546 if (is_reg_file(path))
1547 return BTRFS_ARG_REG;
1549 return BTRFS_ARG_UNKNOWN;
1552 if (strlen(input) == (BTRFS_UUID_UNPARSED_SIZE - 1) &&
1553 !uuid_parse(input, uuid))
1554 return BTRFS_ARG_UUID;
1556 return BTRFS_ARG_UNKNOWN;
1560 * Find the mount point for a mounted device.
1561 * On success, returns 0 with mountpoint in *mp.
1562 * On failure, returns -errno (not mounted yields -EINVAL)
1563 * Is noisy on failures, expects to be given a mounted device.
1565 int get_btrfs_mount(const char *dev, char *mp, size_t mp_size)
1570 ret = is_block_device(dev);
1573 error("not a block device: %s", dev);
1576 error("cannot check %s: %s", dev, strerror(-ret));
1581 fd = open(dev, O_RDONLY);
1584 error("cannot open %s: %s", dev, strerror(errno));
1588 ret = check_mounted_where(fd, dev, mp, mp_size, NULL);
1591 } else { /* mounted, all good */
1601 * Given a pathname, return a filehandle to:
1602 * the original pathname or,
1603 * if the pathname is a mounted btrfs device, to its mountpoint.
1605 * On error, return -1, errno should be set.
1607 int open_path_or_dev_mnt(const char *path, DIR **dirstream, int verbose)
1612 if (is_block_device(path)) {
1613 ret = get_btrfs_mount(path, mp, sizeof(mp));
1615 /* not a mounted btrfs dev */
1616 error_on(verbose, "'%s' is not a mounted btrfs device",
1621 ret = open_file_or_dir(mp, dirstream);
1622 error_on(verbose && ret < 0, "can't access '%s': %s",
1623 path, strerror(errno));
1625 ret = btrfs_open_dir(path, dirstream, 1);
1632 * Do the following checks before calling open_file_or_dir():
1633 * 1: path is in a btrfs filesystem
1634 * 2: path is a directory
1636 int btrfs_open_dir(const char *path, DIR **dirstream, int verbose)
1642 if (statfs(path, &stfs) != 0) {
1643 error_on(verbose, "cannot access '%s': %s", path,
1648 if (stfs.f_type != BTRFS_SUPER_MAGIC) {
1649 error_on(verbose, "not a btrfs filesystem: %s", path);
1653 if (stat(path, &st) != 0) {
1654 error_on(verbose, "cannot access '%s': %s", path,
1659 if (!S_ISDIR(st.st_mode)) {
1660 error_on(verbose, "not a directory: %s", path);
1664 ret = open_file_or_dir(path, dirstream);
1666 error_on(verbose, "cannot access '%s': %s", path,
1673 /* checks if a device is a loop device */
1674 static int is_loop_device (const char* device) {
1675 struct stat statbuf;
1677 if(stat(device, &statbuf) < 0)
1680 return (S_ISBLK(statbuf.st_mode) &&
1681 MAJOR(statbuf.st_rdev) == LOOP_MAJOR);
1685 * Takes a loop device path (e.g. /dev/loop0) and returns
1686 * the associated file (e.g. /images/my_btrfs.img) using
1689 static int resolve_loop_device_with_loopdev(const char* loop_dev, char* loop_file)
1693 struct loop_info64 lo64;
1695 fd = open(loop_dev, O_RDONLY | O_NONBLOCK);
1698 ret = ioctl(fd, LOOP_GET_STATUS64, &lo64);
1704 memcpy(loop_file, lo64.lo_file_name, sizeof(lo64.lo_file_name));
1705 loop_file[sizeof(lo64.lo_file_name)] = 0;
1713 /* Takes a loop device path (e.g. /dev/loop0) and returns
1714 * the associated file (e.g. /images/my_btrfs.img) */
1715 static int resolve_loop_device(const char* loop_dev, char* loop_file,
1722 char real_loop_dev[PATH_MAX];
1724 if (!realpath(loop_dev, real_loop_dev))
1726 snprintf(p, PATH_MAX, "/sys/block/%s/loop/backing_file", strrchr(real_loop_dev, '/'));
1727 if (!(f = fopen(p, "r"))) {
1728 if (errno == ENOENT)
1730 * It's possibly a partitioned loop device, which is
1731 * resolvable with loopdev API.
1733 return resolve_loop_device_with_loopdev(loop_dev, loop_file);
1737 snprintf(fmt, 20, "%%%i[^\n]", max_len-1);
1738 ret = fscanf(f, fmt, loop_file);
1747 * Checks whether a and b are identical or device
1748 * files associated with the same block device
1750 static int is_same_blk_file(const char* a, const char* b)
1752 struct stat st_buf_a, st_buf_b;
1753 char real_a[PATH_MAX];
1754 char real_b[PATH_MAX];
1756 if (!realpath(a, real_a))
1757 strncpy_null(real_a, a);
1759 if (!realpath(b, real_b))
1760 strncpy_null(real_b, b);
1762 /* Identical path? */
1763 if (strcmp(real_a, real_b) == 0)
1766 if (stat(a, &st_buf_a) < 0 || stat(b, &st_buf_b) < 0) {
1767 if (errno == ENOENT)
1772 /* Same blockdevice? */
1773 if (S_ISBLK(st_buf_a.st_mode) && S_ISBLK(st_buf_b.st_mode) &&
1774 st_buf_a.st_rdev == st_buf_b.st_rdev) {
1779 if (st_buf_a.st_dev == st_buf_b.st_dev &&
1780 st_buf_a.st_ino == st_buf_b.st_ino) {
1787 /* checks if a and b are identical or device
1788 * files associated with the same block device or
1789 * if one file is a loop device that uses the other
1792 static int is_same_loop_file(const char* a, const char* b)
1794 char res_a[PATH_MAX];
1795 char res_b[PATH_MAX];
1796 const char* final_a = NULL;
1797 const char* final_b = NULL;
1800 /* Resolve a if it is a loop device */
1801 if((ret = is_loop_device(a)) < 0) {
1806 ret = resolve_loop_device(a, res_a, sizeof(res_a));
1817 /* Resolve b if it is a loop device */
1818 if ((ret = is_loop_device(b)) < 0) {
1823 ret = resolve_loop_device(b, res_b, sizeof(res_b));
1834 return is_same_blk_file(final_a, final_b);
1837 /* Checks if a file exists and is a block or regular file*/
1838 static int is_existing_blk_or_reg_file(const char* filename)
1842 if(stat(filename, &st_buf) < 0) {
1849 return (S_ISBLK(st_buf.st_mode) || S_ISREG(st_buf.st_mode));
1852 /* Checks if a file is used (directly or indirectly via a loop device)
1853 * by a device in fs_devices
1855 static int blk_file_in_dev_list(struct btrfs_fs_devices* fs_devices,
1859 struct list_head *head;
1860 struct list_head *cur;
1861 struct btrfs_device *device;
1863 head = &fs_devices->devices;
1864 list_for_each(cur, head) {
1865 device = list_entry(cur, struct btrfs_device, dev_list);
1867 if((ret = is_same_loop_file(device->name, file)))
1875 * Resolve a pathname to a device mapper node to /dev/mapper/<name>
1876 * Returns NULL on invalid input or malloc failure; Other failures
1877 * will be handled by the caller using the input pathame.
1879 char *canonicalize_dm_name(const char *ptname)
1883 char path[PATH_MAX], name[PATH_MAX], *res = NULL;
1885 if (!ptname || !*ptname)
1888 snprintf(path, sizeof(path), "/sys/block/%s/dm/name", ptname);
1889 if (!(f = fopen(path, "r")))
1892 /* read <name>\n from sysfs */
1893 if (fgets(name, sizeof(name), f) && (sz = strlen(name)) > 1) {
1894 name[sz - 1] = '\0';
1895 snprintf(path, sizeof(path), "/dev/mapper/%s", name);
1897 if (access(path, F_OK) == 0)
1905 * Resolve a pathname to a canonical device node, e.g. /dev/sda1 or
1906 * to a device mapper pathname.
1907 * Returns NULL on invalid input or malloc failure; Other failures
1908 * will be handled by the caller using the input pathame.
1910 char *canonicalize_path(const char *path)
1912 char *canonical, *p;
1914 if (!path || !*path)
1917 canonical = realpath(path, NULL);
1919 return strdup(path);
1920 p = strrchr(canonical, '/');
1921 if (p && strncmp(p, "/dm-", 4) == 0 && isdigit(*(p + 4))) {
1922 char *dm = canonicalize_dm_name(p + 1);
1933 * returns 1 if the device was mounted, < 0 on error or 0 if everything
1934 * is safe to continue.
1936 int check_mounted(const char* file)
1941 fd = open(file, O_RDONLY);
1943 error("mount check: cannot open %s: %s", file,
1948 ret = check_mounted_where(fd, file, NULL, 0, NULL);
1954 int check_mounted_where(int fd, const char *file, char *where, int size,
1955 struct btrfs_fs_devices **fs_dev_ret)
1960 struct btrfs_fs_devices *fs_devices_mnt = NULL;
1964 /* scan the initial device */
1965 ret = btrfs_scan_one_device(fd, file, &fs_devices_mnt,
1966 &total_devs, BTRFS_SUPER_INFO_OFFSET, SBREAD_DEFAULT);
1967 is_btrfs = (ret >= 0);
1969 /* scan other devices */
1970 if (is_btrfs && total_devs > 1) {
1971 ret = btrfs_scan_devices();
1976 /* iterate over the list of currently mounted filesystems */
1977 if ((f = setmntent ("/proc/self/mounts", "r")) == NULL)
1980 while ((mnt = getmntent (f)) != NULL) {
1982 if(strcmp(mnt->mnt_type, "btrfs") != 0)
1985 ret = blk_file_in_dev_list(fs_devices_mnt, mnt->mnt_fsname);
1987 /* ignore entries in the mount table that are not
1988 associated with a file*/
1989 if((ret = is_existing_blk_or_reg_file(mnt->mnt_fsname)) < 0)
1990 goto out_mntloop_err;
1994 ret = is_same_loop_file(file, mnt->mnt_fsname);
1998 goto out_mntloop_err;
2003 /* Did we find an entry in mnt table? */
2004 if (mnt && size && where) {
2005 strncpy(where, mnt->mnt_dir, size);
2009 *fs_dev_ret = fs_devices_mnt;
2011 ret = (mnt != NULL);
2019 struct pending_dir {
2020 struct list_head list;
2021 char name[PATH_MAX];
2024 int btrfs_register_one_device(const char *fname)
2026 struct btrfs_ioctl_vol_args args;
2030 fd = open("/dev/btrfs-control", O_RDWR);
2033 "failed to open /dev/btrfs-control, skipping device registration: %s",
2037 memset(&args, 0, sizeof(args));
2038 strncpy_null(args.name, fname);
2039 ret = ioctl(fd, BTRFS_IOC_SCAN_DEV, &args);
2041 error("device scan failed on '%s': %s", fname,
2050 * Register all devices in the fs_uuid list created in the user
2051 * space. Ensure btrfs_scan_devices() is called before this func.
2053 int btrfs_register_all_devices(void)
2057 struct btrfs_fs_devices *fs_devices;
2058 struct btrfs_device *device;
2059 struct list_head *all_uuids;
2061 all_uuids = btrfs_scanned_uuids();
2063 list_for_each_entry(fs_devices, all_uuids, list) {
2064 list_for_each_entry(device, &fs_devices->devices, dev_list) {
2066 err = btrfs_register_one_device(device->name);
2076 int btrfs_device_already_in_root(struct btrfs_root *root, int fd,
2079 struct btrfs_super_block *disk_super;
2083 buf = malloc(BTRFS_SUPER_INFO_SIZE);
2088 ret = pread(fd, buf, BTRFS_SUPER_INFO_SIZE, super_offset);
2089 if (ret != BTRFS_SUPER_INFO_SIZE)
2093 disk_super = (struct btrfs_super_block *)buf;
2095 * Accept devices from the same filesystem, allow partially created
2098 if (btrfs_super_magic(disk_super) != BTRFS_MAGIC &&
2099 btrfs_super_magic(disk_super) != BTRFS_MAGIC_PARTIAL)
2102 if (!memcmp(disk_super->fsid, root->fs_info->super_copy->fsid,
2112 * Note: this function uses a static per-thread buffer. Do not call this
2113 * function more than 10 times within one argument list!
2115 const char *pretty_size_mode(u64 size, unsigned mode)
2117 static __thread int ps_index = 0;
2118 static __thread char ps_array[10][32];
2121 ret = ps_array[ps_index];
2124 (void)pretty_size_snprintf(size, ret, 32, mode);
2129 static const char* unit_suffix_binary[] =
2130 { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"};
2131 static const char* unit_suffix_decimal[] =
2132 { "B", "kB", "MB", "GB", "TB", "PB", "EB"};
2134 int pretty_size_snprintf(u64 size, char *str, size_t str_size, unsigned unit_mode)
2140 const char** suffix = NULL;
2147 negative = !!(unit_mode & UNITS_NEGATIVE);
2148 unit_mode &= ~UNITS_NEGATIVE;
2150 if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_RAW) {
2152 snprintf(str, str_size, "%lld", size);
2154 snprintf(str, str_size, "%llu", size);
2158 if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_BINARY) {
2161 suffix = unit_suffix_binary;
2162 } else if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_DECIMAL) {
2165 suffix = unit_suffix_decimal;
2170 fprintf(stderr, "INTERNAL ERROR: unknown unit base, mode %d\n",
2178 switch (unit_mode & UNITS_MODE_MASK) {
2179 case UNITS_TBYTES: base *= mult; num_divs++;
2180 case UNITS_GBYTES: base *= mult; num_divs++;
2181 case UNITS_MBYTES: base *= mult; num_divs++;
2182 case UNITS_KBYTES: num_divs++;
2190 s64 ssize = (s64)size;
2191 s64 last_ssize = ssize;
2193 while ((ssize < 0 ? -ssize : ssize) >= mult) {
2198 last_size = (u64)last_ssize;
2200 while (size >= mult) {
2207 * If the value is smaller than base, we didn't do any
2208 * division, in that case, base should be 1, not original
2209 * base, or the unit will be wrong
2215 if (num_divs >= ARRAY_SIZE(unit_suffix_binary)) {
2217 printf("INTERNAL ERROR: unsupported unit suffix, index %d\n",
2224 fraction = (float)(s64)last_size / base;
2226 fraction = (float)last_size / base;
2229 return snprintf(str, str_size, "%.2f%s", fraction, suffix[num_divs]);
2233 * __strncpy_null - strncpy with null termination
2234 * @dest: the target array
2235 * @src: the source string
2236 * @n: maximum bytes to copy (size of *dest)
2238 * Like strncpy, but ensures destination is null-terminated.
2240 * Copies the string pointed to by src, including the terminating null
2241 * byte ('\0'), to the buffer pointed to by dest, up to a maximum
2242 * of n bytes. Then ensure that dest is null-terminated.
2244 char *__strncpy_null(char *dest, const char *src, size_t n)
2246 strncpy(dest, src, n);
2253 * Checks to make sure that the label matches our requirements.
2255 0 if everything is safe and usable
2256 -1 if the label is too long
2258 static int check_label(const char *input)
2260 int len = strlen(input);
2262 if (len > BTRFS_LABEL_SIZE - 1) {
2263 error("label %s is too long (max %d)", input,
2264 BTRFS_LABEL_SIZE - 1);
2271 static int set_label_unmounted(const char *dev, const char *label)
2273 struct btrfs_trans_handle *trans;
2274 struct btrfs_root *root;
2277 ret = check_mounted(dev);
2279 error("checking mount status of %s failed: %d", dev, ret);
2283 error("device %s is mounted, use mount point", dev);
2287 /* Open the super_block at the default location
2288 * and as read-write.
2290 root = open_ctree(dev, 0, OPEN_CTREE_WRITES);
2291 if (!root) /* errors are printed by open_ctree() */
2294 trans = btrfs_start_transaction(root, 1);
2295 __strncpy_null(root->fs_info->super_copy->label, label, BTRFS_LABEL_SIZE - 1);
2297 btrfs_commit_transaction(trans, root);
2299 /* Now we close it since we are done. */
2304 static int set_label_mounted(const char *mount_path, const char *labelp)
2307 char label[BTRFS_LABEL_SIZE];
2309 fd = open(mount_path, O_RDONLY | O_NOATIME);
2311 error("unable to access %s: %s", mount_path, strerror(errno));
2315 memset(label, 0, sizeof(label));
2316 __strncpy_null(label, labelp, BTRFS_LABEL_SIZE - 1);
2317 if (ioctl(fd, BTRFS_IOC_SET_FSLABEL, label) < 0) {
2318 error("unable to set label of %s: %s", mount_path,
2328 int get_label_unmounted(const char *dev, char *label)
2330 struct btrfs_root *root;
2333 ret = check_mounted(dev);
2335 error("checking mount status of %s failed: %d", dev, ret);
2339 /* Open the super_block at the default location
2342 root = open_ctree(dev, 0, 0);
2346 __strncpy_null(label, root->fs_info->super_copy->label,
2347 BTRFS_LABEL_SIZE - 1);
2349 /* Now we close it since we are done. */
2355 * If a partition is mounted, try to get the filesystem label via its
2356 * mounted path rather than device. Return the corresponding error
2357 * the user specified the device path.
2359 int get_label_mounted(const char *mount_path, char *labelp)
2361 char label[BTRFS_LABEL_SIZE];
2365 fd = open(mount_path, O_RDONLY | O_NOATIME);
2367 error("unable to access %s: %s", mount_path, strerror(errno));
2371 memset(label, '\0', sizeof(label));
2372 ret = ioctl(fd, BTRFS_IOC_GET_FSLABEL, label);
2374 if (errno != ENOTTY)
2375 error("unable to get label of %s: %s", mount_path,
2382 __strncpy_null(labelp, label, BTRFS_LABEL_SIZE - 1);
2387 int get_label(const char *btrfs_dev, char *label)
2391 ret = is_existing_blk_or_reg_file(btrfs_dev);
2393 ret = get_label_mounted(btrfs_dev, label);
2395 ret = get_label_unmounted(btrfs_dev, label);
2400 int set_label(const char *btrfs_dev, const char *label)
2404 if (check_label(label))
2407 ret = is_existing_blk_or_reg_file(btrfs_dev);
2409 ret = set_label_mounted(btrfs_dev, label);
2411 ret = set_label_unmounted(btrfs_dev, label);
2417 * A not-so-good version fls64. No fascinating optimization since
2418 * no one except parse_size use it
2420 static int fls64(u64 x)
2424 for (i = 0; i <64; i++)
2425 if (x << i & (1ULL << 63))
2430 u64 parse_size(char *s)
2438 error("size value is empty");
2442 error("size value '%s' is less equal than 0", s);
2445 ret = strtoull(s, &endptr, 10);
2447 error("size value '%s' is invalid", s);
2450 if (endptr[0] && endptr[1]) {
2451 error("illegal suffix contains character '%c' in wrong position",
2456 * strtoll returns LLONG_MAX when overflow, if this happens,
2457 * need to call strtoull to get the real size
2459 if (errno == ERANGE && ret == ULLONG_MAX) {
2460 error("size value '%s' is too large for u64", s);
2464 c = tolower(endptr[0]);
2487 error("unknown size descriptor '%c'", c);
2491 /* Check whether ret * mult overflow */
2492 if (fls64(ret) + fls64(mult) - 1 > 64) {
2493 error("size value '%s' is too large for u64", s);
2500 u64 parse_qgroupid(const char *p)
2502 char *s = strchr(p, '/');
2503 const char *ptr_src_end = p + strlen(p);
2504 char *ptr_parse_end = NULL;
2513 /* Numeric format like '0/257' is the primary case */
2515 id = strtoull(p, &ptr_parse_end, 10);
2516 if (ptr_parse_end != ptr_src_end)
2520 level = strtoull(p, &ptr_parse_end, 10);
2521 if (ptr_parse_end != s)
2524 id = strtoull(s + 1, &ptr_parse_end, 10);
2525 if (ptr_parse_end != ptr_src_end)
2528 return (level << BTRFS_QGROUP_LEVEL_SHIFT) | id;
2531 /* Path format like subv at 'my_subvol' is the fallback case */
2532 ret = test_issubvolume(p);
2533 if (ret < 0 || !ret)
2535 fd = open(p, O_RDONLY);
2538 ret = lookup_path_rootid(fd, &id);
2540 error("failed to lookup root id: %s", strerror(-ret));
2547 error("invalid qgroupid or subvolume path: %s", p);
2551 int open_file_or_dir3(const char *fname, DIR **dirstream, int open_flags)
2557 ret = stat(fname, &st);
2561 if (S_ISDIR(st.st_mode)) {
2562 *dirstream = opendir(fname);
2565 fd = dirfd(*dirstream);
2566 } else if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
2567 fd = open(fname, open_flags);
2570 * we set this on purpose, in case the caller output
2571 * strerror(errno) as success
2579 closedir(*dirstream);
2586 int open_file_or_dir(const char *fname, DIR **dirstream)
2588 return open_file_or_dir3(fname, dirstream, O_RDWR);
2591 void close_file_or_dir(int fd, DIR *dirstream)
2594 closedir(dirstream);
2599 int get_device_info(int fd, u64 devid,
2600 struct btrfs_ioctl_dev_info_args *di_args)
2604 di_args->devid = devid;
2605 memset(&di_args->uuid, '\0', sizeof(di_args->uuid));
2607 ret = ioctl(fd, BTRFS_IOC_DEV_INFO, di_args);
2608 return ret < 0 ? -errno : 0;
2611 static u64 find_max_device_id(struct btrfs_ioctl_search_args *search_args,
2614 struct btrfs_dev_item *dev_item;
2615 char *buf = search_args->buf;
2617 buf += (nr_items - 1) * (sizeof(struct btrfs_ioctl_search_header)
2618 + sizeof(struct btrfs_dev_item));
2619 buf += sizeof(struct btrfs_ioctl_search_header);
2621 dev_item = (struct btrfs_dev_item *)buf;
2623 return btrfs_stack_device_id(dev_item);
2626 static int search_chunk_tree_for_fs_info(int fd,
2627 struct btrfs_ioctl_fs_info_args *fi_args)
2631 u64 start_devid = 1;
2632 struct btrfs_ioctl_search_args search_args;
2633 struct btrfs_ioctl_search_key *search_key = &search_args.key;
2635 fi_args->num_devices = 0;
2637 max_items = BTRFS_SEARCH_ARGS_BUFSIZE
2638 / (sizeof(struct btrfs_ioctl_search_header)
2639 + sizeof(struct btrfs_dev_item));
2641 search_key->tree_id = BTRFS_CHUNK_TREE_OBJECTID;
2642 search_key->min_objectid = BTRFS_DEV_ITEMS_OBJECTID;
2643 search_key->max_objectid = BTRFS_DEV_ITEMS_OBJECTID;
2644 search_key->min_type = BTRFS_DEV_ITEM_KEY;
2645 search_key->max_type = BTRFS_DEV_ITEM_KEY;
2646 search_key->min_transid = 0;
2647 search_key->max_transid = (u64)-1;
2648 search_key->nr_items = max_items;
2649 search_key->max_offset = (u64)-1;
2652 search_key->min_offset = start_devid;
2654 ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH, &search_args);
2658 fi_args->num_devices += (u64)search_key->nr_items;
2660 if (search_key->nr_items == max_items) {
2661 start_devid = find_max_device_id(&search_args,
2662 search_key->nr_items) + 1;
2666 /* get the lastest max_id to stay consistent with the num_devices */
2667 if (search_key->nr_items == 0)
2669 * last tree_search returns an empty buf, use the devid of
2670 * the last dev_item of the previous tree_search
2672 fi_args->max_id = start_devid - 1;
2674 fi_args->max_id = find_max_device_id(&search_args,
2675 search_key->nr_items);
2681 * For a given path, fill in the ioctl fs_ and info_ args.
2682 * If the path is a btrfs mountpoint, fill info for all devices.
2683 * If the path is a btrfs device, fill in only that device.
2685 * The path provided must be either on a mounted btrfs fs,
2686 * or be a mounted btrfs device.
2688 * Returns 0 on success, or a negative errno.
2690 int get_fs_info(const char *path, struct btrfs_ioctl_fs_info_args *fi_args,
2691 struct btrfs_ioctl_dev_info_args **di_ret)
2698 struct btrfs_fs_devices *fs_devices_mnt = NULL;
2699 struct btrfs_ioctl_dev_info_args *di_args;
2700 struct btrfs_ioctl_dev_info_args tmp;
2702 DIR *dirstream = NULL;
2704 memset(fi_args, 0, sizeof(*fi_args));
2706 if (is_block_device(path) == 1) {
2707 struct btrfs_super_block *disk_super;
2708 char buf[BTRFS_SUPER_INFO_SIZE];
2710 /* Ensure it's mounted, then set path to the mountpoint */
2711 fd = open(path, O_RDONLY);
2714 error("cannot open %s: %s", path, strerror(errno));
2717 ret = check_mounted_where(fd, path, mp, sizeof(mp),
2726 /* Only fill in this one device */
2727 fi_args->num_devices = 1;
2729 disk_super = (struct btrfs_super_block *)buf;
2730 ret = btrfs_read_dev_super(fd, disk_super,
2731 BTRFS_SUPER_INFO_OFFSET, 0);
2736 last_devid = btrfs_stack_device_id(&disk_super->dev_item);
2737 fi_args->max_id = last_devid;
2739 memcpy(fi_args->fsid, fs_devices_mnt->fsid, BTRFS_FSID_SIZE);
2743 /* at this point path must not be for a block device */
2744 fd = open_file_or_dir(path, &dirstream);
2750 /* fill in fi_args if not just a single device */
2751 if (fi_args->num_devices != 1) {
2752 ret = ioctl(fd, BTRFS_IOC_FS_INFO, fi_args);
2759 * The fs_args->num_devices does not include seed devices
2761 ret = search_chunk_tree_for_fs_info(fd, fi_args);
2766 * search_chunk_tree_for_fs_info() will lacks the devid 0
2767 * so manual probe for it here.
2769 ret = get_device_info(fd, 0, &tmp);
2771 fi_args->num_devices++;
2774 if (last_devid == 0)
2779 if (!fi_args->num_devices)
2782 di_args = *di_ret = malloc((fi_args->num_devices) * sizeof(*di_args));
2789 memcpy(di_args, &tmp, sizeof(tmp));
2790 for (; last_devid <= fi_args->max_id; last_devid++) {
2791 ret = get_device_info(fd, last_devid, &di_args[ndevs]);
2800 * only when the only dev we wanted to find is not there then
2801 * let any error be returned
2803 if (fi_args->num_devices != 1) {
2809 close_file_or_dir(fd, dirstream);
2813 #define isoctal(c) (((c) & ~7) == '0')
2815 static inline void translate(char *f, char *t)
2817 while (*f != '\0') {
2819 isoctal(f[1]) && isoctal(f[2]) && isoctal(f[3])) {
2820 *t++ = 64*(f[1] & 7) + 8*(f[2] & 7) + (f[3] & 7);
2830 * Checks if the swap device.
2831 * Returns 1 if swap device, < 0 on error or 0 if not swap device.
2833 static int is_swap_device(const char *file)
2844 if (stat(file, &st_buf) < 0)
2846 if (S_ISBLK(st_buf.st_mode))
2847 dev = st_buf.st_rdev;
2848 else if (S_ISREG(st_buf.st_mode)) {
2849 dev = st_buf.st_dev;
2850 ino = st_buf.st_ino;
2854 if ((f = fopen("/proc/swaps", "r")) == NULL)
2857 /* skip the first line */
2858 if (fgets(tmp, sizeof(tmp), f) == NULL)
2861 while (fgets(tmp, sizeof(tmp), f) != NULL) {
2862 if ((cp = strchr(tmp, ' ')) != NULL)
2864 if ((cp = strchr(tmp, '\t')) != NULL)
2866 translate(tmp, buf);
2867 if (stat(buf, &st_buf) != 0)
2869 if (S_ISBLK(st_buf.st_mode)) {
2870 if (dev == st_buf.st_rdev) {
2874 } else if (S_ISREG(st_buf.st_mode)) {
2875 if (dev == st_buf.st_dev && ino == st_buf.st_ino) {
2889 * Check for existing filesystem or partition table on device.
2891 * 1 for existing fs or partition
2892 * 0 for nothing found
2893 * -1 for internal error
2895 static int check_overwrite(const char *device)
2898 blkid_probe pr = NULL;
2902 if (!device || !*device)
2905 ret = -1; /* will reset on success of all setup calls */
2907 pr = blkid_new_probe_from_filename(device);
2911 size = blkid_probe_get_size(pr);
2915 /* nothing to overwrite on a 0-length device */
2921 ret = blkid_probe_enable_partitions(pr, 1);
2925 ret = blkid_do_fullprobe(pr);
2930 * Blkid returns 1 for nothing found and 0 when it finds a signature,
2931 * but we want the exact opposite, so reverse the return value here.
2933 * In addition print some useful diagnostics about what actually is
2941 if (!blkid_probe_lookup_value(pr, "TYPE", &type, NULL)) {
2943 "%s appears to contain an existing "
2944 "filesystem (%s).\n", device, type);
2945 } else if (!blkid_probe_lookup_value(pr, "PTTYPE", &type, NULL)) {
2947 "%s appears to contain a partition "
2948 "table (%s).\n", device, type);
2951 "%s appears to contain something weird "
2952 "according to blkid\n", device);
2958 blkid_free_probe(pr);
2961 "probe of %s failed, cannot detect "
2962 "existing filesystem.\n", device);
2966 static int group_profile_devs_min(u64 flag)
2968 switch (flag & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
2969 case 0: /* single */
2970 case BTRFS_BLOCK_GROUP_DUP:
2972 case BTRFS_BLOCK_GROUP_RAID0:
2973 case BTRFS_BLOCK_GROUP_RAID1:
2974 case BTRFS_BLOCK_GROUP_RAID5:
2976 case BTRFS_BLOCK_GROUP_RAID6:
2978 case BTRFS_BLOCK_GROUP_RAID10:
2985 int test_num_disk_vs_raid(u64 metadata_profile, u64 data_profile,
2986 u64 dev_cnt, int mixed, int ssd)
2989 u64 profile = metadata_profile | data_profile;
2994 allowed |= BTRFS_BLOCK_GROUP_RAID10;
2996 allowed |= BTRFS_BLOCK_GROUP_RAID6;
2998 allowed |= BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
2999 BTRFS_BLOCK_GROUP_RAID5;
3001 allowed |= BTRFS_BLOCK_GROUP_DUP;
3004 if (dev_cnt > 1 && profile & BTRFS_BLOCK_GROUP_DUP) {
3005 warning("DUP is not recommended on filesystem with multiple devices");
3007 if (metadata_profile & ~allowed) {
3009 "ERROR: unable to create FS with metadata profile %s "
3010 "(have %llu devices but %d devices are required)\n",
3011 btrfs_group_profile_str(metadata_profile), dev_cnt,
3012 group_profile_devs_min(metadata_profile));
3015 if (data_profile & ~allowed) {
3017 "ERROR: unable to create FS with data profile %s "
3018 "(have %llu devices but %d devices are required)\n",
3019 btrfs_group_profile_str(data_profile), dev_cnt,
3020 group_profile_devs_min(data_profile));
3024 if (dev_cnt == 3 && profile & BTRFS_BLOCK_GROUP_RAID6) {
3025 warning("RAID6 is not recommended on filesystem with 3 devices only");
3027 if (dev_cnt == 2 && profile & BTRFS_BLOCK_GROUP_RAID5) {
3028 warning("RAID5 is not recommended on filesystem with 2 devices only");
3030 warning_on(!mixed && (data_profile & BTRFS_BLOCK_GROUP_DUP) && ssd,
3031 "DUP may not actually lead to 2 copies on the device, see manual page");
3036 int group_profile_max_safe_loss(u64 flags)
3038 switch (flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
3039 case 0: /* single */
3040 case BTRFS_BLOCK_GROUP_DUP:
3041 case BTRFS_BLOCK_GROUP_RAID0:
3043 case BTRFS_BLOCK_GROUP_RAID1:
3044 case BTRFS_BLOCK_GROUP_RAID5:
3045 case BTRFS_BLOCK_GROUP_RAID10:
3047 case BTRFS_BLOCK_GROUP_RAID6:
3055 * Check if a device is suitable for btrfs
3057 * 1: something is wrong, an error is printed
3060 int test_dev_for_mkfs(const char *file, int force_overwrite)
3065 ret = is_swap_device(file);
3067 error("checking status of %s: %s", file, strerror(-ret));
3071 error("%s is a swap device", file);
3074 if (!force_overwrite) {
3075 if (check_overwrite(file)) {
3076 error("use the -f option to force overwrite of %s",
3081 ret = check_mounted(file);
3083 error("cannot check mount status of %s: %s", file,
3088 error("%s is mounted", file);
3091 /* check if the device is busy */
3092 fd = open(file, O_RDWR|O_EXCL);
3094 error("unable to open %s: %s", file, strerror(errno));
3097 if (fstat(fd, &st)) {
3098 error("unable to stat %s: %s", file, strerror(errno));
3102 if (!S_ISBLK(st.st_mode)) {
3103 error("%s is not a block device", file);
3111 int btrfs_scan_devices(void)
3116 struct btrfs_fs_devices *tmp_devices;
3117 blkid_dev_iterate iter = NULL;
3118 blkid_dev dev = NULL;
3119 blkid_cache cache = NULL;
3120 char path[PATH_MAX];
3122 if (btrfs_scan_done)
3125 if (blkid_get_cache(&cache, NULL) < 0) {
3126 error("blkid cache get failed");
3129 blkid_probe_all(cache);
3130 iter = blkid_dev_iterate_begin(cache);
3131 blkid_dev_set_search(iter, "TYPE", "btrfs");
3132 while (blkid_dev_next(iter, &dev) == 0) {
3133 dev = blkid_verify(cache, dev);
3136 /* if we are here its definitely a btrfs disk*/
3137 strncpy_null(path, blkid_dev_devname(dev));
3139 fd = open(path, O_RDONLY);
3141 error("cannot open %s: %s", path, strerror(errno));
3144 ret = btrfs_scan_one_device(fd, path, &tmp_devices,
3145 &num_devices, BTRFS_SUPER_INFO_OFFSET,
3148 error("cannot scan %s: %s", path, strerror(-ret));
3155 blkid_dev_iterate_end(iter);
3156 blkid_put_cache(cache);
3158 btrfs_scan_done = 1;
3163 int is_vol_small(const char *file)
3170 fd = open(file, O_RDONLY);
3173 if (fstat(fd, &st) < 0) {
3178 size = btrfs_device_size(fd, &st);
3183 if (size < BTRFS_MKFS_SMALL_VOLUME_SIZE) {
3193 * This reads a line from the stdin and only returns non-zero if the
3194 * first whitespace delimited token is a case insensitive match with yes
3197 int ask_user(const char *question)
3199 char buf[30] = {0,};
3200 char *saveptr = NULL;
3203 printf("%s [y/N]: ", question);
3205 return fgets(buf, sizeof(buf) - 1, stdin) &&
3206 (answer = strtok_r(buf, " \t\n\r", &saveptr)) &&
3207 (!strcasecmp(answer, "yes") || !strcasecmp(answer, "y"));
3211 * return 0 if a btrfs mount point is found
3212 * return 1 if a mount point is found but not btrfs
3213 * return <0 if something goes wrong
3215 int find_mount_root(const char *path, char **mount_root)
3223 int longest_matchlen = 0;
3224 char *longest_match = NULL;
3226 fd = open(path, O_RDONLY | O_NOATIME);
3231 mnttab = setmntent("/proc/self/mounts", "r");
3235 while ((ent = getmntent(mnttab))) {
3236 len = strlen(ent->mnt_dir);
3237 if (strncmp(ent->mnt_dir, path, len) == 0) {
3238 /* match found and use the latest match */
3239 if (longest_matchlen <= len) {
3240 free(longest_match);
3241 longest_matchlen = len;
3242 longest_match = strdup(ent->mnt_dir);
3243 not_btrfs = strcmp(ent->mnt_type, "btrfs");
3252 free(longest_match);
3257 *mount_root = realpath(longest_match, NULL);
3261 free(longest_match);
3265 int test_minimum_size(const char *file, u32 nodesize)
3268 struct stat statbuf;
3270 fd = open(file, O_RDONLY);
3273 if (stat(file, &statbuf) < 0) {
3277 if (btrfs_device_size(fd, &statbuf) < btrfs_min_dev_size(nodesize)) {
3287 * Test if path is a directory
3289 * 0 - path exists but it is not a directory
3290 * 1 - path exists and it is a directory
3293 int test_isdir(const char *path)
3298 ret = stat(path, &st);
3302 return !!S_ISDIR(st.st_mode);
3305 void units_set_mode(unsigned *units, unsigned mode)
3307 unsigned base = *units & UNITS_MODE_MASK;
3309 *units = base | mode;
3312 void units_set_base(unsigned *units, unsigned base)
3314 unsigned mode = *units & ~UNITS_MODE_MASK;
3316 *units = base | mode;
3319 int find_next_key(struct btrfs_path *path, struct btrfs_key *key)
3323 for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
3324 if (!path->nodes[level])
3326 if (path->slots[level] + 1 >=
3327 btrfs_header_nritems(path->nodes[level]))
3330 btrfs_item_key_to_cpu(path->nodes[level], key,
3331 path->slots[level] + 1);
3333 btrfs_node_key_to_cpu(path->nodes[level], key,
3334 path->slots[level] + 1);
3340 const char* btrfs_group_type_str(u64 flag)
3342 u64 mask = BTRFS_BLOCK_GROUP_TYPE_MASK |
3343 BTRFS_SPACE_INFO_GLOBAL_RSV;
3345 switch (flag & mask) {
3346 case BTRFS_BLOCK_GROUP_DATA:
3348 case BTRFS_BLOCK_GROUP_SYSTEM:
3350 case BTRFS_BLOCK_GROUP_METADATA:
3352 case BTRFS_BLOCK_GROUP_DATA|BTRFS_BLOCK_GROUP_METADATA:
3353 return "Data+Metadata";
3354 case BTRFS_SPACE_INFO_GLOBAL_RSV:
3355 return "GlobalReserve";
3361 const char* btrfs_group_profile_str(u64 flag)
3363 switch (flag & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
3366 case BTRFS_BLOCK_GROUP_RAID0:
3368 case BTRFS_BLOCK_GROUP_RAID1:
3370 case BTRFS_BLOCK_GROUP_RAID5:
3372 case BTRFS_BLOCK_GROUP_RAID6:
3374 case BTRFS_BLOCK_GROUP_DUP:
3376 case BTRFS_BLOCK_GROUP_RAID10:
3383 u64 disk_size(const char *path)
3387 if (statfs(path, &sfs) < 0)
3390 return sfs.f_bsize * sfs.f_blocks;
3393 u64 get_partition_size(const char *dev)
3396 int fd = open(dev, O_RDONLY);
3400 if (ioctl(fd, BLKGETSIZE64, &result) < 0) {
3410 * Check if the BTRFS_IOC_TREE_SEARCH_V2 ioctl is supported on a given
3411 * filesystem, opened at fd
3413 int btrfs_tree_search2_ioctl_supported(int fd)
3415 struct btrfs_ioctl_search_args_v2 *args2;
3416 struct btrfs_ioctl_search_key *sk;
3417 int args2_size = 1024;
3418 char args2_buf[args2_size];
3421 args2 = (struct btrfs_ioctl_search_args_v2 *)args2_buf;
3425 * Search for the extent tree item in the root tree.
3427 sk->tree_id = BTRFS_ROOT_TREE_OBJECTID;
3428 sk->min_objectid = BTRFS_EXTENT_TREE_OBJECTID;
3429 sk->max_objectid = BTRFS_EXTENT_TREE_OBJECTID;
3430 sk->min_type = BTRFS_ROOT_ITEM_KEY;
3431 sk->max_type = BTRFS_ROOT_ITEM_KEY;
3433 sk->max_offset = (u64)-1;
3434 sk->min_transid = 0;
3435 sk->max_transid = (u64)-1;
3437 args2->buf_size = args2_size - sizeof(struct btrfs_ioctl_search_args_v2);
3438 ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH_V2, args2);
3439 if (ret == -EOPNOTSUPP)
3446 int btrfs_check_nodesize(u32 nodesize, u32 sectorsize, u64 features)
3448 if (nodesize < sectorsize) {
3449 error("illegal nodesize %u (smaller than %u)",
3450 nodesize, sectorsize);
3452 } else if (nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
3453 error("illegal nodesize %u (larger than %u)",
3454 nodesize, BTRFS_MAX_METADATA_BLOCKSIZE);
3456 } else if (nodesize & (sectorsize - 1)) {
3457 error("illegal nodesize %u (not aligned to %u)",
3458 nodesize, sectorsize);
3460 } else if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS &&
3461 nodesize != sectorsize) {
3462 error("illegal nodesize %u (not equal to %u for mixed block group)",
3463 nodesize, sectorsize);
3470 * Copy a path argument from SRC to DEST and check the SRC length if it's at
3471 * most PATH_MAX and fits into DEST. DESTLEN is supposed to be exact size of
3473 * The destination buffer is zero terminated.
3474 * Return < 0 for error, 0 otherwise.
3476 int arg_copy_path(char *dest, const char *src, int destlen)
3478 size_t len = strlen(src);
3480 if (len >= PATH_MAX || len >= destlen)
3481 return -ENAMETOOLONG;
3483 __strncpy_null(dest, src, destlen);
3488 unsigned int get_unit_mode_from_arg(int *argc, char *argv[], int df_mode)
3490 unsigned int unit_mode = UNITS_DEFAULT;
3494 for (arg_i = 0; arg_i < *argc; arg_i++) {
3495 if (!strcmp(argv[arg_i], "--"))
3498 if (!strcmp(argv[arg_i], "--raw")) {
3499 unit_mode = UNITS_RAW;
3503 if (!strcmp(argv[arg_i], "--human-readable")) {
3504 unit_mode = UNITS_HUMAN_BINARY;
3509 if (!strcmp(argv[arg_i], "--iec")) {
3510 units_set_mode(&unit_mode, UNITS_BINARY);
3514 if (!strcmp(argv[arg_i], "--si")) {
3515 units_set_mode(&unit_mode, UNITS_DECIMAL);
3520 if (!strcmp(argv[arg_i], "--kbytes")) {
3521 units_set_base(&unit_mode, UNITS_KBYTES);
3525 if (!strcmp(argv[arg_i], "--mbytes")) {
3526 units_set_base(&unit_mode, UNITS_MBYTES);
3530 if (!strcmp(argv[arg_i], "--gbytes")) {
3531 units_set_base(&unit_mode, UNITS_GBYTES);
3535 if (!strcmp(argv[arg_i], "--tbytes")) {
3536 units_set_base(&unit_mode, UNITS_TBYTES);
3544 if (!strcmp(argv[arg_i], "-b")) {
3545 unit_mode = UNITS_RAW;
3549 if (!strcmp(argv[arg_i], "-h")) {
3550 unit_mode = UNITS_HUMAN_BINARY;
3554 if (!strcmp(argv[arg_i], "-H")) {
3555 unit_mode = UNITS_HUMAN_DECIMAL;
3559 if (!strcmp(argv[arg_i], "-k")) {
3560 units_set_base(&unit_mode, UNITS_KBYTES);
3564 if (!strcmp(argv[arg_i], "-m")) {
3565 units_set_base(&unit_mode, UNITS_MBYTES);
3569 if (!strcmp(argv[arg_i], "-g")) {
3570 units_set_base(&unit_mode, UNITS_GBYTES);
3574 if (!strcmp(argv[arg_i], "-t")) {
3575 units_set_base(&unit_mode, UNITS_TBYTES);
3581 for (arg_i = 0, arg_end = 0; arg_i < *argc; arg_i++) {
3584 argv[arg_end] = argv[arg_i];
3593 int string_is_numerical(const char *str)
3597 if (!(*str >= '0' && *str <= '9'))
3599 while (*str >= '0' && *str <= '9')
3606 /* Subvolume helper functions */
3608 * test if name is a correct subvolume name
3609 * this function return
3610 * 0-> name is not a correct subvolume name
3611 * 1-> name is a correct subvolume name
3613 int test_issubvolname(const char *name)
3615 return name[0] != '\0' && !strchr(name, '/') &&
3616 strcmp(name, ".") && strcmp(name, "..");
3620 * Test if path is a subvolume
3622 * 0 - path exists but it is not a subvolume
3623 * 1 - path exists and it is a subvolume
3626 int test_issubvolume(const char *path)
3632 res = stat(path, &st);
3636 if (st.st_ino != BTRFS_FIRST_FREE_OBJECTID || !S_ISDIR(st.st_mode))
3639 res = statfs(path, &stfs);
3643 return (int)stfs.f_type == BTRFS_SUPER_MAGIC;
3646 const char *subvol_strip_mountpoint(const char *mnt, const char *full_path)
3648 int len = strlen(mnt);
3652 if (mnt[len - 1] != '/')
3655 return full_path + len;
3662 * 1: Error; and error info printed to the terminal. Fixme.
3663 * 2: If the fullpath is root tree instead of subvol tree
3665 int get_subvol_info(const char *fullpath, struct root_info *get_ri)
3672 const char *svpath = NULL;
3673 DIR *dirstream1 = NULL;
3674 DIR *dirstream2 = NULL;
3676 ret = test_issubvolume(fullpath);
3680 error("not a subvolume: %s", fullpath);
3684 ret = find_mount_root(fullpath, &mnt);
3688 error("%s doesn't belong to btrfs mount point", fullpath);
3692 svpath = subvol_strip_mountpoint(mnt, fullpath);
3694 fd = btrfs_open_dir(fullpath, &dirstream1, 1);
3698 ret = btrfs_list_get_path_rootid(fd, &sv_id);
3702 mntfd = btrfs_open_dir(mnt, &dirstream2, 1);
3706 memset(get_ri, 0, sizeof(*get_ri));
3707 get_ri->root_id = sv_id;
3709 if (sv_id == BTRFS_FS_TREE_OBJECTID)
3710 ret = btrfs_get_toplevel_subvol(mntfd, get_ri);
3712 ret = btrfs_get_subvol(mntfd, get_ri);
3714 error("can't find '%s': %d", svpath, ret);
3717 close_file_or_dir(mntfd, dirstream2);
3718 close_file_or_dir(fd, dirstream1);
3724 void init_rand_seed(u64 seed)
3728 /* only use the last 48 bits */
3729 for (i = 0; i < 3; i++) {
3730 rand_seed[i] = (unsigned short)(seed ^ (unsigned short)(-1));
3733 rand_seed_initlized = 1;
3736 static void __init_seed(void)
3742 if(rand_seed_initlized)
3744 /* Use urandom as primary seed source. */
3745 fd = open("/dev/urandom", O_RDONLY);
3747 ret = read(fd, rand_seed, sizeof(rand_seed));
3749 if (ret < sizeof(rand_seed))
3753 /* Use time and pid as fallback seed */
3754 warning("failed to read /dev/urandom, use time and pid as random seed");
3755 gettimeofday(&tv, 0);
3756 rand_seed[0] = getpid() ^ (tv.tv_sec & 0xFFFF);
3757 rand_seed[1] = getppid() ^ (tv.tv_usec & 0xFFFF);
3758 rand_seed[2] = (tv.tv_sec ^ tv.tv_usec) >> 16;
3760 rand_seed_initlized = 1;
3767 * Don't use nrand48, its range is [0,2^31) The highest bit will alwasy
3768 * be 0. Use jrand48 to include the highest bit.
3770 return (u32)jrand48(rand_seed);
3773 unsigned int rand_range(unsigned int upper)
3777 * Use the full 48bits to mod, which would be more uniformly
3780 return (unsigned int)(jrand48(rand_seed) % upper);
3783 void btrfs_config_init(void)