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.
20 #define _XOPEN_SOURCE 700
21 #define __USE_XOPEN2K8
22 #define __XOPEN2K8 /* due to an error in dirent.h, to get dirfd() */
23 #define _GNU_SOURCE /* O_NOATIME */
27 #include <sys/ioctl.h>
28 #include <sys/mount.h>
29 #include <sys/types.h>
31 #include <uuid/uuid.h>
36 #include <linux/loop.h>
37 #include <linux/major.h>
38 #include <linux/kdev_t.h>
40 #include <blkid/blkid.h>
41 #include "kerncompat.h"
42 #include "radix-tree.h"
45 #include "transaction.h"
52 #define BLKDISCARD _IO(0x12,119)
55 static int btrfs_scan_done = 0;
57 static char argv0_buf[ARGV0_BUF_SIZE] = "btrfs";
59 void fixup_argv0(char **argv, const char *token)
61 int len = strlen(argv0_buf);
63 snprintf(argv0_buf + len, sizeof(argv0_buf) - len, " %s", token);
67 void set_argv0(char **argv)
69 strncpy(argv0_buf, argv[0], sizeof(argv0_buf));
70 argv0_buf[sizeof(argv0_buf) - 1] = 0;
73 int check_argc_exact(int nargs, int expected)
76 fprintf(stderr, "%s: too few arguments\n", argv0_buf);
78 fprintf(stderr, "%s: too many arguments\n", argv0_buf);
80 return nargs != expected;
83 int check_argc_min(int nargs, int expected)
85 if (nargs < expected) {
86 fprintf(stderr, "%s: too few arguments\n", argv0_buf);
93 int check_argc_max(int nargs, int expected)
95 if (nargs > expected) {
96 fprintf(stderr, "%s: too many arguments\n", argv0_buf);
105 * Discard the given range in one go
107 static int discard_range(int fd, u64 start, u64 len)
109 u64 range[2] = { start, len };
111 if (ioctl(fd, BLKDISCARD, &range) < 0)
117 * Discard blocks in the given range in 1G chunks, the process is interruptible
119 static int discard_blocks(int fd, u64 start, u64 len)
123 u64 chunk_size = min_t(u64, len, 1*1024*1024*1024);
126 ret = discard_range(fd, start, chunk_size);
136 static u64 reference_root_table[] = {
137 [1] = BTRFS_ROOT_TREE_OBJECTID,
138 [2] = BTRFS_EXTENT_TREE_OBJECTID,
139 [3] = BTRFS_CHUNK_TREE_OBJECTID,
140 [4] = BTRFS_DEV_TREE_OBJECTID,
141 [5] = BTRFS_FS_TREE_OBJECTID,
142 [6] = BTRFS_CSUM_TREE_OBJECTID,
145 int test_uuid_unique(char *fs_uuid)
148 blkid_dev_iterate iter = NULL;
149 blkid_dev dev = NULL;
150 blkid_cache cache = NULL;
152 if (blkid_get_cache(&cache, 0) < 0) {
153 printf("ERROR: lblkid cache get failed\n");
156 blkid_probe_all(cache);
157 iter = blkid_dev_iterate_begin(cache);
158 blkid_dev_set_search(iter, "UUID", fs_uuid);
160 while (blkid_dev_next(iter, &dev) == 0) {
161 dev = blkid_verify(cache, dev);
168 blkid_dev_iterate_end(iter);
169 blkid_put_cache(cache);
174 int make_btrfs(int fd, const char *device, const char *label, char *fs_uuid,
175 u64 blocks[7], u64 num_bytes, u32 nodesize,
176 u32 leafsize, u32 sectorsize, u32 stripesize, u64 features)
178 struct btrfs_super_block super;
179 struct extent_buffer *buf = NULL;
180 struct btrfs_root_item root_item;
181 struct btrfs_disk_key disk_key;
182 struct btrfs_extent_item *extent_item;
183 struct btrfs_inode_item *inode_item;
184 struct btrfs_chunk *chunk;
185 struct btrfs_dev_item *dev_item;
186 struct btrfs_dev_extent *dev_extent;
187 u8 chunk_tree_uuid[BTRFS_UUID_SIZE];
197 int skinny_metadata = !!(features &
198 BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA);
200 first_free = BTRFS_SUPER_INFO_OFFSET + sectorsize * 2 - 1;
201 first_free &= ~((u64)sectorsize - 1);
203 memset(&super, 0, sizeof(super));
205 num_bytes = (num_bytes / sectorsize) * sectorsize;
207 if (uuid_parse(fs_uuid, super.fsid) != 0) {
208 fprintf(stderr, "could not parse UUID: %s\n", fs_uuid);
212 if (!test_uuid_unique(fs_uuid)) {
213 fprintf(stderr, "non-unique UUID: %s\n", fs_uuid);
218 uuid_generate(super.fsid);
220 uuid_generate(super.dev_item.uuid);
221 uuid_generate(chunk_tree_uuid);
223 btrfs_set_super_bytenr(&super, blocks[0]);
224 btrfs_set_super_num_devices(&super, 1);
225 btrfs_set_super_magic(&super, BTRFS_MAGIC);
226 btrfs_set_super_generation(&super, 1);
227 btrfs_set_super_root(&super, blocks[1]);
228 btrfs_set_super_chunk_root(&super, blocks[3]);
229 btrfs_set_super_total_bytes(&super, num_bytes);
230 btrfs_set_super_bytes_used(&super, 6 * leafsize);
231 btrfs_set_super_sectorsize(&super, sectorsize);
232 btrfs_set_super_leafsize(&super, leafsize);
233 btrfs_set_super_nodesize(&super, nodesize);
234 btrfs_set_super_stripesize(&super, stripesize);
235 btrfs_set_super_csum_type(&super, BTRFS_CSUM_TYPE_CRC32);
236 btrfs_set_super_chunk_root_generation(&super, 1);
237 btrfs_set_super_cache_generation(&super, -1);
238 btrfs_set_super_incompat_flags(&super, features);
240 strncpy(super.label, label, BTRFS_LABEL_SIZE - 1);
242 buf = malloc(sizeof(*buf) + max(sectorsize, leafsize));
244 /* create the tree of root objects */
245 memset(buf->data, 0, leafsize);
247 btrfs_set_header_bytenr(buf, blocks[1]);
248 btrfs_set_header_nritems(buf, 4);
249 btrfs_set_header_generation(buf, 1);
250 btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
251 btrfs_set_header_owner(buf, BTRFS_ROOT_TREE_OBJECTID);
252 write_extent_buffer(buf, super.fsid, btrfs_header_fsid(),
255 write_extent_buffer(buf, chunk_tree_uuid,
256 btrfs_header_chunk_tree_uuid(buf),
259 /* create the items for the root tree */
260 memset(&root_item, 0, sizeof(root_item));
261 inode_item = &root_item.inode;
262 btrfs_set_stack_inode_generation(inode_item, 1);
263 btrfs_set_stack_inode_size(inode_item, 3);
264 btrfs_set_stack_inode_nlink(inode_item, 1);
265 btrfs_set_stack_inode_nbytes(inode_item, leafsize);
266 btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
267 btrfs_set_root_refs(&root_item, 1);
268 btrfs_set_root_used(&root_item, leafsize);
269 btrfs_set_root_generation(&root_item, 1);
271 memset(&disk_key, 0, sizeof(disk_key));
272 btrfs_set_disk_key_type(&disk_key, BTRFS_ROOT_ITEM_KEY);
273 btrfs_set_disk_key_offset(&disk_key, 0);
276 itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize) - sizeof(root_item);
277 btrfs_set_root_bytenr(&root_item, blocks[2]);
278 btrfs_set_disk_key_objectid(&disk_key, BTRFS_EXTENT_TREE_OBJECTID);
279 btrfs_set_item_key(buf, &disk_key, nritems);
280 btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
281 btrfs_set_item_size(buf, btrfs_item_nr(nritems),
283 write_extent_buffer(buf, &root_item, btrfs_item_ptr_offset(buf,
284 nritems), sizeof(root_item));
287 itemoff = itemoff - sizeof(root_item);
288 btrfs_set_root_bytenr(&root_item, blocks[4]);
289 btrfs_set_disk_key_objectid(&disk_key, BTRFS_DEV_TREE_OBJECTID);
290 btrfs_set_item_key(buf, &disk_key, nritems);
291 btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
292 btrfs_set_item_size(buf, btrfs_item_nr(nritems),
294 write_extent_buffer(buf, &root_item,
295 btrfs_item_ptr_offset(buf, nritems),
299 itemoff = itemoff - sizeof(root_item);
300 btrfs_set_root_bytenr(&root_item, blocks[5]);
301 btrfs_set_disk_key_objectid(&disk_key, BTRFS_FS_TREE_OBJECTID);
302 btrfs_set_item_key(buf, &disk_key, nritems);
303 btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
304 btrfs_set_item_size(buf, btrfs_item_nr(nritems),
306 write_extent_buffer(buf, &root_item,
307 btrfs_item_ptr_offset(buf, nritems),
311 itemoff = itemoff - sizeof(root_item);
312 btrfs_set_root_bytenr(&root_item, blocks[6]);
313 btrfs_set_disk_key_objectid(&disk_key, BTRFS_CSUM_TREE_OBJECTID);
314 btrfs_set_item_key(buf, &disk_key, nritems);
315 btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
316 btrfs_set_item_size(buf, btrfs_item_nr(nritems),
318 write_extent_buffer(buf, &root_item,
319 btrfs_item_ptr_offset(buf, nritems),
324 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
325 ret = pwrite(fd, buf->data, leafsize, blocks[1]);
326 if (ret != leafsize) {
327 ret = (ret < 0 ? -errno : -EIO);
331 /* create the items for the extent tree */
332 memset(buf->data+sizeof(struct btrfs_header), 0,
333 leafsize-sizeof(struct btrfs_header));
335 itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize);
336 for (i = 1; i < 7; i++) {
337 item_size = sizeof(struct btrfs_extent_item);
338 if (!skinny_metadata)
339 item_size += sizeof(struct btrfs_tree_block_info);
341 BUG_ON(blocks[i] < first_free);
342 BUG_ON(blocks[i] < blocks[i - 1]);
344 /* create extent item */
345 itemoff -= item_size;
346 btrfs_set_disk_key_objectid(&disk_key, blocks[i]);
347 if (skinny_metadata) {
348 btrfs_set_disk_key_type(&disk_key,
349 BTRFS_METADATA_ITEM_KEY);
350 btrfs_set_disk_key_offset(&disk_key, 0);
352 btrfs_set_disk_key_type(&disk_key,
353 BTRFS_EXTENT_ITEM_KEY);
354 btrfs_set_disk_key_offset(&disk_key, leafsize);
356 btrfs_set_item_key(buf, &disk_key, nritems);
357 btrfs_set_item_offset(buf, btrfs_item_nr(nritems),
359 btrfs_set_item_size(buf, btrfs_item_nr(nritems),
361 extent_item = btrfs_item_ptr(buf, nritems,
362 struct btrfs_extent_item);
363 btrfs_set_extent_refs(buf, extent_item, 1);
364 btrfs_set_extent_generation(buf, extent_item, 1);
365 btrfs_set_extent_flags(buf, extent_item,
366 BTRFS_EXTENT_FLAG_TREE_BLOCK);
369 /* create extent ref */
370 ref_root = reference_root_table[i];
371 btrfs_set_disk_key_objectid(&disk_key, blocks[i]);
372 btrfs_set_disk_key_offset(&disk_key, ref_root);
373 btrfs_set_disk_key_type(&disk_key, BTRFS_TREE_BLOCK_REF_KEY);
374 btrfs_set_item_key(buf, &disk_key, nritems);
375 btrfs_set_item_offset(buf, btrfs_item_nr(nritems),
377 btrfs_set_item_size(buf, btrfs_item_nr(nritems), 0);
380 btrfs_set_header_bytenr(buf, blocks[2]);
381 btrfs_set_header_owner(buf, BTRFS_EXTENT_TREE_OBJECTID);
382 btrfs_set_header_nritems(buf, nritems);
383 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
384 ret = pwrite(fd, buf->data, leafsize, blocks[2]);
385 if (ret != leafsize) {
386 ret = (ret < 0 ? -errno : -EIO);
390 /* create the chunk tree */
391 memset(buf->data+sizeof(struct btrfs_header), 0,
392 leafsize-sizeof(struct btrfs_header));
394 item_size = sizeof(*dev_item);
395 itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize) - item_size;
397 /* first device 1 (there is no device 0) */
398 btrfs_set_disk_key_objectid(&disk_key, BTRFS_DEV_ITEMS_OBJECTID);
399 btrfs_set_disk_key_offset(&disk_key, 1);
400 btrfs_set_disk_key_type(&disk_key, BTRFS_DEV_ITEM_KEY);
401 btrfs_set_item_key(buf, &disk_key, nritems);
402 btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
403 btrfs_set_item_size(buf, btrfs_item_nr(nritems), item_size);
405 dev_item = btrfs_item_ptr(buf, nritems, struct btrfs_dev_item);
406 btrfs_set_device_id(buf, dev_item, 1);
407 btrfs_set_device_generation(buf, dev_item, 0);
408 btrfs_set_device_total_bytes(buf, dev_item, num_bytes);
409 btrfs_set_device_bytes_used(buf, dev_item,
410 BTRFS_MKFS_SYSTEM_GROUP_SIZE);
411 btrfs_set_device_io_align(buf, dev_item, sectorsize);
412 btrfs_set_device_io_width(buf, dev_item, sectorsize);
413 btrfs_set_device_sector_size(buf, dev_item, sectorsize);
414 btrfs_set_device_type(buf, dev_item, 0);
416 write_extent_buffer(buf, super.dev_item.uuid,
417 (unsigned long)btrfs_device_uuid(dev_item),
419 write_extent_buffer(buf, super.fsid,
420 (unsigned long)btrfs_device_fsid(dev_item),
422 read_extent_buffer(buf, &super.dev_item, (unsigned long)dev_item,
426 item_size = btrfs_chunk_item_size(1);
427 itemoff = itemoff - item_size;
429 /* then we have chunk 0 */
430 btrfs_set_disk_key_objectid(&disk_key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
431 btrfs_set_disk_key_offset(&disk_key, 0);
432 btrfs_set_disk_key_type(&disk_key, BTRFS_CHUNK_ITEM_KEY);
433 btrfs_set_item_key(buf, &disk_key, nritems);
434 btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
435 btrfs_set_item_size(buf, btrfs_item_nr(nritems), item_size);
437 chunk = btrfs_item_ptr(buf, nritems, struct btrfs_chunk);
438 btrfs_set_chunk_length(buf, chunk, BTRFS_MKFS_SYSTEM_GROUP_SIZE);
439 btrfs_set_chunk_owner(buf, chunk, BTRFS_EXTENT_TREE_OBJECTID);
440 btrfs_set_chunk_stripe_len(buf, chunk, 64 * 1024);
441 btrfs_set_chunk_type(buf, chunk, BTRFS_BLOCK_GROUP_SYSTEM);
442 btrfs_set_chunk_io_align(buf, chunk, sectorsize);
443 btrfs_set_chunk_io_width(buf, chunk, sectorsize);
444 btrfs_set_chunk_sector_size(buf, chunk, sectorsize);
445 btrfs_set_chunk_num_stripes(buf, chunk, 1);
446 btrfs_set_stripe_devid_nr(buf, chunk, 0, 1);
447 btrfs_set_stripe_offset_nr(buf, chunk, 0, 0);
450 write_extent_buffer(buf, super.dev_item.uuid,
451 (unsigned long)btrfs_stripe_dev_uuid(&chunk->stripe),
454 /* copy the key for the chunk to the system array */
455 ptr = super.sys_chunk_array;
456 array_size = sizeof(disk_key);
458 memcpy(ptr, &disk_key, sizeof(disk_key));
459 ptr += sizeof(disk_key);
461 /* copy the chunk to the system array */
462 read_extent_buffer(buf, ptr, (unsigned long)chunk, item_size);
463 array_size += item_size;
465 btrfs_set_super_sys_array_size(&super, array_size);
467 btrfs_set_header_bytenr(buf, blocks[3]);
468 btrfs_set_header_owner(buf, BTRFS_CHUNK_TREE_OBJECTID);
469 btrfs_set_header_nritems(buf, nritems);
470 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
471 ret = pwrite(fd, buf->data, leafsize, blocks[3]);
472 if (ret != leafsize) {
473 ret = (ret < 0 ? -errno : -EIO);
477 /* create the device tree */
478 memset(buf->data+sizeof(struct btrfs_header), 0,
479 leafsize-sizeof(struct btrfs_header));
481 itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize) -
482 sizeof(struct btrfs_dev_extent);
484 btrfs_set_disk_key_objectid(&disk_key, 1);
485 btrfs_set_disk_key_offset(&disk_key, 0);
486 btrfs_set_disk_key_type(&disk_key, BTRFS_DEV_EXTENT_KEY);
487 btrfs_set_item_key(buf, &disk_key, nritems);
488 btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
489 btrfs_set_item_size(buf, btrfs_item_nr(nritems),
490 sizeof(struct btrfs_dev_extent));
491 dev_extent = btrfs_item_ptr(buf, nritems, struct btrfs_dev_extent);
492 btrfs_set_dev_extent_chunk_tree(buf, dev_extent,
493 BTRFS_CHUNK_TREE_OBJECTID);
494 btrfs_set_dev_extent_chunk_objectid(buf, dev_extent,
495 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
496 btrfs_set_dev_extent_chunk_offset(buf, dev_extent, 0);
498 write_extent_buffer(buf, chunk_tree_uuid,
499 (unsigned long)btrfs_dev_extent_chunk_tree_uuid(dev_extent),
502 btrfs_set_dev_extent_length(buf, dev_extent,
503 BTRFS_MKFS_SYSTEM_GROUP_SIZE);
506 btrfs_set_header_bytenr(buf, blocks[4]);
507 btrfs_set_header_owner(buf, BTRFS_DEV_TREE_OBJECTID);
508 btrfs_set_header_nritems(buf, nritems);
509 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
510 ret = pwrite(fd, buf->data, leafsize, blocks[4]);
511 if (ret != leafsize) {
512 ret = (ret < 0 ? -errno : -EIO);
516 /* create the FS root */
517 memset(buf->data+sizeof(struct btrfs_header), 0,
518 leafsize-sizeof(struct btrfs_header));
519 btrfs_set_header_bytenr(buf, blocks[5]);
520 btrfs_set_header_owner(buf, BTRFS_FS_TREE_OBJECTID);
521 btrfs_set_header_nritems(buf, 0);
522 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
523 ret = pwrite(fd, buf->data, leafsize, blocks[5]);
524 if (ret != leafsize) {
525 ret = (ret < 0 ? -errno : -EIO);
528 /* finally create the csum root */
529 memset(buf->data+sizeof(struct btrfs_header), 0,
530 leafsize-sizeof(struct btrfs_header));
531 btrfs_set_header_bytenr(buf, blocks[6]);
532 btrfs_set_header_owner(buf, BTRFS_CSUM_TREE_OBJECTID);
533 btrfs_set_header_nritems(buf, 0);
534 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
535 ret = pwrite(fd, buf->data, leafsize, blocks[6]);
536 if (ret != leafsize) {
537 ret = (ret < 0 ? -errno : -EIO);
541 /* and write out the super block */
542 BUG_ON(sizeof(super) > sectorsize);
543 memset(buf->data, 0, sectorsize);
544 memcpy(buf->data, &super, sizeof(super));
545 buf->len = sectorsize;
546 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
547 ret = pwrite(fd, buf->data, sectorsize, blocks[0]);
548 if (ret != sectorsize) {
549 ret = (ret < 0 ? -errno : -EIO);
560 u64 btrfs_device_size(int fd, struct stat *st)
563 if (S_ISREG(st->st_mode)) {
566 if (!S_ISBLK(st->st_mode)) {
569 if (ioctl(fd, BLKGETSIZE64, &size) >= 0) {
575 static int zero_blocks(int fd, off_t start, size_t len)
577 char *buf = malloc(len);
584 written = pwrite(fd, buf, len, start);
591 #define ZERO_DEV_BYTES (2 * 1024 * 1024)
593 /* don't write outside the device by clamping the region to the device size */
594 static int zero_dev_clamped(int fd, off_t start, ssize_t len, u64 dev_size)
596 off_t end = max(start, start + len);
599 /* and don't overwrite the disk labels on sparc */
600 start = max(start, 1024);
601 end = max(end, 1024);
604 start = min_t(u64, start, dev_size);
605 end = min_t(u64, end, dev_size);
607 return zero_blocks(fd, start, end - start);
610 int btrfs_add_to_fsid(struct btrfs_trans_handle *trans,
611 struct btrfs_root *root, int fd, char *path,
612 u64 block_count, u32 io_width, u32 io_align,
615 struct btrfs_super_block *disk_super;
616 struct btrfs_super_block *super = root->fs_info->super_copy;
617 struct btrfs_device *device;
618 struct btrfs_dev_item *dev_item;
624 device = kzalloc(sizeof(*device), GFP_NOFS);
627 buf = kmalloc(sectorsize, GFP_NOFS);
632 BUG_ON(sizeof(*disk_super) > sectorsize);
633 memset(buf, 0, sectorsize);
635 disk_super = (struct btrfs_super_block *)buf;
636 dev_item = &disk_super->dev_item;
638 uuid_generate(device->uuid);
641 device->io_width = io_width;
642 device->io_align = io_align;
643 device->sector_size = sectorsize;
645 device->writeable = 1;
646 device->total_bytes = block_count;
647 device->bytes_used = 0;
648 device->total_ios = 0;
649 device->dev_root = root->fs_info->dev_root;
651 ret = btrfs_add_device(trans, root, device);
654 total_bytes = btrfs_super_total_bytes(super) + block_count;
655 btrfs_set_super_total_bytes(super, total_bytes);
657 num_devs = btrfs_super_num_devices(super) + 1;
658 btrfs_set_super_num_devices(super, num_devs);
660 memcpy(disk_super, super, sizeof(*disk_super));
662 printf("adding device %s id %llu\n", path,
663 (unsigned long long)device->devid);
665 btrfs_set_super_bytenr(disk_super, BTRFS_SUPER_INFO_OFFSET);
666 btrfs_set_stack_device_id(dev_item, device->devid);
667 btrfs_set_stack_device_type(dev_item, device->type);
668 btrfs_set_stack_device_io_align(dev_item, device->io_align);
669 btrfs_set_stack_device_io_width(dev_item, device->io_width);
670 btrfs_set_stack_device_sector_size(dev_item, device->sector_size);
671 btrfs_set_stack_device_total_bytes(dev_item, device->total_bytes);
672 btrfs_set_stack_device_bytes_used(dev_item, device->bytes_used);
673 memcpy(&dev_item->uuid, device->uuid, BTRFS_UUID_SIZE);
675 ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
676 BUG_ON(ret != sectorsize);
679 list_add(&device->dev_list, &root->fs_info->fs_devices->devices);
680 device->fs_devices = root->fs_info->fs_devices;
684 static void btrfs_wipe_existing_sb(int fd)
686 const char *off = NULL;
691 blkid_probe pr = NULL;
693 pr = blkid_new_probe();
697 if (blkid_probe_set_device(pr, fd, 0, 0))
700 rc = blkid_probe_lookup_value(pr, "SBMAGIC_OFFSET", &off, NULL);
702 rc = blkid_probe_lookup_value(pr, "SBMAGIC", NULL, &len);
704 if (rc || len == 0 || off == NULL)
707 offset = strtoll(off, NULL, 10);
708 if (len > sizeof(buf))
712 rc = pwrite(fd, buf, len, offset);
716 blkid_free_probe(pr);
720 int btrfs_prepare_device(int fd, char *file, int zero_end, u64 *block_count_ret,
721 u64 max_block_count, int *mixed, int discard)
727 ret = fstat(fd, &st);
729 fprintf(stderr, "unable to stat %s\n", file);
733 block_count = btrfs_device_size(fd, &st);
734 if (block_count == 0) {
735 fprintf(stderr, "unable to find %s size\n", file);
739 block_count = min(block_count, max_block_count);
741 if (block_count < BTRFS_MKFS_SMALL_VOLUME_SIZE && !(*mixed))
746 * We intentionally ignore errors from the discard ioctl. It
747 * is not necessary for the mkfs functionality but just an
750 if (discard_range(fd, 0, 0) == 0) {
751 fprintf(stderr, "Performing full device TRIM (%s) ...\n",
752 pretty_size(block_count));
753 discard_blocks(fd, 0, block_count);
757 ret = zero_dev_clamped(fd, 0, ZERO_DEV_BYTES, block_count);
758 for (i = 0 ; !ret && i < BTRFS_SUPER_MIRROR_MAX; i++)
759 ret = zero_dev_clamped(fd, btrfs_sb_offset(i),
760 BTRFS_SUPER_INFO_SIZE, block_count);
761 if (!ret && zero_end)
762 ret = zero_dev_clamped(fd, block_count - ZERO_DEV_BYTES,
763 ZERO_DEV_BYTES, block_count);
766 fprintf(stderr, "ERROR: failed to zero device '%s' - %s\n",
767 file, strerror(-ret));
771 btrfs_wipe_existing_sb(fd);
773 *block_count_ret = block_count;
777 int btrfs_make_root_dir(struct btrfs_trans_handle *trans,
778 struct btrfs_root *root, u64 objectid)
781 struct btrfs_inode_item inode_item;
782 time_t now = time(NULL);
784 memset(&inode_item, 0, sizeof(inode_item));
785 btrfs_set_stack_inode_generation(&inode_item, trans->transid);
786 btrfs_set_stack_inode_size(&inode_item, 0);
787 btrfs_set_stack_inode_nlink(&inode_item, 1);
788 btrfs_set_stack_inode_nbytes(&inode_item, root->leafsize);
789 btrfs_set_stack_inode_mode(&inode_item, S_IFDIR | 0755);
790 btrfs_set_stack_timespec_sec(&inode_item.atime, now);
791 btrfs_set_stack_timespec_nsec(&inode_item.atime, 0);
792 btrfs_set_stack_timespec_sec(&inode_item.ctime, now);
793 btrfs_set_stack_timespec_nsec(&inode_item.ctime, 0);
794 btrfs_set_stack_timespec_sec(&inode_item.mtime, now);
795 btrfs_set_stack_timespec_nsec(&inode_item.mtime, 0);
796 btrfs_set_stack_timespec_sec(&inode_item.otime, 0);
797 btrfs_set_stack_timespec_nsec(&inode_item.otime, 0);
799 if (root->fs_info->tree_root == root)
800 btrfs_set_super_root_dir(root->fs_info->super_copy, objectid);
802 ret = btrfs_insert_inode(trans, root, objectid, &inode_item);
806 ret = btrfs_insert_inode_ref(trans, root, "..", 2, objectid, objectid, 0);
810 btrfs_set_root_dirid(&root->root_item, objectid);
817 * checks if a path is a block device node
818 * Returns negative errno on failure, otherwise
819 * returns 1 for blockdev, 0 for not-blockdev
821 int is_block_device(const char *path)
825 if (stat(path, &statbuf) < 0)
828 return S_ISBLK(statbuf.st_mode);
832 * check if given path is a mount point
833 * return 1 if yes. 0 if no. -1 for error
835 int is_mount_point(const char *path)
841 f = setmntent("/proc/self/mounts", "r");
845 while ((mnt = getmntent(f)) != NULL) {
846 if (strcmp(mnt->mnt_dir, path))
856 * Find the mount point for a mounted device.
857 * On success, returns 0 with mountpoint in *mp.
858 * On failure, returns -errno (not mounted yields -EINVAL)
859 * Is noisy on failures, expects to be given a mounted device.
861 int get_btrfs_mount(const char *dev, char *mp, size_t mp_size)
866 ret = is_block_device(dev);
869 fprintf(stderr, "%s is not a block device\n", dev);
872 fprintf(stderr, "Could not check %s: %s\n",
873 dev, strerror(-ret));
878 fd = open(dev, O_RDONLY);
881 fprintf(stderr, "Could not open %s: %s\n", dev, strerror(errno));
885 ret = check_mounted_where(fd, dev, mp, mp_size, NULL);
888 } else { /* mounted, all good */
898 * Given a pathname, return a filehandle to:
899 * the original pathname or,
900 * if the pathname is a mounted btrfs device, to its mountpoint.
902 * On error, return -1, errno should be set.
904 int open_path_or_dev_mnt(const char *path, DIR **dirstream)
906 char mp[BTRFS_PATH_NAME_MAX + 1];
909 if (is_block_device(path)) {
912 ret = get_btrfs_mount(path, mp, sizeof(mp));
914 /* not a mounted btrfs dev */
918 fdmnt = open_file_or_dir(mp, dirstream);
920 fdmnt = open_file_or_dir(path, dirstream);
926 /* checks if a device is a loop device */
927 static int is_loop_device (const char* device) {
930 if(stat(device, &statbuf) < 0)
933 return (S_ISBLK(statbuf.st_mode) &&
934 MAJOR(statbuf.st_rdev) == LOOP_MAJOR);
938 /* Takes a loop device path (e.g. /dev/loop0) and returns
939 * the associated file (e.g. /images/my_btrfs.img) */
940 static int resolve_loop_device(const char* loop_dev, char* loop_file,
947 char real_loop_dev[PATH_MAX];
949 if (!realpath(loop_dev, real_loop_dev))
951 snprintf(p, PATH_MAX, "/sys/block/%s/loop/backing_file", strrchr(real_loop_dev, '/'));
952 if (!(f = fopen(p, "r")))
955 snprintf(fmt, 20, "%%%i[^\n]", max_len-1);
956 ret = fscanf(f, fmt, loop_file);
964 /* Checks whether a and b are identical or device
965 * files associated with the same block device
967 static int is_same_blk_file(const char* a, const char* b)
969 struct stat st_buf_a, st_buf_b;
970 char real_a[PATH_MAX];
971 char real_b[PATH_MAX];
973 if(!realpath(a, real_a))
976 if (!realpath(b, real_b))
979 /* Identical path? */
980 if(strcmp(real_a, real_b) == 0)
983 if(stat(a, &st_buf_a) < 0 ||
984 stat(b, &st_buf_b) < 0)
991 /* Same blockdevice? */
992 if(S_ISBLK(st_buf_a.st_mode) &&
993 S_ISBLK(st_buf_b.st_mode) &&
994 st_buf_a.st_rdev == st_buf_b.st_rdev)
1000 if (st_buf_a.st_dev == st_buf_b.st_dev &&
1001 st_buf_a.st_ino == st_buf_b.st_ino)
1009 /* checks if a and b are identical or device
1010 * files associated with the same block device or
1011 * if one file is a loop device that uses the other
1014 static int is_same_loop_file(const char* a, const char* b)
1016 char res_a[PATH_MAX];
1017 char res_b[PATH_MAX];
1018 const char* final_a = NULL;
1019 const char* final_b = NULL;
1022 /* Resolve a if it is a loop device */
1023 if((ret = is_loop_device(a)) < 0) {
1028 ret = resolve_loop_device(a, res_a, sizeof(res_a));
1039 /* Resolve b if it is a loop device */
1040 if ((ret = is_loop_device(b)) < 0) {
1045 ret = resolve_loop_device(b, res_b, sizeof(res_b));
1056 return is_same_blk_file(final_a, final_b);
1059 /* Checks if a file exists and is a block or regular file*/
1060 static int is_existing_blk_or_reg_file(const char* filename)
1064 if(stat(filename, &st_buf) < 0) {
1071 return (S_ISBLK(st_buf.st_mode) || S_ISREG(st_buf.st_mode));
1074 /* Checks if a file is used (directly or indirectly via a loop device)
1075 * by a device in fs_devices
1077 static int blk_file_in_dev_list(struct btrfs_fs_devices* fs_devices,
1081 struct list_head *head;
1082 struct list_head *cur;
1083 struct btrfs_device *device;
1085 head = &fs_devices->devices;
1086 list_for_each(cur, head) {
1087 device = list_entry(cur, struct btrfs_device, dev_list);
1089 if((ret = is_same_loop_file(device->name, file)))
1097 * Resolve a pathname to a device mapper node to /dev/mapper/<name>
1098 * Returns NULL on invalid input or malloc failure; Other failures
1099 * will be handled by the caller using the input pathame.
1101 char *canonicalize_dm_name(const char *ptname)
1105 char path[PATH_MAX], name[PATH_MAX], *res = NULL;
1107 if (!ptname || !*ptname)
1110 snprintf(path, sizeof(path), "/sys/block/%s/dm/name", ptname);
1111 if (!(f = fopen(path, "r")))
1114 /* read <name>\n from sysfs */
1115 if (fgets(name, sizeof(name), f) && (sz = strlen(name)) > 1) {
1116 name[sz - 1] = '\0';
1117 snprintf(path, sizeof(path), "/dev/mapper/%s", name);
1119 if (access(path, F_OK) == 0)
1127 * Resolve a pathname to a canonical device node, e.g. /dev/sda1 or
1128 * to a device mapper pathname.
1129 * Returns NULL on invalid input or malloc failure; Other failures
1130 * will be handled by the caller using the input pathame.
1132 char *canonicalize_path(const char *path)
1134 char *canonical, *p;
1136 if (!path || !*path)
1139 canonical = realpath(path, NULL);
1141 return strdup(path);
1142 p = strrchr(canonical, '/');
1143 if (p && strncmp(p, "/dm-", 4) == 0 && isdigit(*(p + 4))) {
1144 char *dm = canonicalize_dm_name(p + 1);
1155 * returns 1 if the device was mounted, < 0 on error or 0 if everything
1156 * is safe to continue.
1158 int check_mounted(const char* file)
1163 fd = open(file, O_RDONLY);
1165 fprintf (stderr, "check_mounted(): Could not open %s\n", file);
1169 ret = check_mounted_where(fd, file, NULL, 0, NULL);
1175 int check_mounted_where(int fd, const char *file, char *where, int size,
1176 struct btrfs_fs_devices **fs_dev_ret)
1181 struct btrfs_fs_devices *fs_devices_mnt = NULL;
1185 /* scan the initial device */
1186 ret = btrfs_scan_one_device(fd, file, &fs_devices_mnt,
1187 &total_devs, BTRFS_SUPER_INFO_OFFSET, 0);
1188 is_btrfs = (ret >= 0);
1190 /* scan other devices */
1191 if (is_btrfs && total_devs > 1) {
1192 ret = btrfs_scan_lblkid();
1197 /* iterate over the list of currently mountes filesystems */
1198 if ((f = setmntent ("/proc/self/mounts", "r")) == NULL)
1201 while ((mnt = getmntent (f)) != NULL) {
1203 if(strcmp(mnt->mnt_type, "btrfs") != 0)
1206 ret = blk_file_in_dev_list(fs_devices_mnt, mnt->mnt_fsname);
1208 /* ignore entries in the mount table that are not
1209 associated with a file*/
1210 if((ret = is_existing_blk_or_reg_file(mnt->mnt_fsname)) < 0)
1211 goto out_mntloop_err;
1215 ret = is_same_loop_file(file, mnt->mnt_fsname);
1219 goto out_mntloop_err;
1224 /* Did we find an entry in mnt table? */
1225 if (mnt && size && where) {
1226 strncpy(where, mnt->mnt_dir, size);
1230 *fs_dev_ret = fs_devices_mnt;
1232 ret = (mnt != NULL);
1240 struct pending_dir {
1241 struct list_head list;
1242 char name[PATH_MAX];
1245 int btrfs_register_one_device(const char *fname)
1247 struct btrfs_ioctl_vol_args args;
1252 fd = open("/dev/btrfs-control", O_RDWR);
1254 fprintf(stderr, "failed to open /dev/btrfs-control "
1255 "skipping device registration: %s\n",
1259 strncpy(args.name, fname, BTRFS_PATH_NAME_MAX);
1260 args.name[BTRFS_PATH_NAME_MAX-1] = 0;
1261 ret = ioctl(fd, BTRFS_IOC_SCAN_DEV, &args);
1264 fprintf(stderr, "ERROR: device scan failed '%s' - %s\n",
1265 fname, strerror(e));
1273 * Register all devices in the fs_uuid list created in the user
1274 * space. Ensure btrfs_scan_lblkid() is called before this func.
1276 int btrfs_register_all_devices(void)
1279 struct btrfs_fs_devices *fs_devices;
1280 struct btrfs_device *device;
1281 struct list_head *all_uuids;
1283 all_uuids = btrfs_scanned_uuids();
1285 list_for_each_entry(fs_devices, all_uuids, list) {
1286 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1287 if (strlen(device->name) != 0) {
1288 err = btrfs_register_one_device(device->name);
1299 int btrfs_device_already_in_root(struct btrfs_root *root, int fd,
1302 struct btrfs_super_block *disk_super;
1306 buf = malloc(BTRFS_SUPER_INFO_SIZE);
1311 ret = pread(fd, buf, BTRFS_SUPER_INFO_SIZE, super_offset);
1312 if (ret != BTRFS_SUPER_INFO_SIZE)
1316 disk_super = (struct btrfs_super_block *)buf;
1317 if (btrfs_super_magic(disk_super) != BTRFS_MAGIC)
1320 if (!memcmp(disk_super->fsid, root->fs_info->super_copy->fsid,
1329 static const char* unit_suffix_binary[] =
1330 { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"};
1331 static const char* unit_suffix_decimal[] =
1332 { "B", "kB", "MB", "GB", "TB", "PB", "EB"};
1334 int pretty_size_snprintf(u64 size, char *str, size_t str_size, unsigned unit_mode)
1340 const char** suffix = NULL;
1346 if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_RAW) {
1347 snprintf(str, str_size, "%llu", size);
1351 if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_BINARY) {
1354 suffix = unit_suffix_binary;
1355 } else if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_DECIMAL) {
1358 suffix = unit_suffix_decimal;
1363 fprintf(stderr, "INTERNAL ERROR: unknown unit base, mode %d\n",
1371 switch (unit_mode & UNITS_MODE_MASK) {
1372 case UNITS_TBYTES: base *= mult; num_divs++;
1373 case UNITS_GBYTES: base *= mult; num_divs++;
1374 case UNITS_MBYTES: base *= mult; num_divs++;
1375 case UNITS_KBYTES: num_divs++;
1382 while (size >= mult) {
1389 if (num_divs >= ARRAY_SIZE(unit_suffix_binary)) {
1391 printf("INTERNAL ERROR: unsupported unit suffix, index %d\n",
1396 fraction = (float)last_size / base;
1398 return snprintf(str, str_size, "%.2f%s", fraction, suffix[num_divs]);
1402 * __strncpy__null - strncpy with null termination
1403 * @dest: the target array
1404 * @src: the source string
1405 * @n: maximum bytes to copy (size of *dest)
1407 * Like strncpy, but ensures destination is null-terminated.
1409 * Copies the string pointed to by src, including the terminating null
1410 * byte ('\0'), to the buffer pointed to by dest, up to a maximum
1411 * of n bytes. Then ensure that dest is null-terminated.
1413 char *__strncpy__null(char *dest, const char *src, size_t n)
1415 strncpy(dest, src, n);
1422 * Checks to make sure that the label matches our requirements.
1424 0 if everything is safe and usable
1425 -1 if the label is too long
1427 static int check_label(const char *input)
1429 int len = strlen(input);
1431 if (len > BTRFS_LABEL_SIZE - 1) {
1432 fprintf(stderr, "ERROR: Label %s is too long (max %d)\n",
1433 input, BTRFS_LABEL_SIZE - 1);
1440 static int set_label_unmounted(const char *dev, const char *label)
1442 struct btrfs_trans_handle *trans;
1443 struct btrfs_root *root;
1446 ret = check_mounted(dev);
1448 fprintf(stderr, "FATAL: error checking %s mount status\n", dev);
1452 fprintf(stderr, "ERROR: dev %s is mounted, use mount point\n",
1457 /* Open the super_block at the default location
1458 * and as read-write.
1460 root = open_ctree(dev, 0, OPEN_CTREE_WRITES);
1461 if (!root) /* errors are printed by open_ctree() */
1464 trans = btrfs_start_transaction(root, 1);
1465 snprintf(root->fs_info->super_copy->label, BTRFS_LABEL_SIZE, "%s",
1467 btrfs_commit_transaction(trans, root);
1469 /* Now we close it since we are done. */
1474 static int set_label_mounted(const char *mount_path, const char *label)
1478 fd = open(mount_path, O_RDONLY | O_NOATIME);
1480 fprintf(stderr, "ERROR: unable to access '%s'\n", mount_path);
1484 if (ioctl(fd, BTRFS_IOC_SET_FSLABEL, label) < 0) {
1485 fprintf(stderr, "ERROR: unable to set label %s\n",
1495 static int get_label_unmounted(const char *dev, char *label)
1497 struct btrfs_root *root;
1500 ret = check_mounted(dev);
1502 fprintf(stderr, "FATAL: error checking %s mount status\n", dev);
1506 fprintf(stderr, "ERROR: dev %s is mounted, use mount point\n",
1511 /* Open the super_block at the default location
1514 root = open_ctree(dev, 0, 0);
1518 memcpy(label, root->fs_info->super_copy->label, BTRFS_LABEL_SIZE);
1520 /* Now we close it since we are done. */
1526 * If a partition is mounted, try to get the filesystem label via its
1527 * mounted path rather than device. Return the corresponding error
1528 * the user specified the device path.
1530 int get_label_mounted(const char *mount_path, char *labelp)
1532 char label[BTRFS_LABEL_SIZE];
1535 fd = open(mount_path, O_RDONLY | O_NOATIME);
1537 fprintf(stderr, "ERROR: unable to access '%s'\n", mount_path);
1541 memset(label, '\0', sizeof(label));
1542 if (ioctl(fd, BTRFS_IOC_GET_FSLABEL, label) < 0) {
1543 fprintf(stderr, "ERROR: unable get label %s\n", strerror(errno));
1548 strncpy(labelp, label, sizeof(label));
1553 int get_label(const char *btrfs_dev, char *label)
1557 ret = is_existing_blk_or_reg_file(btrfs_dev);
1559 ret = get_label_mounted(btrfs_dev, label);
1561 ret = get_label_unmounted(btrfs_dev, label);
1566 int set_label(const char *btrfs_dev, const char *label)
1570 if (check_label(label))
1573 ret = is_existing_blk_or_reg_file(btrfs_dev);
1575 ret = set_label_mounted(btrfs_dev, label);
1577 ret = set_label_unmounted(btrfs_dev, label);
1582 int btrfs_scan_block_devices(int run_ioctl)
1588 struct btrfs_fs_devices *tmp_devices;
1590 FILE *proc_partitions;
1598 proc_partitions = fopen("/proc/partitions","r");
1599 if (!proc_partitions) {
1600 fprintf(stderr, "Unable to open '/proc/partitions' for scanning\n");
1603 /* skip the header */
1604 for (i = 0; i < 2; i++)
1605 if (!fgets(buf, 1023, proc_partitions)) {
1607 "Unable to read '/proc/partitions' for scanning\n");
1608 fclose(proc_partitions);
1612 strcpy(fullpath,"/dev/");
1613 while(fgets(buf, 1023, proc_partitions)) {
1614 ret = sscanf(buf," %*d %*d %*d %99s", fullpath + 5);
1617 "failed to scan device name from /proc/partitions\n");
1622 * multipath and MD devices may register as a btrfs filesystem
1623 * both through the original block device and through
1624 * the special (/dev/mapper or /dev/mdX) entry.
1625 * This scans the special entries last
1627 special = strncmp(fullpath, "/dev/dm-", strlen("/dev/dm-")) == 0;
1629 special = strncmp(fullpath, "/dev/md", strlen("/dev/md")) == 0;
1631 if (scans == 0 && special)
1633 if (scans > 0 && !special)
1636 ret = lstat(fullpath, &st);
1638 fprintf(stderr, "failed to stat %s\n", fullpath);
1641 if (!S_ISBLK(st.st_mode)) {
1645 fd = open(fullpath, O_RDONLY);
1647 if (errno != ENOMEDIUM)
1648 fprintf(stderr, "failed to open %s: %s\n",
1649 fullpath, strerror(errno));
1652 ret = btrfs_scan_one_device(fd, fullpath, &tmp_devices,
1654 BTRFS_SUPER_INFO_OFFSET, 0);
1655 if (ret == 0 && run_ioctl > 0) {
1656 btrfs_register_one_device(fullpath);
1661 fclose(proc_partitions);
1671 * A not-so-good version fls64. No fascinating optimization since
1672 * no one except parse_size use it
1674 static int fls64(u64 x)
1678 for (i = 0; i <64; i++)
1679 if (x << i & (1ULL << 63))
1684 u64 parse_size(char *s)
1692 fprintf(stderr, "ERROR: Size value is empty\n");
1697 "ERROR: Size value '%s' is less equal than 0\n", s);
1700 ret = strtoull(s, &endptr, 10);
1702 fprintf(stderr, "ERROR: Size value '%s' is invalid\n", s);
1705 if (endptr[0] && endptr[1]) {
1706 fprintf(stderr, "ERROR: Illegal suffix contains character '%c' in wrong position\n",
1711 * strtoll returns LLONG_MAX when overflow, if this happens,
1712 * need to call strtoull to get the real size
1714 if (errno == ERANGE && ret == ULLONG_MAX) {
1716 "ERROR: Size value '%s' is too large for u64\n", s);
1720 c = tolower(endptr[0]);
1743 fprintf(stderr, "ERROR: Unknown size descriptor '%c'\n",
1748 /* Check whether ret * mult overflow */
1749 if (fls64(ret) + fls64(mult) - 1 > 64) {
1751 "ERROR: Size value '%s' is too large for u64\n", s);
1758 int open_file_or_dir3(const char *fname, DIR **dirstream, int open_flags)
1764 ret = stat(fname, &st);
1768 if (S_ISDIR(st.st_mode)) {
1769 *dirstream = opendir(fname);
1772 fd = dirfd(*dirstream);
1773 } else if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
1774 fd = open(fname, open_flags);
1777 * we set this on purpose, in case the caller output
1778 * strerror(errno) as success
1786 closedir(*dirstream);
1791 int open_file_or_dir(const char *fname, DIR **dirstream)
1793 return open_file_or_dir3(fname, dirstream, O_RDWR);
1796 void close_file_or_dir(int fd, DIR *dirstream)
1799 closedir(dirstream);
1804 int get_device_info(int fd, u64 devid,
1805 struct btrfs_ioctl_dev_info_args *di_args)
1809 di_args->devid = devid;
1810 memset(&di_args->uuid, '\0', sizeof(di_args->uuid));
1812 ret = ioctl(fd, BTRFS_IOC_DEV_INFO, di_args);
1813 return ret ? -errno : 0;
1817 * For a given path, fill in the ioctl fs_ and info_ args.
1818 * If the path is a btrfs mountpoint, fill info for all devices.
1819 * If the path is a btrfs device, fill in only that device.
1821 * The path provided must be either on a mounted btrfs fs,
1822 * or be a mounted btrfs device.
1824 * Returns 0 on success, or a negative errno.
1826 int get_fs_info(char *path, struct btrfs_ioctl_fs_info_args *fi_args,
1827 struct btrfs_ioctl_dev_info_args **di_ret)
1833 struct btrfs_fs_devices *fs_devices_mnt = NULL;
1834 struct btrfs_ioctl_dev_info_args *di_args;
1835 char mp[BTRFS_PATH_NAME_MAX + 1];
1836 DIR *dirstream = NULL;
1838 memset(fi_args, 0, sizeof(*fi_args));
1840 if (is_block_device(path)) {
1841 struct btrfs_super_block *disk_super;
1842 char buf[BTRFS_SUPER_INFO_SIZE];
1845 /* Ensure it's mounted, then set path to the mountpoint */
1846 fd = open(path, O_RDONLY);
1849 fprintf(stderr, "Couldn't open %s: %s\n",
1850 path, strerror(errno));
1853 ret = check_mounted_where(fd, path, mp, sizeof(mp),
1862 /* Only fill in this one device */
1863 fi_args->num_devices = 1;
1865 disk_super = (struct btrfs_super_block *)buf;
1866 ret = btrfs_read_dev_super(fd, disk_super,
1867 BTRFS_SUPER_INFO_OFFSET, 0);
1872 devid = btrfs_stack_device_id(&disk_super->dev_item);
1874 fi_args->max_id = devid;
1877 memcpy(fi_args->fsid, fs_devices_mnt->fsid, BTRFS_FSID_SIZE);
1881 /* at this point path must not be for a block device */
1882 fd = open_file_or_dir(path, &dirstream);
1888 /* fill in fi_args if not just a single device */
1889 if (fi_args->num_devices != 1) {
1890 ret = ioctl(fd, BTRFS_IOC_FS_INFO, fi_args);
1897 if (!fi_args->num_devices)
1900 di_args = *di_ret = malloc((fi_args->num_devices) * sizeof(*di_args));
1906 for (; i <= fi_args->max_id; ++i) {
1907 BUG_ON(ndevs >= fi_args->num_devices);
1908 ret = get_device_info(fd, i, &di_args[ndevs]);
1917 * only when the only dev we wanted to find is not there then
1918 * let any error be returned
1920 if (fi_args->num_devices != 1) {
1926 close_file_or_dir(fd, dirstream);
1930 #define isoctal(c) (((c) & ~7) == '0')
1932 static inline void translate(char *f, char *t)
1934 while (*f != '\0') {
1936 isoctal(f[1]) && isoctal(f[2]) && isoctal(f[3])) {
1937 *t++ = 64*(f[1] & 7) + 8*(f[2] & 7) + (f[3] & 7);
1947 * Checks if the swap device.
1948 * Returns 1 if swap device, < 0 on error or 0 if not swap device.
1950 static int is_swap_device(const char *file)
1961 if (stat(file, &st_buf) < 0)
1963 if (S_ISBLK(st_buf.st_mode))
1964 dev = st_buf.st_rdev;
1965 else if (S_ISREG(st_buf.st_mode)) {
1966 dev = st_buf.st_dev;
1967 ino = st_buf.st_ino;
1971 if ((f = fopen("/proc/swaps", "r")) == NULL)
1974 /* skip the first line */
1975 if (fgets(tmp, sizeof(tmp), f) == NULL)
1978 while (fgets(tmp, sizeof(tmp), f) != NULL) {
1979 if ((cp = strchr(tmp, ' ')) != NULL)
1981 if ((cp = strchr(tmp, '\t')) != NULL)
1983 translate(tmp, buf);
1984 if (stat(buf, &st_buf) != 0)
1986 if (S_ISBLK(st_buf.st_mode)) {
1987 if (dev == st_buf.st_rdev) {
1991 } else if (S_ISREG(st_buf.st_mode)) {
1992 if (dev == st_buf.st_dev && ino == st_buf.st_ino) {
2006 * Check for existing filesystem or partition table on device.
2008 * 1 for existing fs or partition
2009 * 0 for nothing found
2010 * -1 for internal error
2017 blkid_probe pr = NULL;
2021 if (!device || !*device)
2024 ret = -1; /* will reset on success of all setup calls */
2026 pr = blkid_new_probe_from_filename(device);
2030 size = blkid_probe_get_size(pr);
2034 /* nothing to overwrite on a 0-length device */
2040 ret = blkid_probe_enable_partitions(pr, 1);
2044 ret = blkid_do_fullprobe(pr);
2049 * Blkid returns 1 for nothing found and 0 when it finds a signature,
2050 * but we want the exact opposite, so reverse the return value here.
2052 * In addition print some useful diagnostics about what actually is
2060 if (!blkid_probe_lookup_value(pr, "TYPE", &type, NULL)) {
2062 "%s appears to contain an existing "
2063 "filesystem (%s).\n", device, type);
2064 } else if (!blkid_probe_lookup_value(pr, "PTTYPE", &type, NULL)) {
2066 "%s appears to contain a partition "
2067 "table (%s).\n", device, type);
2070 "%s appears to contain something weird "
2071 "according to blkid\n", device);
2077 blkid_free_probe(pr);
2080 "probe of %s failed, cannot detect "
2081 "existing filesystem.\n", device);
2085 int test_num_disk_vs_raid(u64 metadata_profile, u64 data_profile,
2086 u64 dev_cnt, int mixed, char *estr)
2094 allowed |= BTRFS_BLOCK_GROUP_RAID10;
2096 allowed |= BTRFS_BLOCK_GROUP_RAID6;
2098 allowed |= BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
2099 BTRFS_BLOCK_GROUP_RAID5;
2102 allowed |= BTRFS_BLOCK_GROUP_DUP;
2105 if (metadata_profile & ~allowed) {
2106 snprintf(estr, sz, "unable to create FS with metadata "
2107 "profile %llu (have %llu devices)\n",
2108 metadata_profile, dev_cnt);
2111 if (data_profile & ~allowed) {
2112 snprintf(estr, sz, "unable to create FS with data "
2113 "profile %llu (have %llu devices)\n",
2114 metadata_profile, dev_cnt);
2118 if (!mixed && (data_profile & BTRFS_BLOCK_GROUP_DUP)) {
2120 "dup for data is allowed only in mixed mode");
2126 /* Check if disk is suitable for btrfs
2128 * 1: something is wrong, estr provides the error
2131 int test_dev_for_mkfs(char *file, int force_overwrite, char *estr)
2137 ret = is_swap_device(file);
2139 snprintf(estr, sz, "error checking %s status: %s\n", file,
2144 snprintf(estr, sz, "%s is a swap device\n", file);
2147 if (!force_overwrite) {
2148 if (check_overwrite(file)) {
2149 snprintf(estr, sz, "Use the -f option to force overwrite.\n");
2153 ret = check_mounted(file);
2155 snprintf(estr, sz, "error checking %s mount status\n",
2160 snprintf(estr, sz, "%s is mounted\n", file);
2163 /* check if the device is busy */
2164 fd = open(file, O_RDWR|O_EXCL);
2166 snprintf(estr, sz, "unable to open %s: %s\n", file,
2170 if (fstat(fd, &st)) {
2171 snprintf(estr, sz, "unable to stat %s: %s\n", file,
2176 if (!S_ISBLK(st.st_mode)) {
2177 fprintf(stderr, "'%s' is not a block device\n", file);
2185 int btrfs_scan_lblkid()
2190 struct btrfs_fs_devices *tmp_devices;
2191 blkid_dev_iterate iter = NULL;
2192 blkid_dev dev = NULL;
2193 blkid_cache cache = NULL;
2194 char path[PATH_MAX];
2196 if (btrfs_scan_done)
2199 if (blkid_get_cache(&cache, 0) < 0) {
2200 printf("ERROR: lblkid cache get failed\n");
2203 blkid_probe_all(cache);
2204 iter = blkid_dev_iterate_begin(cache);
2205 blkid_dev_set_search(iter, "TYPE", "btrfs");
2206 while (blkid_dev_next(iter, &dev) == 0) {
2207 dev = blkid_verify(cache, dev);
2210 /* if we are here its definitely a btrfs disk*/
2211 strncpy(path, blkid_dev_devname(dev), PATH_MAX);
2213 fd = open(path, O_RDONLY);
2215 printf("ERROR: could not open %s\n", path);
2218 ret = btrfs_scan_one_device(fd, path, &tmp_devices,
2219 &num_devices, BTRFS_SUPER_INFO_OFFSET, 0);
2221 printf("ERROR: could not scan %s\n", path);
2228 blkid_dev_iterate_end(iter);
2229 blkid_put_cache(cache);
2231 btrfs_scan_done = 1;
2236 int is_vol_small(char *file)
2243 fd = open(file, O_RDONLY);
2246 if (fstat(fd, &st) < 0) {
2251 size = btrfs_device_size(fd, &st);
2256 if (size < BTRFS_MKFS_SMALL_VOLUME_SIZE) {
2266 * This reads a line from the stdin and only returns non-zero if the
2267 * first whitespace delimited token is a case insensitive match with yes
2270 int ask_user(char *question)
2272 char buf[30] = {0,};
2273 char *saveptr = NULL;
2276 printf("%s [y/N]: ", question);
2278 return fgets(buf, sizeof(buf) - 1, stdin) &&
2279 (answer = strtok_r(buf, " \t\n\r", &saveptr)) &&
2280 (!strcasecmp(answer, "yes") || !strcasecmp(answer, "y"));
2285 * - file or directory return the containing tree root id
2286 * - subvolume return its own tree id
2287 * - BTRFS_EMPTY_SUBVOL_DIR_OBJECTID (directory with ino == 2) the result is
2288 * undefined and function returns -1
2290 int lookup_ino_rootid(int fd, u64 *rootid)
2292 struct btrfs_ioctl_ino_lookup_args args;
2296 memset(&args, 0, sizeof(args));
2298 args.objectid = BTRFS_FIRST_FREE_OBJECTID;
2300 ret = ioctl(fd, BTRFS_IOC_INO_LOOKUP, &args);
2303 fprintf(stderr, "ERROR: Failed to lookup root id - %s\n",
2308 *rootid = args.treeid;
2314 * return 0 if a btrfs mount point is found
2315 * return 1 if a mount point is found but not btrfs
2316 * return <0 if something goes wrong
2318 int find_mount_root(const char *path, char **mount_root)
2326 int longest_matchlen = 0;
2327 char *longest_match = NULL;
2329 fd = open(path, O_RDONLY | O_NOATIME);
2334 mnttab = setmntent("/proc/self/mounts", "r");
2338 while ((ent = getmntent(mnttab))) {
2339 len = strlen(ent->mnt_dir);
2340 if (strncmp(ent->mnt_dir, path, len) == 0) {
2341 /* match found and use the latest match */
2342 if (longest_matchlen <= len) {
2343 free(longest_match);
2344 longest_matchlen = len;
2345 longest_match = strdup(ent->mnt_dir);
2346 not_btrfs = strcmp(ent->mnt_type, "btrfs");
2355 free(longest_match);
2360 *mount_root = realpath(longest_match, NULL);
2364 free(longest_match);
2368 int test_minimum_size(const char *file, u32 leafsize)
2371 struct stat statbuf;
2373 fd = open(file, O_RDONLY);
2376 if (stat(file, &statbuf) < 0) {
2380 if (btrfs_device_size(fd, &statbuf) < btrfs_min_dev_size(leafsize)) {
2389 * test if name is a correct subvolume name
2390 * this function return
2391 * 0-> name is not a correct subvolume name
2392 * 1-> name is a correct subvolume name
2394 int test_issubvolname(const char *name)
2396 return name[0] != '\0' && !strchr(name, '/') &&
2397 strcmp(name, ".") && strcmp(name, "..");
2401 * test if path is a directory
2402 * this function return
2403 * 0-> path exists but it is not a directory
2404 * 1-> path exists and it is a directory
2405 * -1 -> path is unaccessible
2407 int test_isdir(const char *path)
2412 ret = stat(path, &st);
2416 return S_ISDIR(st.st_mode);
2419 void units_set_mode(unsigned *units, unsigned mode)
2421 unsigned base = *units & UNITS_MODE_MASK;
2423 *units = base | mode;
2426 void units_set_base(unsigned *units, unsigned base)
2428 unsigned mode = *units & ~UNITS_MODE_MASK;
2430 *units = base | mode;
2433 int find_next_key(struct btrfs_path *path, struct btrfs_key *key)
2437 for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2438 if (!path->nodes[level])
2440 if (path->slots[level] + 1 >=
2441 btrfs_header_nritems(path->nodes[level]))
2444 btrfs_item_key_to_cpu(path->nodes[level], key,
2445 path->slots[level] + 1);
2447 btrfs_node_key_to_cpu(path->nodes[level], key,
2448 path->slots[level] + 1);