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>
39 #include "kerncompat.h"
40 #include "radix-tree.h"
43 #include "transaction.h"
50 #define BLKDISCARD _IO(0x12,119)
53 static int btrfs_scan_done = 0;
55 static char argv0_buf[ARGV0_BUF_SIZE] = "btrfs";
57 void fixup_argv0(char **argv, const char *token)
59 int len = strlen(argv0_buf);
61 snprintf(argv0_buf + len, sizeof(argv0_buf) - len, " %s", token);
65 void set_argv0(char **argv)
67 strncpy(argv0_buf, argv[0], sizeof(argv0_buf));
68 argv0_buf[sizeof(argv0_buf) - 1] = 0;
71 int check_argc_exact(int nargs, int expected)
74 fprintf(stderr, "%s: too few arguments\n", argv0_buf);
76 fprintf(stderr, "%s: too many arguments\n", argv0_buf);
78 return nargs != expected;
81 int check_argc_min(int nargs, int expected)
83 if (nargs < expected) {
84 fprintf(stderr, "%s: too few arguments\n", argv0_buf);
91 int check_argc_max(int nargs, int expected)
93 if (nargs > expected) {
94 fprintf(stderr, "%s: too many arguments\n", argv0_buf);
103 * Discard the given range in one go
105 static int discard_range(int fd, u64 start, u64 len)
107 u64 range[2] = { start, len };
109 if (ioctl(fd, BLKDISCARD, &range) < 0)
115 * Discard blocks in the given range in 1G chunks, the process is interruptible
117 static int discard_blocks(int fd, u64 start, u64 len)
121 u64 chunk_size = min_t(u64, len, 1*1024*1024*1024);
124 ret = discard_range(fd, start, chunk_size);
134 static u64 reference_root_table[] = {
135 [1] = BTRFS_ROOT_TREE_OBJECTID,
136 [2] = BTRFS_EXTENT_TREE_OBJECTID,
137 [3] = BTRFS_CHUNK_TREE_OBJECTID,
138 [4] = BTRFS_DEV_TREE_OBJECTID,
139 [5] = BTRFS_FS_TREE_OBJECTID,
140 [6] = BTRFS_CSUM_TREE_OBJECTID,
143 int test_uuid_unique(char *fs_uuid)
146 blkid_dev_iterate iter = NULL;
147 blkid_dev dev = NULL;
148 blkid_cache cache = NULL;
150 if (blkid_get_cache(&cache, 0) < 0) {
151 printf("ERROR: lblkid cache get failed\n");
154 blkid_probe_all(cache);
155 iter = blkid_dev_iterate_begin(cache);
156 blkid_dev_set_search(iter, "UUID", fs_uuid);
158 while (blkid_dev_next(iter, &dev) == 0) {
159 dev = blkid_verify(cache, dev);
166 blkid_dev_iterate_end(iter);
167 blkid_put_cache(cache);
173 * @fs_uuid - if NULL, generates a UUID, returns back the new filesystem UUID
175 int make_btrfs(int fd, const char *device, const char *label, char *fs_uuid,
176 u64 blocks[7], u64 num_bytes, u32 nodesize,
177 u32 sectorsize, u32 stripesize, u64 features)
179 struct btrfs_super_block super;
180 struct extent_buffer *buf = NULL;
181 struct btrfs_root_item root_item;
182 struct btrfs_disk_key disk_key;
183 struct btrfs_extent_item *extent_item;
184 struct btrfs_inode_item *inode_item;
185 struct btrfs_chunk *chunk;
186 struct btrfs_dev_item *dev_item;
187 struct btrfs_dev_extent *dev_extent;
188 u8 chunk_tree_uuid[BTRFS_UUID_SIZE];
198 int skinny_metadata = !!(features &
199 BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA);
201 first_free = BTRFS_SUPER_INFO_OFFSET + sectorsize * 2 - 1;
202 first_free &= ~((u64)sectorsize - 1);
204 memset(&super, 0, sizeof(super));
206 num_bytes = (num_bytes / sectorsize) * sectorsize;
207 if (fs_uuid && *fs_uuid) {
208 if (uuid_parse(fs_uuid, super.fsid) != 0) {
209 fprintf(stderr, "could not parse UUID: %s\n", fs_uuid);
213 if (!test_uuid_unique(fs_uuid)) {
214 fprintf(stderr, "non-unique UUID: %s\n", fs_uuid);
219 uuid_generate(super.fsid);
221 uuid_unparse(super.fsid, fs_uuid);
223 uuid_generate(super.dev_item.uuid);
224 uuid_generate(chunk_tree_uuid);
226 btrfs_set_super_bytenr(&super, blocks[0]);
227 btrfs_set_super_num_devices(&super, 1);
228 btrfs_set_super_magic(&super, BTRFS_MAGIC);
229 btrfs_set_super_generation(&super, 1);
230 btrfs_set_super_root(&super, blocks[1]);
231 btrfs_set_super_chunk_root(&super, blocks[3]);
232 btrfs_set_super_total_bytes(&super, num_bytes);
233 btrfs_set_super_bytes_used(&super, 6 * nodesize);
234 btrfs_set_super_sectorsize(&super, sectorsize);
235 btrfs_set_super_leafsize(&super, nodesize);
236 btrfs_set_super_nodesize(&super, nodesize);
237 btrfs_set_super_stripesize(&super, stripesize);
238 btrfs_set_super_csum_type(&super, BTRFS_CSUM_TYPE_CRC32);
239 btrfs_set_super_chunk_root_generation(&super, 1);
240 btrfs_set_super_cache_generation(&super, -1);
241 btrfs_set_super_incompat_flags(&super, features);
243 strncpy(super.label, label, BTRFS_LABEL_SIZE - 1);
245 buf = malloc(sizeof(*buf) + max(sectorsize, nodesize));
247 /* create the tree of root objects */
248 memset(buf->data, 0, nodesize);
250 btrfs_set_header_bytenr(buf, blocks[1]);
251 btrfs_set_header_nritems(buf, 4);
252 btrfs_set_header_generation(buf, 1);
253 btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
254 btrfs_set_header_owner(buf, BTRFS_ROOT_TREE_OBJECTID);
255 write_extent_buffer(buf, super.fsid, btrfs_header_fsid(),
258 write_extent_buffer(buf, chunk_tree_uuid,
259 btrfs_header_chunk_tree_uuid(buf),
262 /* create the items for the root tree */
263 memset(&root_item, 0, sizeof(root_item));
264 inode_item = &root_item.inode;
265 btrfs_set_stack_inode_generation(inode_item, 1);
266 btrfs_set_stack_inode_size(inode_item, 3);
267 btrfs_set_stack_inode_nlink(inode_item, 1);
268 btrfs_set_stack_inode_nbytes(inode_item, nodesize);
269 btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
270 btrfs_set_root_refs(&root_item, 1);
271 btrfs_set_root_used(&root_item, nodesize);
272 btrfs_set_root_generation(&root_item, 1);
274 memset(&disk_key, 0, sizeof(disk_key));
275 btrfs_set_disk_key_type(&disk_key, BTRFS_ROOT_ITEM_KEY);
276 btrfs_set_disk_key_offset(&disk_key, 0);
279 itemoff = __BTRFS_LEAF_DATA_SIZE(nodesize) - sizeof(root_item);
280 btrfs_set_root_bytenr(&root_item, blocks[2]);
281 btrfs_set_disk_key_objectid(&disk_key, BTRFS_EXTENT_TREE_OBJECTID);
282 btrfs_set_item_key(buf, &disk_key, nritems);
283 btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
284 btrfs_set_item_size(buf, btrfs_item_nr(nritems),
286 write_extent_buffer(buf, &root_item, btrfs_item_ptr_offset(buf,
287 nritems), sizeof(root_item));
290 itemoff = itemoff - sizeof(root_item);
291 btrfs_set_root_bytenr(&root_item, blocks[4]);
292 btrfs_set_disk_key_objectid(&disk_key, BTRFS_DEV_TREE_OBJECTID);
293 btrfs_set_item_key(buf, &disk_key, nritems);
294 btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
295 btrfs_set_item_size(buf, btrfs_item_nr(nritems),
297 write_extent_buffer(buf, &root_item,
298 btrfs_item_ptr_offset(buf, nritems),
302 itemoff = itemoff - sizeof(root_item);
303 btrfs_set_root_bytenr(&root_item, blocks[5]);
304 btrfs_set_disk_key_objectid(&disk_key, BTRFS_FS_TREE_OBJECTID);
305 btrfs_set_item_key(buf, &disk_key, nritems);
306 btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
307 btrfs_set_item_size(buf, btrfs_item_nr(nritems),
309 write_extent_buffer(buf, &root_item,
310 btrfs_item_ptr_offset(buf, nritems),
314 itemoff = itemoff - sizeof(root_item);
315 btrfs_set_root_bytenr(&root_item, blocks[6]);
316 btrfs_set_disk_key_objectid(&disk_key, BTRFS_CSUM_TREE_OBJECTID);
317 btrfs_set_item_key(buf, &disk_key, nritems);
318 btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
319 btrfs_set_item_size(buf, btrfs_item_nr(nritems),
321 write_extent_buffer(buf, &root_item,
322 btrfs_item_ptr_offset(buf, nritems),
327 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
328 ret = pwrite(fd, buf->data, nodesize, blocks[1]);
329 if (ret != nodesize) {
330 ret = (ret < 0 ? -errno : -EIO);
334 /* create the items for the extent tree */
335 memset(buf->data + sizeof(struct btrfs_header), 0,
336 nodesize - sizeof(struct btrfs_header));
338 itemoff = __BTRFS_LEAF_DATA_SIZE(nodesize);
339 for (i = 1; i < 7; i++) {
340 item_size = sizeof(struct btrfs_extent_item);
341 if (!skinny_metadata)
342 item_size += sizeof(struct btrfs_tree_block_info);
344 BUG_ON(blocks[i] < first_free);
345 BUG_ON(blocks[i] < blocks[i - 1]);
347 /* create extent item */
348 itemoff -= item_size;
349 btrfs_set_disk_key_objectid(&disk_key, blocks[i]);
350 if (skinny_metadata) {
351 btrfs_set_disk_key_type(&disk_key,
352 BTRFS_METADATA_ITEM_KEY);
353 btrfs_set_disk_key_offset(&disk_key, 0);
355 btrfs_set_disk_key_type(&disk_key,
356 BTRFS_EXTENT_ITEM_KEY);
357 btrfs_set_disk_key_offset(&disk_key, nodesize);
359 btrfs_set_item_key(buf, &disk_key, nritems);
360 btrfs_set_item_offset(buf, btrfs_item_nr(nritems),
362 btrfs_set_item_size(buf, btrfs_item_nr(nritems),
364 extent_item = btrfs_item_ptr(buf, nritems,
365 struct btrfs_extent_item);
366 btrfs_set_extent_refs(buf, extent_item, 1);
367 btrfs_set_extent_generation(buf, extent_item, 1);
368 btrfs_set_extent_flags(buf, extent_item,
369 BTRFS_EXTENT_FLAG_TREE_BLOCK);
372 /* create extent ref */
373 ref_root = reference_root_table[i];
374 btrfs_set_disk_key_objectid(&disk_key, blocks[i]);
375 btrfs_set_disk_key_offset(&disk_key, ref_root);
376 btrfs_set_disk_key_type(&disk_key, BTRFS_TREE_BLOCK_REF_KEY);
377 btrfs_set_item_key(buf, &disk_key, nritems);
378 btrfs_set_item_offset(buf, btrfs_item_nr(nritems),
380 btrfs_set_item_size(buf, btrfs_item_nr(nritems), 0);
383 btrfs_set_header_bytenr(buf, blocks[2]);
384 btrfs_set_header_owner(buf, BTRFS_EXTENT_TREE_OBJECTID);
385 btrfs_set_header_nritems(buf, nritems);
386 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
387 ret = pwrite(fd, buf->data, nodesize, blocks[2]);
388 if (ret != nodesize) {
389 ret = (ret < 0 ? -errno : -EIO);
393 /* create the chunk tree */
394 memset(buf->data + sizeof(struct btrfs_header), 0,
395 nodesize - sizeof(struct btrfs_header));
397 item_size = sizeof(*dev_item);
398 itemoff = __BTRFS_LEAF_DATA_SIZE(nodesize) - item_size;
400 /* first device 1 (there is no device 0) */
401 btrfs_set_disk_key_objectid(&disk_key, BTRFS_DEV_ITEMS_OBJECTID);
402 btrfs_set_disk_key_offset(&disk_key, 1);
403 btrfs_set_disk_key_type(&disk_key, BTRFS_DEV_ITEM_KEY);
404 btrfs_set_item_key(buf, &disk_key, nritems);
405 btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
406 btrfs_set_item_size(buf, btrfs_item_nr(nritems), item_size);
408 dev_item = btrfs_item_ptr(buf, nritems, struct btrfs_dev_item);
409 btrfs_set_device_id(buf, dev_item, 1);
410 btrfs_set_device_generation(buf, dev_item, 0);
411 btrfs_set_device_total_bytes(buf, dev_item, num_bytes);
412 btrfs_set_device_bytes_used(buf, dev_item,
413 BTRFS_MKFS_SYSTEM_GROUP_SIZE);
414 btrfs_set_device_io_align(buf, dev_item, sectorsize);
415 btrfs_set_device_io_width(buf, dev_item, sectorsize);
416 btrfs_set_device_sector_size(buf, dev_item, sectorsize);
417 btrfs_set_device_type(buf, dev_item, 0);
419 write_extent_buffer(buf, super.dev_item.uuid,
420 (unsigned long)btrfs_device_uuid(dev_item),
422 write_extent_buffer(buf, super.fsid,
423 (unsigned long)btrfs_device_fsid(dev_item),
425 read_extent_buffer(buf, &super.dev_item, (unsigned long)dev_item,
429 item_size = btrfs_chunk_item_size(1);
430 itemoff = itemoff - item_size;
432 /* then we have chunk 0 */
433 btrfs_set_disk_key_objectid(&disk_key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
434 btrfs_set_disk_key_offset(&disk_key, 0);
435 btrfs_set_disk_key_type(&disk_key, BTRFS_CHUNK_ITEM_KEY);
436 btrfs_set_item_key(buf, &disk_key, nritems);
437 btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
438 btrfs_set_item_size(buf, btrfs_item_nr(nritems), item_size);
440 chunk = btrfs_item_ptr(buf, nritems, struct btrfs_chunk);
441 btrfs_set_chunk_length(buf, chunk, BTRFS_MKFS_SYSTEM_GROUP_SIZE);
442 btrfs_set_chunk_owner(buf, chunk, BTRFS_EXTENT_TREE_OBJECTID);
443 btrfs_set_chunk_stripe_len(buf, chunk, 64 * 1024);
444 btrfs_set_chunk_type(buf, chunk, BTRFS_BLOCK_GROUP_SYSTEM);
445 btrfs_set_chunk_io_align(buf, chunk, sectorsize);
446 btrfs_set_chunk_io_width(buf, chunk, sectorsize);
447 btrfs_set_chunk_sector_size(buf, chunk, sectorsize);
448 btrfs_set_chunk_num_stripes(buf, chunk, 1);
449 btrfs_set_stripe_devid_nr(buf, chunk, 0, 1);
450 btrfs_set_stripe_offset_nr(buf, chunk, 0, 0);
453 write_extent_buffer(buf, super.dev_item.uuid,
454 (unsigned long)btrfs_stripe_dev_uuid(&chunk->stripe),
457 /* copy the key for the chunk to the system array */
458 ptr = super.sys_chunk_array;
459 array_size = sizeof(disk_key);
461 memcpy(ptr, &disk_key, sizeof(disk_key));
462 ptr += sizeof(disk_key);
464 /* copy the chunk to the system array */
465 read_extent_buffer(buf, ptr, (unsigned long)chunk, item_size);
466 array_size += item_size;
468 btrfs_set_super_sys_array_size(&super, array_size);
470 btrfs_set_header_bytenr(buf, blocks[3]);
471 btrfs_set_header_owner(buf, BTRFS_CHUNK_TREE_OBJECTID);
472 btrfs_set_header_nritems(buf, nritems);
473 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
474 ret = pwrite(fd, buf->data, nodesize, blocks[3]);
475 if (ret != nodesize) {
476 ret = (ret < 0 ? -errno : -EIO);
480 /* create the device tree */
481 memset(buf->data + sizeof(struct btrfs_header), 0,
482 nodesize - sizeof(struct btrfs_header));
484 itemoff = __BTRFS_LEAF_DATA_SIZE(nodesize) -
485 sizeof(struct btrfs_dev_extent);
487 btrfs_set_disk_key_objectid(&disk_key, 1);
488 btrfs_set_disk_key_offset(&disk_key, 0);
489 btrfs_set_disk_key_type(&disk_key, BTRFS_DEV_EXTENT_KEY);
490 btrfs_set_item_key(buf, &disk_key, nritems);
491 btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
492 btrfs_set_item_size(buf, btrfs_item_nr(nritems),
493 sizeof(struct btrfs_dev_extent));
494 dev_extent = btrfs_item_ptr(buf, nritems, struct btrfs_dev_extent);
495 btrfs_set_dev_extent_chunk_tree(buf, dev_extent,
496 BTRFS_CHUNK_TREE_OBJECTID);
497 btrfs_set_dev_extent_chunk_objectid(buf, dev_extent,
498 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
499 btrfs_set_dev_extent_chunk_offset(buf, dev_extent, 0);
501 write_extent_buffer(buf, chunk_tree_uuid,
502 (unsigned long)btrfs_dev_extent_chunk_tree_uuid(dev_extent),
505 btrfs_set_dev_extent_length(buf, dev_extent,
506 BTRFS_MKFS_SYSTEM_GROUP_SIZE);
509 btrfs_set_header_bytenr(buf, blocks[4]);
510 btrfs_set_header_owner(buf, BTRFS_DEV_TREE_OBJECTID);
511 btrfs_set_header_nritems(buf, nritems);
512 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
513 ret = pwrite(fd, buf->data, nodesize, blocks[4]);
514 if (ret != nodesize) {
515 ret = (ret < 0 ? -errno : -EIO);
519 /* create the FS root */
520 memset(buf->data + sizeof(struct btrfs_header), 0,
521 nodesize - sizeof(struct btrfs_header));
522 btrfs_set_header_bytenr(buf, blocks[5]);
523 btrfs_set_header_owner(buf, BTRFS_FS_TREE_OBJECTID);
524 btrfs_set_header_nritems(buf, 0);
525 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
526 ret = pwrite(fd, buf->data, nodesize, blocks[5]);
527 if (ret != nodesize) {
528 ret = (ret < 0 ? -errno : -EIO);
531 /* finally create the csum root */
532 memset(buf->data + sizeof(struct btrfs_header), 0,
533 nodesize - sizeof(struct btrfs_header));
534 btrfs_set_header_bytenr(buf, blocks[6]);
535 btrfs_set_header_owner(buf, BTRFS_CSUM_TREE_OBJECTID);
536 btrfs_set_header_nritems(buf, 0);
537 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
538 ret = pwrite(fd, buf->data, nodesize, blocks[6]);
539 if (ret != nodesize) {
540 ret = (ret < 0 ? -errno : -EIO);
544 /* and write out the super block */
545 BUG_ON(sizeof(super) > sectorsize);
546 memset(buf->data, 0, sectorsize);
547 memcpy(buf->data, &super, sizeof(super));
548 buf->len = sectorsize;
549 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
550 ret = pwrite(fd, buf->data, sectorsize, blocks[0]);
551 if (ret != sectorsize) {
552 ret = (ret < 0 ? -errno : -EIO);
563 static const struct btrfs_fs_feature {
567 } mkfs_features[] = {
568 { "mixed-bg", BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS,
569 "mixed data and metadata block groups" },
570 { "extref", BTRFS_FEATURE_INCOMPAT_EXTENDED_IREF,
571 "increased hardlink limit per file to 65536" },
572 { "raid56", BTRFS_FEATURE_INCOMPAT_RAID56,
573 "raid56 extended format" },
574 { "skinny-metadata", BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA,
575 "reduced-size metadata extent refs" },
576 { "no-holes", BTRFS_FEATURE_INCOMPAT_NO_HOLES,
577 "no explicit hole extents for files" },
578 /* Keep this one last */
579 { "list-all", BTRFS_FEATURE_LIST_ALL, NULL }
582 static int parse_one_fs_feature(const char *name, u64 *flags)
587 for (i = 0; i < ARRAY_SIZE(mkfs_features); i++) {
588 if (name[0] == '^' &&
589 !strcmp(mkfs_features[i].name, name + 1)) {
590 *flags &= ~ mkfs_features[i].flag;
592 } else if (!strcmp(mkfs_features[i].name, name)) {
593 *flags |= mkfs_features[i].flag;
601 void btrfs_parse_features_to_string(char *buf, u64 flags)
607 for (i = 0; i < ARRAY_SIZE(mkfs_features); i++) {
608 if (flags & mkfs_features[i].flag) {
611 strcat(buf, mkfs_features[i].name);
616 void btrfs_process_fs_features(u64 flags)
620 for (i = 0; i < ARRAY_SIZE(mkfs_features); i++) {
621 if (flags & mkfs_features[i].flag) {
622 printf("Turning ON incompat feature '%s': %s\n",
623 mkfs_features[i].name,
624 mkfs_features[i].desc);
629 void btrfs_list_all_fs_features(u64 mask_disallowed)
633 fprintf(stderr, "Filesystem features available:\n");
634 for (i = 0; i < ARRAY_SIZE(mkfs_features) - 1; i++) {
635 char *is_default = "";
637 if (mkfs_features[i].flag & mask_disallowed)
639 if (mkfs_features[i].flag & BTRFS_MKFS_DEFAULT_FEATURES)
640 is_default = ", default";
641 fprintf(stderr, "%-20s- %s (0x%llx%s)\n",
642 mkfs_features[i].name,
643 mkfs_features[i].desc,
644 mkfs_features[i].flag,
650 * Return NULL if all features were parsed fine, otherwise return the name of
651 * the first unparsed.
653 char* btrfs_parse_fs_features(char *namelist, u64 *flags)
656 char *save_ptr = NULL; /* Satisfy static checkers */
658 for (this_char = strtok_r(namelist, ",", &save_ptr);
660 this_char = strtok_r(NULL, ",", &save_ptr)) {
661 if (parse_one_fs_feature(this_char, flags))
668 u64 btrfs_device_size(int fd, struct stat *st)
671 if (S_ISREG(st->st_mode)) {
674 if (!S_ISBLK(st->st_mode)) {
677 if (ioctl(fd, BLKGETSIZE64, &size) >= 0) {
683 static int zero_blocks(int fd, off_t start, size_t len)
685 char *buf = malloc(len);
692 written = pwrite(fd, buf, len, start);
699 #define ZERO_DEV_BYTES (2 * 1024 * 1024)
701 /* don't write outside the device by clamping the region to the device size */
702 static int zero_dev_clamped(int fd, off_t start, ssize_t len, u64 dev_size)
704 off_t end = max(start, start + len);
707 /* and don't overwrite the disk labels on sparc */
708 start = max(start, 1024);
709 end = max(end, 1024);
712 start = min_t(u64, start, dev_size);
713 end = min_t(u64, end, dev_size);
715 return zero_blocks(fd, start, end - start);
718 int btrfs_add_to_fsid(struct btrfs_trans_handle *trans,
719 struct btrfs_root *root, int fd, char *path,
720 u64 block_count, u32 io_width, u32 io_align,
723 struct btrfs_super_block *disk_super;
724 struct btrfs_super_block *super = root->fs_info->super_copy;
725 struct btrfs_device *device;
726 struct btrfs_dev_item *dev_item;
732 device = kzalloc(sizeof(*device), GFP_NOFS);
735 buf = kmalloc(sectorsize, GFP_NOFS);
740 BUG_ON(sizeof(*disk_super) > sectorsize);
741 memset(buf, 0, sectorsize);
743 disk_super = (struct btrfs_super_block *)buf;
744 dev_item = &disk_super->dev_item;
746 uuid_generate(device->uuid);
749 device->io_width = io_width;
750 device->io_align = io_align;
751 device->sector_size = sectorsize;
753 device->writeable = 1;
754 device->total_bytes = block_count;
755 device->bytes_used = 0;
756 device->total_ios = 0;
757 device->dev_root = root->fs_info->dev_root;
758 device->name = strdup(path);
760 ret = btrfs_add_device(trans, root, device);
763 total_bytes = btrfs_super_total_bytes(super) + block_count;
764 btrfs_set_super_total_bytes(super, total_bytes);
766 num_devs = btrfs_super_num_devices(super) + 1;
767 btrfs_set_super_num_devices(super, num_devs);
769 memcpy(disk_super, super, sizeof(*disk_super));
771 btrfs_set_super_bytenr(disk_super, BTRFS_SUPER_INFO_OFFSET);
772 btrfs_set_stack_device_id(dev_item, device->devid);
773 btrfs_set_stack_device_type(dev_item, device->type);
774 btrfs_set_stack_device_io_align(dev_item, device->io_align);
775 btrfs_set_stack_device_io_width(dev_item, device->io_width);
776 btrfs_set_stack_device_sector_size(dev_item, device->sector_size);
777 btrfs_set_stack_device_total_bytes(dev_item, device->total_bytes);
778 btrfs_set_stack_device_bytes_used(dev_item, device->bytes_used);
779 memcpy(&dev_item->uuid, device->uuid, BTRFS_UUID_SIZE);
781 ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
782 BUG_ON(ret != sectorsize);
785 list_add(&device->dev_list, &root->fs_info->fs_devices->devices);
786 device->fs_devices = root->fs_info->fs_devices;
790 static void btrfs_wipe_existing_sb(int fd)
792 const char *off = NULL;
797 blkid_probe pr = NULL;
799 pr = blkid_new_probe();
803 if (blkid_probe_set_device(pr, fd, 0, 0))
806 rc = blkid_probe_lookup_value(pr, "SBMAGIC_OFFSET", &off, NULL);
808 rc = blkid_probe_lookup_value(pr, "SBMAGIC", NULL, &len);
810 if (rc || len == 0 || off == NULL)
813 offset = strtoll(off, NULL, 10);
814 if (len > sizeof(buf))
818 rc = pwrite(fd, buf, len, offset);
822 blkid_free_probe(pr);
826 int btrfs_prepare_device(int fd, char *file, int zero_end, u64 *block_count_ret,
827 u64 max_block_count, int *mixed, int discard)
833 ret = fstat(fd, &st);
835 fprintf(stderr, "unable to stat %s\n", file);
839 block_count = btrfs_device_size(fd, &st);
840 if (block_count == 0) {
841 fprintf(stderr, "unable to find %s size\n", file);
845 block_count = min(block_count, max_block_count);
847 if (block_count < BTRFS_MKFS_SMALL_VOLUME_SIZE && !(*mixed))
852 * We intentionally ignore errors from the discard ioctl. It
853 * is not necessary for the mkfs functionality but just an
856 if (discard_range(fd, 0, 0) == 0) {
857 printf("Performing full device TRIM (%s) ...\n",
858 pretty_size(block_count));
859 discard_blocks(fd, 0, block_count);
863 ret = zero_dev_clamped(fd, 0, ZERO_DEV_BYTES, block_count);
864 for (i = 0 ; !ret && i < BTRFS_SUPER_MIRROR_MAX; i++)
865 ret = zero_dev_clamped(fd, btrfs_sb_offset(i),
866 BTRFS_SUPER_INFO_SIZE, block_count);
867 if (!ret && zero_end)
868 ret = zero_dev_clamped(fd, block_count - ZERO_DEV_BYTES,
869 ZERO_DEV_BYTES, block_count);
872 fprintf(stderr, "ERROR: failed to zero device '%s' - %s\n",
873 file, strerror(-ret));
877 btrfs_wipe_existing_sb(fd);
879 *block_count_ret = block_count;
883 int btrfs_make_root_dir(struct btrfs_trans_handle *trans,
884 struct btrfs_root *root, u64 objectid)
887 struct btrfs_inode_item inode_item;
888 time_t now = time(NULL);
890 memset(&inode_item, 0, sizeof(inode_item));
891 btrfs_set_stack_inode_generation(&inode_item, trans->transid);
892 btrfs_set_stack_inode_size(&inode_item, 0);
893 btrfs_set_stack_inode_nlink(&inode_item, 1);
894 btrfs_set_stack_inode_nbytes(&inode_item, root->nodesize);
895 btrfs_set_stack_inode_mode(&inode_item, S_IFDIR | 0755);
896 btrfs_set_stack_timespec_sec(&inode_item.atime, now);
897 btrfs_set_stack_timespec_nsec(&inode_item.atime, 0);
898 btrfs_set_stack_timespec_sec(&inode_item.ctime, now);
899 btrfs_set_stack_timespec_nsec(&inode_item.ctime, 0);
900 btrfs_set_stack_timespec_sec(&inode_item.mtime, now);
901 btrfs_set_stack_timespec_nsec(&inode_item.mtime, 0);
902 btrfs_set_stack_timespec_sec(&inode_item.otime, 0);
903 btrfs_set_stack_timespec_nsec(&inode_item.otime, 0);
905 if (root->fs_info->tree_root == root)
906 btrfs_set_super_root_dir(root->fs_info->super_copy, objectid);
908 ret = btrfs_insert_inode(trans, root, objectid, &inode_item);
912 ret = btrfs_insert_inode_ref(trans, root, "..", 2, objectid, objectid, 0);
916 btrfs_set_root_dirid(&root->root_item, objectid);
923 * checks if a path is a block device node
924 * Returns negative errno on failure, otherwise
925 * returns 1 for blockdev, 0 for not-blockdev
927 int is_block_device(const char *path)
931 if (stat(path, &statbuf) < 0)
934 return S_ISBLK(statbuf.st_mode);
938 * check if given path is a mount point
939 * return 1 if yes. 0 if no. -1 for error
941 int is_mount_point(const char *path)
947 f = setmntent("/proc/self/mounts", "r");
951 while ((mnt = getmntent(f)) != NULL) {
952 if (strcmp(mnt->mnt_dir, path))
961 static int is_reg_file(const char *path)
965 if (stat(path, &statbuf) < 0)
967 return S_ISREG(statbuf.st_mode);
971 * This function checks if the given input parameter is
973 * return <0 : some error in the given input
974 * return BTRFS_ARG_UNKNOWN: unknown input
975 * return BTRFS_ARG_UUID: given input is uuid
976 * return BTRFS_ARG_MNTPOINT: given input is path
977 * return BTRFS_ARG_REG: given input is regular file
979 int check_arg_type(const char *input)
987 if (realpath(input, path)) {
988 if (is_block_device(path) == 1)
989 return BTRFS_ARG_BLKDEV;
991 if (is_mount_point(path) == 1)
992 return BTRFS_ARG_MNTPOINT;
994 if (is_reg_file(path))
995 return BTRFS_ARG_REG;
997 return BTRFS_ARG_UNKNOWN;
1000 if (strlen(input) == (BTRFS_UUID_UNPARSED_SIZE - 1) &&
1001 !uuid_parse(input, uuid))
1002 return BTRFS_ARG_UUID;
1004 return BTRFS_ARG_UNKNOWN;
1008 * Find the mount point for a mounted device.
1009 * On success, returns 0 with mountpoint in *mp.
1010 * On failure, returns -errno (not mounted yields -EINVAL)
1011 * Is noisy on failures, expects to be given a mounted device.
1013 int get_btrfs_mount(const char *dev, char *mp, size_t mp_size)
1018 ret = is_block_device(dev);
1021 fprintf(stderr, "%s is not a block device\n", dev);
1024 fprintf(stderr, "Could not check %s: %s\n",
1025 dev, strerror(-ret));
1030 fd = open(dev, O_RDONLY);
1033 fprintf(stderr, "Could not open %s: %s\n", dev, strerror(errno));
1037 ret = check_mounted_where(fd, dev, mp, mp_size, NULL);
1040 } else { /* mounted, all good */
1050 * Given a pathname, return a filehandle to:
1051 * the original pathname or,
1052 * if the pathname is a mounted btrfs device, to its mountpoint.
1054 * On error, return -1, errno should be set.
1056 int open_path_or_dev_mnt(const char *path, DIR **dirstream)
1058 char mp[BTRFS_PATH_NAME_MAX + 1];
1061 if (is_block_device(path)) {
1064 ret = get_btrfs_mount(path, mp, sizeof(mp));
1066 /* not a mounted btrfs dev */
1070 fdmnt = open_file_or_dir(mp, dirstream);
1072 fdmnt = open_file_or_dir(path, dirstream);
1078 /* checks if a device is a loop device */
1079 static int is_loop_device (const char* device) {
1080 struct stat statbuf;
1082 if(stat(device, &statbuf) < 0)
1085 return (S_ISBLK(statbuf.st_mode) &&
1086 MAJOR(statbuf.st_rdev) == LOOP_MAJOR);
1090 /* Takes a loop device path (e.g. /dev/loop0) and returns
1091 * the associated file (e.g. /images/my_btrfs.img) */
1092 static int resolve_loop_device(const char* loop_dev, char* loop_file,
1099 char real_loop_dev[PATH_MAX];
1101 if (!realpath(loop_dev, real_loop_dev))
1103 snprintf(p, PATH_MAX, "/sys/block/%s/loop/backing_file", strrchr(real_loop_dev, '/'));
1104 if (!(f = fopen(p, "r")))
1107 snprintf(fmt, 20, "%%%i[^\n]", max_len-1);
1108 ret = fscanf(f, fmt, loop_file);
1117 * Checks whether a and b are identical or device
1118 * files associated with the same block device
1120 static int is_same_blk_file(const char* a, const char* b)
1122 struct stat st_buf_a, st_buf_b;
1123 char real_a[PATH_MAX];
1124 char real_b[PATH_MAX];
1126 if (!realpath(a, real_a))
1127 strncpy_null(real_a, a);
1129 if (!realpath(b, real_b))
1130 strncpy_null(real_b, b);
1132 /* Identical path? */
1133 if (strcmp(real_a, real_b) == 0)
1136 if (stat(a, &st_buf_a) < 0 || stat(b, &st_buf_b) < 0) {
1137 if (errno == ENOENT)
1142 /* Same blockdevice? */
1143 if (S_ISBLK(st_buf_a.st_mode) && S_ISBLK(st_buf_b.st_mode) &&
1144 st_buf_a.st_rdev == st_buf_b.st_rdev) {
1149 if (st_buf_a.st_dev == st_buf_b.st_dev &&
1150 st_buf_a.st_ino == st_buf_b.st_ino) {
1157 /* checks if a and b are identical or device
1158 * files associated with the same block device or
1159 * if one file is a loop device that uses the other
1162 static int is_same_loop_file(const char* a, const char* b)
1164 char res_a[PATH_MAX];
1165 char res_b[PATH_MAX];
1166 const char* final_a = NULL;
1167 const char* final_b = NULL;
1170 /* Resolve a if it is a loop device */
1171 if((ret = is_loop_device(a)) < 0) {
1176 ret = resolve_loop_device(a, res_a, sizeof(res_a));
1187 /* Resolve b if it is a loop device */
1188 if ((ret = is_loop_device(b)) < 0) {
1193 ret = resolve_loop_device(b, res_b, sizeof(res_b));
1204 return is_same_blk_file(final_a, final_b);
1207 /* Checks if a file exists and is a block or regular file*/
1208 static int is_existing_blk_or_reg_file(const char* filename)
1212 if(stat(filename, &st_buf) < 0) {
1219 return (S_ISBLK(st_buf.st_mode) || S_ISREG(st_buf.st_mode));
1222 /* Checks if a file is used (directly or indirectly via a loop device)
1223 * by a device in fs_devices
1225 static int blk_file_in_dev_list(struct btrfs_fs_devices* fs_devices,
1229 struct list_head *head;
1230 struct list_head *cur;
1231 struct btrfs_device *device;
1233 head = &fs_devices->devices;
1234 list_for_each(cur, head) {
1235 device = list_entry(cur, struct btrfs_device, dev_list);
1237 if((ret = is_same_loop_file(device->name, file)))
1245 * Resolve a pathname to a device mapper node to /dev/mapper/<name>
1246 * Returns NULL on invalid input or malloc failure; Other failures
1247 * will be handled by the caller using the input pathame.
1249 char *canonicalize_dm_name(const char *ptname)
1253 char path[PATH_MAX], name[PATH_MAX], *res = NULL;
1255 if (!ptname || !*ptname)
1258 snprintf(path, sizeof(path), "/sys/block/%s/dm/name", ptname);
1259 if (!(f = fopen(path, "r")))
1262 /* read <name>\n from sysfs */
1263 if (fgets(name, sizeof(name), f) && (sz = strlen(name)) > 1) {
1264 name[sz - 1] = '\0';
1265 snprintf(path, sizeof(path), "/dev/mapper/%s", name);
1267 if (access(path, F_OK) == 0)
1275 * Resolve a pathname to a canonical device node, e.g. /dev/sda1 or
1276 * to a device mapper pathname.
1277 * Returns NULL on invalid input or malloc failure; Other failures
1278 * will be handled by the caller using the input pathame.
1280 char *canonicalize_path(const char *path)
1282 char *canonical, *p;
1284 if (!path || !*path)
1287 canonical = realpath(path, NULL);
1289 return strdup(path);
1290 p = strrchr(canonical, '/');
1291 if (p && strncmp(p, "/dm-", 4) == 0 && isdigit(*(p + 4))) {
1292 char *dm = canonicalize_dm_name(p + 1);
1303 * returns 1 if the device was mounted, < 0 on error or 0 if everything
1304 * is safe to continue.
1306 int check_mounted(const char* file)
1311 fd = open(file, O_RDONLY);
1313 fprintf (stderr, "check_mounted(): Could not open %s\n", file);
1317 ret = check_mounted_where(fd, file, NULL, 0, NULL);
1323 int check_mounted_where(int fd, const char *file, char *where, int size,
1324 struct btrfs_fs_devices **fs_dev_ret)
1329 struct btrfs_fs_devices *fs_devices_mnt = NULL;
1333 /* scan the initial device */
1334 ret = btrfs_scan_one_device(fd, file, &fs_devices_mnt,
1335 &total_devs, BTRFS_SUPER_INFO_OFFSET, 0);
1336 is_btrfs = (ret >= 0);
1338 /* scan other devices */
1339 if (is_btrfs && total_devs > 1) {
1340 ret = btrfs_scan_lblkid();
1345 /* iterate over the list of currently mountes filesystems */
1346 if ((f = setmntent ("/proc/self/mounts", "r")) == NULL)
1349 while ((mnt = getmntent (f)) != NULL) {
1351 if(strcmp(mnt->mnt_type, "btrfs") != 0)
1354 ret = blk_file_in_dev_list(fs_devices_mnt, mnt->mnt_fsname);
1356 /* ignore entries in the mount table that are not
1357 associated with a file*/
1358 if((ret = is_existing_blk_or_reg_file(mnt->mnt_fsname)) < 0)
1359 goto out_mntloop_err;
1363 ret = is_same_loop_file(file, mnt->mnt_fsname);
1367 goto out_mntloop_err;
1372 /* Did we find an entry in mnt table? */
1373 if (mnt && size && where) {
1374 strncpy(where, mnt->mnt_dir, size);
1378 *fs_dev_ret = fs_devices_mnt;
1380 ret = (mnt != NULL);
1388 struct pending_dir {
1389 struct list_head list;
1390 char name[PATH_MAX];
1393 int btrfs_register_one_device(const char *fname)
1395 struct btrfs_ioctl_vol_args args;
1400 fd = open("/dev/btrfs-control", O_RDWR);
1402 fprintf(stderr, "failed to open /dev/btrfs-control "
1403 "skipping device registration: %s\n",
1407 strncpy(args.name, fname, BTRFS_PATH_NAME_MAX);
1408 args.name[BTRFS_PATH_NAME_MAX-1] = 0;
1409 ret = ioctl(fd, BTRFS_IOC_SCAN_DEV, &args);
1412 fprintf(stderr, "ERROR: device scan failed '%s' - %s\n",
1413 fname, strerror(e));
1421 * Register all devices in the fs_uuid list created in the user
1422 * space. Ensure btrfs_scan_lblkid() is called before this func.
1424 int btrfs_register_all_devices(void)
1427 struct btrfs_fs_devices *fs_devices;
1428 struct btrfs_device *device;
1429 struct list_head *all_uuids;
1431 all_uuids = btrfs_scanned_uuids();
1433 list_for_each_entry(fs_devices, all_uuids, list) {
1434 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1435 if (strlen(device->name) != 0) {
1436 err = btrfs_register_one_device(device->name);
1447 int btrfs_device_already_in_root(struct btrfs_root *root, int fd,
1450 struct btrfs_super_block *disk_super;
1454 buf = malloc(BTRFS_SUPER_INFO_SIZE);
1459 ret = pread(fd, buf, BTRFS_SUPER_INFO_SIZE, super_offset);
1460 if (ret != BTRFS_SUPER_INFO_SIZE)
1464 disk_super = (struct btrfs_super_block *)buf;
1465 if (btrfs_super_magic(disk_super) != BTRFS_MAGIC)
1468 if (!memcmp(disk_super->fsid, root->fs_info->super_copy->fsid,
1477 static const char* unit_suffix_binary[] =
1478 { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"};
1479 static const char* unit_suffix_decimal[] =
1480 { "B", "kB", "MB", "GB", "TB", "PB", "EB"};
1482 int pretty_size_snprintf(u64 size, char *str, size_t str_size, unsigned unit_mode)
1488 const char** suffix = NULL;
1494 if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_RAW) {
1495 snprintf(str, str_size, "%llu", size);
1499 if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_BINARY) {
1502 suffix = unit_suffix_binary;
1503 } else if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_DECIMAL) {
1506 suffix = unit_suffix_decimal;
1511 fprintf(stderr, "INTERNAL ERROR: unknown unit base, mode %d\n",
1519 switch (unit_mode & UNITS_MODE_MASK) {
1520 case UNITS_TBYTES: base *= mult; num_divs++;
1521 case UNITS_GBYTES: base *= mult; num_divs++;
1522 case UNITS_MBYTES: base *= mult; num_divs++;
1523 case UNITS_KBYTES: num_divs++;
1530 while (size >= mult) {
1537 if (num_divs >= ARRAY_SIZE(unit_suffix_binary)) {
1539 printf("INTERNAL ERROR: unsupported unit suffix, index %d\n",
1544 fraction = (float)last_size / base;
1546 return snprintf(str, str_size, "%.2f%s", fraction, suffix[num_divs]);
1550 * __strncpy__null - strncpy with null termination
1551 * @dest: the target array
1552 * @src: the source string
1553 * @n: maximum bytes to copy (size of *dest)
1555 * Like strncpy, but ensures destination is null-terminated.
1557 * Copies the string pointed to by src, including the terminating null
1558 * byte ('\0'), to the buffer pointed to by dest, up to a maximum
1559 * of n bytes. Then ensure that dest is null-terminated.
1561 char *__strncpy__null(char *dest, const char *src, size_t n)
1563 strncpy(dest, src, n);
1570 * Checks to make sure that the label matches our requirements.
1572 0 if everything is safe and usable
1573 -1 if the label is too long
1575 static int check_label(const char *input)
1577 int len = strlen(input);
1579 if (len > BTRFS_LABEL_SIZE - 1) {
1580 fprintf(stderr, "ERROR: Label %s is too long (max %d)\n",
1581 input, BTRFS_LABEL_SIZE - 1);
1588 static int set_label_unmounted(const char *dev, const char *label)
1590 struct btrfs_trans_handle *trans;
1591 struct btrfs_root *root;
1594 ret = check_mounted(dev);
1596 fprintf(stderr, "FATAL: error checking %s mount status\n", dev);
1600 fprintf(stderr, "ERROR: dev %s is mounted, use mount point\n",
1605 /* Open the super_block at the default location
1606 * and as read-write.
1608 root = open_ctree(dev, 0, OPEN_CTREE_WRITES);
1609 if (!root) /* errors are printed by open_ctree() */
1612 trans = btrfs_start_transaction(root, 1);
1613 snprintf(root->fs_info->super_copy->label, BTRFS_LABEL_SIZE, "%s",
1615 btrfs_commit_transaction(trans, root);
1617 /* Now we close it since we are done. */
1622 static int set_label_mounted(const char *mount_path, const char *label)
1626 fd = open(mount_path, O_RDONLY | O_NOATIME);
1628 fprintf(stderr, "ERROR: unable to access '%s'\n", mount_path);
1632 if (ioctl(fd, BTRFS_IOC_SET_FSLABEL, label) < 0) {
1633 fprintf(stderr, "ERROR: unable to set label %s\n",
1643 static int get_label_unmounted(const char *dev, char *label)
1645 struct btrfs_root *root;
1648 ret = check_mounted(dev);
1650 fprintf(stderr, "FATAL: error checking %s mount status\n", dev);
1654 fprintf(stderr, "ERROR: dev %s is mounted, use mount point\n",
1659 /* Open the super_block at the default location
1662 root = open_ctree(dev, 0, 0);
1666 memcpy(label, root->fs_info->super_copy->label, BTRFS_LABEL_SIZE);
1668 /* Now we close it since we are done. */
1674 * If a partition is mounted, try to get the filesystem label via its
1675 * mounted path rather than device. Return the corresponding error
1676 * the user specified the device path.
1678 int get_label_mounted(const char *mount_path, char *labelp)
1680 char label[BTRFS_LABEL_SIZE];
1683 fd = open(mount_path, O_RDONLY | O_NOATIME);
1685 fprintf(stderr, "ERROR: unable to access '%s'\n", mount_path);
1689 memset(label, '\0', sizeof(label));
1690 if (ioctl(fd, BTRFS_IOC_GET_FSLABEL, label) < 0) {
1691 fprintf(stderr, "ERROR: unable get label %s\n", strerror(errno));
1696 strncpy(labelp, label, sizeof(label));
1701 int get_label(const char *btrfs_dev, char *label)
1705 ret = is_existing_blk_or_reg_file(btrfs_dev);
1707 ret = get_label_mounted(btrfs_dev, label);
1709 ret = get_label_unmounted(btrfs_dev, label);
1714 int set_label(const char *btrfs_dev, const char *label)
1718 if (check_label(label))
1721 ret = is_existing_blk_or_reg_file(btrfs_dev);
1723 ret = set_label_mounted(btrfs_dev, label);
1725 ret = set_label_unmounted(btrfs_dev, label);
1731 * Unsafe subvolume check.
1733 * This only checks ino == BTRFS_FIRST_FREE_OBJECTID, even it is not in a
1734 * btrfs mount point.
1735 * Must use together with other reliable method like btrfs ioctl.
1737 static int __is_subvol(const char *path)
1742 ret = lstat(path, &st);
1746 return st.st_ino == BTRFS_FIRST_FREE_OBJECTID;
1750 * A not-so-good version fls64. No fascinating optimization since
1751 * no one except parse_size use it
1753 static int fls64(u64 x)
1757 for (i = 0; i <64; i++)
1758 if (x << i & (1ULL << 63))
1763 u64 parse_size(char *s)
1771 fprintf(stderr, "ERROR: Size value is empty\n");
1776 "ERROR: Size value '%s' is less equal than 0\n", s);
1779 ret = strtoull(s, &endptr, 10);
1781 fprintf(stderr, "ERROR: Size value '%s' is invalid\n", s);
1784 if (endptr[0] && endptr[1]) {
1785 fprintf(stderr, "ERROR: Illegal suffix contains character '%c' in wrong position\n",
1790 * strtoll returns LLONG_MAX when overflow, if this happens,
1791 * need to call strtoull to get the real size
1793 if (errno == ERANGE && ret == ULLONG_MAX) {
1795 "ERROR: Size value '%s' is too large for u64\n", s);
1799 c = tolower(endptr[0]);
1822 fprintf(stderr, "ERROR: Unknown size descriptor '%c'\n",
1827 /* Check whether ret * mult overflow */
1828 if (fls64(ret) + fls64(mult) - 1 > 64) {
1830 "ERROR: Size value '%s' is too large for u64\n", s);
1837 u64 parse_qgroupid(const char *p)
1839 char *s = strchr(p, '/');
1840 const char *ptr_src_end = p + strlen(p);
1841 char *ptr_parse_end = NULL;
1850 /* Numeric format like '0/257' is the primary case */
1852 id = strtoull(p, &ptr_parse_end, 10);
1853 if (ptr_parse_end != ptr_src_end)
1857 level = strtoull(p, &ptr_parse_end, 10);
1858 if (ptr_parse_end != s)
1861 id = strtoull(s + 1, &ptr_parse_end, 10);
1862 if (ptr_parse_end != ptr_src_end)
1865 return (level << BTRFS_QGROUP_LEVEL_SHIFT) | id;
1868 /* Path format like subv at 'my_subvol' is the fallback case */
1869 ret = __is_subvol(p);
1870 if (ret < 0 || !ret)
1872 fd = open(p, O_RDONLY);
1875 ret = lookup_ino_rootid(fd, &id);
1882 fprintf(stderr, "ERROR: invalid qgroupid or subvolume path: %s\n", p);
1886 int open_file_or_dir3(const char *fname, DIR **dirstream, int open_flags)
1892 ret = stat(fname, &st);
1896 if (S_ISDIR(st.st_mode)) {
1897 *dirstream = opendir(fname);
1900 fd = dirfd(*dirstream);
1901 } else if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
1902 fd = open(fname, open_flags);
1905 * we set this on purpose, in case the caller output
1906 * strerror(errno) as success
1914 closedir(*dirstream);
1919 int open_file_or_dir(const char *fname, DIR **dirstream)
1921 return open_file_or_dir3(fname, dirstream, O_RDWR);
1924 void close_file_or_dir(int fd, DIR *dirstream)
1927 closedir(dirstream);
1932 int get_device_info(int fd, u64 devid,
1933 struct btrfs_ioctl_dev_info_args *di_args)
1937 di_args->devid = devid;
1938 memset(&di_args->uuid, '\0', sizeof(di_args->uuid));
1940 ret = ioctl(fd, BTRFS_IOC_DEV_INFO, di_args);
1941 return ret ? -errno : 0;
1944 static u64 find_max_device_id(struct btrfs_ioctl_search_args *search_args,
1947 struct btrfs_dev_item *dev_item;
1948 char *buf = search_args->buf;
1950 buf += (nr_items - 1) * (sizeof(struct btrfs_ioctl_search_header)
1951 + sizeof(struct btrfs_dev_item));
1952 buf += sizeof(struct btrfs_ioctl_search_header);
1954 dev_item = (struct btrfs_dev_item *)buf;
1956 return btrfs_stack_device_id(dev_item);
1959 static int search_chunk_tree_for_fs_info(int fd,
1960 struct btrfs_ioctl_fs_info_args *fi_args)
1964 u64 start_devid = 1;
1965 struct btrfs_ioctl_search_args search_args;
1966 struct btrfs_ioctl_search_key *search_key = &search_args.key;
1968 fi_args->num_devices = 0;
1970 max_items = BTRFS_SEARCH_ARGS_BUFSIZE
1971 / (sizeof(struct btrfs_ioctl_search_header)
1972 + sizeof(struct btrfs_dev_item));
1974 search_key->tree_id = BTRFS_CHUNK_TREE_OBJECTID;
1975 search_key->min_objectid = BTRFS_DEV_ITEMS_OBJECTID;
1976 search_key->max_objectid = BTRFS_DEV_ITEMS_OBJECTID;
1977 search_key->min_type = BTRFS_DEV_ITEM_KEY;
1978 search_key->max_type = BTRFS_DEV_ITEM_KEY;
1979 search_key->min_transid = 0;
1980 search_key->max_transid = (u64)-1;
1981 search_key->nr_items = max_items;
1982 search_key->max_offset = (u64)-1;
1985 search_key->min_offset = start_devid;
1987 ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH, &search_args);
1991 fi_args->num_devices += (u64)search_key->nr_items;
1993 if (search_key->nr_items == max_items) {
1994 start_devid = find_max_device_id(&search_args,
1995 search_key->nr_items) + 1;
1999 /* get the lastest max_id to stay consistent with the num_devices */
2000 if (search_key->nr_items == 0)
2002 * last tree_search returns an empty buf, use the devid of
2003 * the last dev_item of the previous tree_search
2005 fi_args->max_id = start_devid - 1;
2007 fi_args->max_id = find_max_device_id(&search_args,
2008 search_key->nr_items);
2014 * For a given path, fill in the ioctl fs_ and info_ args.
2015 * If the path is a btrfs mountpoint, fill info for all devices.
2016 * If the path is a btrfs device, fill in only that device.
2018 * The path provided must be either on a mounted btrfs fs,
2019 * or be a mounted btrfs device.
2021 * Returns 0 on success, or a negative errno.
2023 int get_fs_info(char *path, struct btrfs_ioctl_fs_info_args *fi_args,
2024 struct btrfs_ioctl_dev_info_args **di_ret)
2031 struct btrfs_fs_devices *fs_devices_mnt = NULL;
2032 struct btrfs_ioctl_dev_info_args *di_args;
2033 struct btrfs_ioctl_dev_info_args tmp;
2034 char mp[BTRFS_PATH_NAME_MAX + 1];
2035 DIR *dirstream = NULL;
2037 memset(fi_args, 0, sizeof(*fi_args));
2039 if (is_block_device(path)) {
2040 struct btrfs_super_block *disk_super;
2041 char buf[BTRFS_SUPER_INFO_SIZE];
2044 /* Ensure it's mounted, then set path to the mountpoint */
2045 fd = open(path, O_RDONLY);
2048 fprintf(stderr, "Couldn't open %s: %s\n",
2049 path, strerror(errno));
2052 ret = check_mounted_where(fd, path, mp, sizeof(mp),
2061 /* Only fill in this one device */
2062 fi_args->num_devices = 1;
2064 disk_super = (struct btrfs_super_block *)buf;
2065 ret = btrfs_read_dev_super(fd, disk_super,
2066 BTRFS_SUPER_INFO_OFFSET, 0);
2071 devid = btrfs_stack_device_id(&disk_super->dev_item);
2073 fi_args->max_id = devid;
2076 memcpy(fi_args->fsid, fs_devices_mnt->fsid, BTRFS_FSID_SIZE);
2080 /* at this point path must not be for a block device */
2081 fd = open_file_or_dir(path, &dirstream);
2087 /* fill in fi_args if not just a single device */
2088 if (fi_args->num_devices != 1) {
2089 ret = ioctl(fd, BTRFS_IOC_FS_INFO, fi_args);
2096 * The fs_args->num_devices does not include seed devices
2098 ret = search_chunk_tree_for_fs_info(fd, fi_args);
2103 * search_chunk_tree_for_fs_info() will lacks the devid 0
2104 * so manual probe for it here.
2106 ret = get_device_info(fd, 0, &tmp);
2108 fi_args->num_devices++;
2116 if (!fi_args->num_devices)
2119 di_args = *di_ret = malloc((fi_args->num_devices) * sizeof(*di_args));
2126 memcpy(di_args, &tmp, sizeof(tmp));
2127 for (; i <= fi_args->max_id; ++i) {
2128 ret = get_device_info(fd, i, &di_args[ndevs]);
2137 * only when the only dev we wanted to find is not there then
2138 * let any error be returned
2140 if (fi_args->num_devices != 1) {
2146 close_file_or_dir(fd, dirstream);
2150 #define isoctal(c) (((c) & ~7) == '0')
2152 static inline void translate(char *f, char *t)
2154 while (*f != '\0') {
2156 isoctal(f[1]) && isoctal(f[2]) && isoctal(f[3])) {
2157 *t++ = 64*(f[1] & 7) + 8*(f[2] & 7) + (f[3] & 7);
2167 * Checks if the swap device.
2168 * Returns 1 if swap device, < 0 on error or 0 if not swap device.
2170 static int is_swap_device(const char *file)
2181 if (stat(file, &st_buf) < 0)
2183 if (S_ISBLK(st_buf.st_mode))
2184 dev = st_buf.st_rdev;
2185 else if (S_ISREG(st_buf.st_mode)) {
2186 dev = st_buf.st_dev;
2187 ino = st_buf.st_ino;
2191 if ((f = fopen("/proc/swaps", "r")) == NULL)
2194 /* skip the first line */
2195 if (fgets(tmp, sizeof(tmp), f) == NULL)
2198 while (fgets(tmp, sizeof(tmp), f) != NULL) {
2199 if ((cp = strchr(tmp, ' ')) != NULL)
2201 if ((cp = strchr(tmp, '\t')) != NULL)
2203 translate(tmp, buf);
2204 if (stat(buf, &st_buf) != 0)
2206 if (S_ISBLK(st_buf.st_mode)) {
2207 if (dev == st_buf.st_rdev) {
2211 } else if (S_ISREG(st_buf.st_mode)) {
2212 if (dev == st_buf.st_dev && ino == st_buf.st_ino) {
2226 * Check for existing filesystem or partition table on device.
2228 * 1 for existing fs or partition
2229 * 0 for nothing found
2230 * -1 for internal error
2237 blkid_probe pr = NULL;
2241 if (!device || !*device)
2244 ret = -1; /* will reset on success of all setup calls */
2246 pr = blkid_new_probe_from_filename(device);
2250 size = blkid_probe_get_size(pr);
2254 /* nothing to overwrite on a 0-length device */
2260 ret = blkid_probe_enable_partitions(pr, 1);
2264 ret = blkid_do_fullprobe(pr);
2269 * Blkid returns 1 for nothing found and 0 when it finds a signature,
2270 * but we want the exact opposite, so reverse the return value here.
2272 * In addition print some useful diagnostics about what actually is
2280 if (!blkid_probe_lookup_value(pr, "TYPE", &type, NULL)) {
2282 "%s appears to contain an existing "
2283 "filesystem (%s).\n", device, type);
2284 } else if (!blkid_probe_lookup_value(pr, "PTTYPE", &type, NULL)) {
2286 "%s appears to contain a partition "
2287 "table (%s).\n", device, type);
2290 "%s appears to contain something weird "
2291 "according to blkid\n", device);
2297 blkid_free_probe(pr);
2300 "probe of %s failed, cannot detect "
2301 "existing filesystem.\n", device);
2305 static int group_profile_devs_min(u64 flag)
2307 switch (flag & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
2308 case 0: /* single */
2309 case BTRFS_BLOCK_GROUP_DUP:
2311 case BTRFS_BLOCK_GROUP_RAID0:
2312 case BTRFS_BLOCK_GROUP_RAID1:
2313 case BTRFS_BLOCK_GROUP_RAID5:
2315 case BTRFS_BLOCK_GROUP_RAID6:
2317 case BTRFS_BLOCK_GROUP_RAID10:
2324 int test_num_disk_vs_raid(u64 metadata_profile, u64 data_profile,
2325 u64 dev_cnt, int mixed, char *estr)
2333 allowed |= BTRFS_BLOCK_GROUP_RAID10;
2335 allowed |= BTRFS_BLOCK_GROUP_RAID6;
2337 allowed |= BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
2338 BTRFS_BLOCK_GROUP_RAID5;
2341 allowed |= BTRFS_BLOCK_GROUP_DUP;
2345 ((metadata_profile | data_profile) & BTRFS_BLOCK_GROUP_DUP)) {
2347 "DUP is not allowed when FS has multiple devices\n");
2350 if (metadata_profile & ~allowed) {
2352 "unable to create FS with metadata profile %s "
2353 "(have %llu devices but %d devices are required)\n",
2354 btrfs_group_profile_str(metadata_profile), dev_cnt,
2355 group_profile_devs_min(metadata_profile));
2358 if (data_profile & ~allowed) {
2360 "unable to create FS with data profile %s "
2361 "(have %llu devices but %d devices are required)\n",
2362 btrfs_group_profile_str(data_profile), dev_cnt,
2363 group_profile_devs_min(data_profile));
2367 if (!mixed && (data_profile & BTRFS_BLOCK_GROUP_DUP)) {
2369 "dup for data is allowed only in mixed mode");
2375 int group_profile_max_safe_loss(u64 flags)
2377 switch (flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
2378 case 0: /* single */
2379 case BTRFS_BLOCK_GROUP_DUP:
2380 case BTRFS_BLOCK_GROUP_RAID0:
2382 case BTRFS_BLOCK_GROUP_RAID1:
2383 case BTRFS_BLOCK_GROUP_RAID5:
2384 case BTRFS_BLOCK_GROUP_RAID10:
2386 case BTRFS_BLOCK_GROUP_RAID6:
2393 /* Check if disk is suitable for btrfs
2395 * 1: something is wrong, estr provides the error
2398 int test_dev_for_mkfs(char *file, int force_overwrite, char *estr)
2404 ret = is_swap_device(file);
2406 snprintf(estr, sz, "error checking %s status: %s\n", file,
2411 snprintf(estr, sz, "%s is a swap device\n", file);
2414 if (!force_overwrite) {
2415 if (check_overwrite(file)) {
2416 snprintf(estr, sz, "Use the -f option to force overwrite.\n");
2420 ret = check_mounted(file);
2422 snprintf(estr, sz, "error checking %s mount status\n",
2427 snprintf(estr, sz, "%s is mounted\n", file);
2430 /* check if the device is busy */
2431 fd = open(file, O_RDWR|O_EXCL);
2433 snprintf(estr, sz, "unable to open %s: %s\n", file,
2437 if (fstat(fd, &st)) {
2438 snprintf(estr, sz, "unable to stat %s: %s\n", file,
2443 if (!S_ISBLK(st.st_mode)) {
2444 fprintf(stderr, "'%s' is not a block device\n", file);
2452 int btrfs_scan_lblkid()
2457 struct btrfs_fs_devices *tmp_devices;
2458 blkid_dev_iterate iter = NULL;
2459 blkid_dev dev = NULL;
2460 blkid_cache cache = NULL;
2461 char path[PATH_MAX];
2463 if (btrfs_scan_done)
2466 if (blkid_get_cache(&cache, 0) < 0) {
2467 printf("ERROR: lblkid cache get failed\n");
2470 blkid_probe_all(cache);
2471 iter = blkid_dev_iterate_begin(cache);
2472 blkid_dev_set_search(iter, "TYPE", "btrfs");
2473 while (blkid_dev_next(iter, &dev) == 0) {
2474 dev = blkid_verify(cache, dev);
2477 /* if we are here its definitely a btrfs disk*/
2478 strncpy_null(path, blkid_dev_devname(dev));
2480 fd = open(path, O_RDONLY);
2482 printf("ERROR: could not open %s\n", path);
2485 ret = btrfs_scan_one_device(fd, path, &tmp_devices,
2486 &num_devices, BTRFS_SUPER_INFO_OFFSET, 0);
2488 printf("ERROR: could not scan %s\n", path);
2495 blkid_dev_iterate_end(iter);
2496 blkid_put_cache(cache);
2498 btrfs_scan_done = 1;
2503 int is_vol_small(char *file)
2510 fd = open(file, O_RDONLY);
2513 if (fstat(fd, &st) < 0) {
2518 size = btrfs_device_size(fd, &st);
2523 if (size < BTRFS_MKFS_SMALL_VOLUME_SIZE) {
2533 * This reads a line from the stdin and only returns non-zero if the
2534 * first whitespace delimited token is a case insensitive match with yes
2537 int ask_user(char *question)
2539 char buf[30] = {0,};
2540 char *saveptr = NULL;
2543 printf("%s [y/N]: ", question);
2545 return fgets(buf, sizeof(buf) - 1, stdin) &&
2546 (answer = strtok_r(buf, " \t\n\r", &saveptr)) &&
2547 (!strcasecmp(answer, "yes") || !strcasecmp(answer, "y"));
2552 * - file or directory return the containing tree root id
2553 * - subvolume return its own tree id
2554 * - BTRFS_EMPTY_SUBVOL_DIR_OBJECTID (directory with ino == 2) the result is
2555 * undefined and function returns -1
2557 int lookup_ino_rootid(int fd, u64 *rootid)
2559 struct btrfs_ioctl_ino_lookup_args args;
2563 memset(&args, 0, sizeof(args));
2565 args.objectid = BTRFS_FIRST_FREE_OBJECTID;
2567 ret = ioctl(fd, BTRFS_IOC_INO_LOOKUP, &args);
2570 fprintf(stderr, "ERROR: Failed to lookup root id - %s\n",
2575 *rootid = args.treeid;
2581 * return 0 if a btrfs mount point is found
2582 * return 1 if a mount point is found but not btrfs
2583 * return <0 if something goes wrong
2585 int find_mount_root(const char *path, char **mount_root)
2593 int longest_matchlen = 0;
2594 char *longest_match = NULL;
2596 fd = open(path, O_RDONLY | O_NOATIME);
2601 mnttab = setmntent("/proc/self/mounts", "r");
2605 while ((ent = getmntent(mnttab))) {
2606 len = strlen(ent->mnt_dir);
2607 if (strncmp(ent->mnt_dir, path, len) == 0) {
2608 /* match found and use the latest match */
2609 if (longest_matchlen <= len) {
2610 free(longest_match);
2611 longest_matchlen = len;
2612 longest_match = strdup(ent->mnt_dir);
2613 not_btrfs = strcmp(ent->mnt_type, "btrfs");
2622 free(longest_match);
2627 *mount_root = realpath(longest_match, NULL);
2631 free(longest_match);
2635 int test_minimum_size(const char *file, u32 nodesize)
2638 struct stat statbuf;
2640 fd = open(file, O_RDONLY);
2643 if (stat(file, &statbuf) < 0) {
2647 if (btrfs_device_size(fd, &statbuf) < btrfs_min_dev_size(nodesize)) {
2656 * test if name is a correct subvolume name
2657 * this function return
2658 * 0-> name is not a correct subvolume name
2659 * 1-> name is a correct subvolume name
2661 int test_issubvolname(const char *name)
2663 return name[0] != '\0' && !strchr(name, '/') &&
2664 strcmp(name, ".") && strcmp(name, "..");
2668 * test if path is a directory
2669 * this function return
2670 * 0-> path exists but it is not a directory
2671 * 1-> path exists and it is a directory
2672 * -1 -> path is unaccessible
2674 int test_isdir(const char *path)
2679 ret = stat(path, &st);
2683 return S_ISDIR(st.st_mode);
2686 void units_set_mode(unsigned *units, unsigned mode)
2688 unsigned base = *units & UNITS_MODE_MASK;
2690 *units = base | mode;
2693 void units_set_base(unsigned *units, unsigned base)
2695 unsigned mode = *units & ~UNITS_MODE_MASK;
2697 *units = base | mode;
2700 int find_next_key(struct btrfs_path *path, struct btrfs_key *key)
2704 for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2705 if (!path->nodes[level])
2707 if (path->slots[level] + 1 >=
2708 btrfs_header_nritems(path->nodes[level]))
2711 btrfs_item_key_to_cpu(path->nodes[level], key,
2712 path->slots[level] + 1);
2714 btrfs_node_key_to_cpu(path->nodes[level], key,
2715 path->slots[level] + 1);
2721 char* btrfs_group_type_str(u64 flag)
2723 u64 mask = BTRFS_BLOCK_GROUP_TYPE_MASK |
2724 BTRFS_SPACE_INFO_GLOBAL_RSV;
2726 switch (flag & mask) {
2727 case BTRFS_BLOCK_GROUP_DATA:
2729 case BTRFS_BLOCK_GROUP_SYSTEM:
2731 case BTRFS_BLOCK_GROUP_METADATA:
2733 case BTRFS_BLOCK_GROUP_DATA|BTRFS_BLOCK_GROUP_METADATA:
2734 return "Data+Metadata";
2735 case BTRFS_SPACE_INFO_GLOBAL_RSV:
2736 return "GlobalReserve";
2742 char* btrfs_group_profile_str(u64 flag)
2744 switch (flag & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
2747 case BTRFS_BLOCK_GROUP_RAID0:
2749 case BTRFS_BLOCK_GROUP_RAID1:
2751 case BTRFS_BLOCK_GROUP_RAID5:
2753 case BTRFS_BLOCK_GROUP_RAID6:
2755 case BTRFS_BLOCK_GROUP_DUP:
2757 case BTRFS_BLOCK_GROUP_RAID10:
2764 u64 disk_size(char *path)
2768 if (statfs(path, &sfs) < 0)
2771 return sfs.f_bsize * sfs.f_blocks;
2774 u64 get_partition_size(char *dev)
2777 int fd = open(dev, O_RDONLY);
2781 if (ioctl(fd, BLKGETSIZE64, &result) < 0) {
2790 int btrfs_tree_search2_ioctl_supported(int fd)
2792 struct btrfs_ioctl_search_args_v2 *args2;
2793 struct btrfs_ioctl_search_key *sk;
2794 int args2_size = 1024;
2795 char args2_buf[args2_size];
2797 static int v2_supported = -1;
2799 if (v2_supported != -1)
2800 return v2_supported;
2802 args2 = (struct btrfs_ioctl_search_args_v2 *)args2_buf;
2806 * Search for the extent tree item in the root tree.
2808 sk->tree_id = BTRFS_ROOT_TREE_OBJECTID;
2809 sk->min_objectid = BTRFS_EXTENT_TREE_OBJECTID;
2810 sk->max_objectid = BTRFS_EXTENT_TREE_OBJECTID;
2811 sk->min_type = BTRFS_ROOT_ITEM_KEY;
2812 sk->max_type = BTRFS_ROOT_ITEM_KEY;
2814 sk->max_offset = (u64)-1;
2815 sk->min_transid = 0;
2816 sk->max_transid = (u64)-1;
2818 args2->buf_size = args2_size - sizeof(struct btrfs_ioctl_search_args_v2);
2819 ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH_V2, args2);
2820 if (ret == -EOPNOTSUPP)
2827 return v2_supported;
2830 int btrfs_check_nodesize(u32 nodesize, u32 sectorsize)
2832 if (nodesize < sectorsize) {
2834 "ERROR: Illegal nodesize %u (smaller than %u)\n",
2835 nodesize, sectorsize);
2837 } else if (nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
2839 "ERROR: Illegal nodesize %u (larger than %u)\n",
2840 nodesize, BTRFS_MAX_METADATA_BLOCKSIZE);
2842 } else if (nodesize & (sectorsize - 1)) {
2844 "ERROR: Illegal nodesize %u (not aligned to %u)\n",
2845 nodesize, sectorsize);