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>
43 #include "kerncompat.h"
44 #include "radix-tree.h"
47 #include "transaction.h"
54 #define BLKDISCARD _IO(0x12,119)
57 static int btrfs_scan_done = 0;
59 static char argv0_buf[ARGV0_BUF_SIZE] = "btrfs";
61 void fixup_argv0(char **argv, const char *token)
63 int len = strlen(argv0_buf);
65 snprintf(argv0_buf + len, sizeof(argv0_buf) - len, " %s", token);
69 void set_argv0(char **argv)
71 strncpy(argv0_buf, argv[0], sizeof(argv0_buf));
72 argv0_buf[sizeof(argv0_buf) - 1] = 0;
75 int check_argc_exact(int nargs, int expected)
78 fprintf(stderr, "%s: too few arguments\n", argv0_buf);
80 fprintf(stderr, "%s: too many arguments\n", argv0_buf);
82 return nargs != expected;
85 int check_argc_min(int nargs, int expected)
87 if (nargs < expected) {
88 fprintf(stderr, "%s: too few arguments\n", argv0_buf);
95 int check_argc_max(int nargs, int expected)
97 if (nargs > expected) {
98 fprintf(stderr, "%s: too many arguments\n", argv0_buf);
107 * Discard the given range in one go
109 static int discard_range(int fd, u64 start, u64 len)
111 u64 range[2] = { start, len };
113 if (ioctl(fd, BLKDISCARD, &range) < 0)
119 * Discard blocks in the given range in 1G chunks, the process is interruptible
121 static int discard_blocks(int fd, u64 start, u64 len)
125 u64 chunk_size = min_t(u64, len, 1*1024*1024*1024);
128 ret = discard_range(fd, start, chunk_size);
138 static u64 reference_root_table[] = {
139 [1] = BTRFS_ROOT_TREE_OBJECTID,
140 [2] = BTRFS_EXTENT_TREE_OBJECTID,
141 [3] = BTRFS_CHUNK_TREE_OBJECTID,
142 [4] = BTRFS_DEV_TREE_OBJECTID,
143 [5] = BTRFS_FS_TREE_OBJECTID,
144 [6] = BTRFS_CSUM_TREE_OBJECTID,
147 int test_uuid_unique(char *fs_uuid)
150 blkid_dev_iterate iter = NULL;
151 blkid_dev dev = NULL;
152 blkid_cache cache = NULL;
154 if (blkid_get_cache(&cache, 0) < 0) {
155 printf("ERROR: lblkid cache get failed\n");
158 blkid_probe_all(cache);
159 iter = blkid_dev_iterate_begin(cache);
160 blkid_dev_set_search(iter, "UUID", fs_uuid);
162 while (blkid_dev_next(iter, &dev) == 0) {
163 dev = blkid_verify(cache, dev);
170 blkid_dev_iterate_end(iter);
171 blkid_put_cache(cache);
176 int make_btrfs(int fd, const char *device, const char *label, char *fs_uuid,
177 u64 blocks[7], u64 num_bytes, u32 nodesize,
178 u32 leafsize, u32 sectorsize, u32 stripesize, u64 features)
180 struct btrfs_super_block super;
181 struct extent_buffer *buf = NULL;
182 struct btrfs_root_item root_item;
183 struct btrfs_disk_key disk_key;
184 struct btrfs_extent_item *extent_item;
185 struct btrfs_inode_item *inode_item;
186 struct btrfs_chunk *chunk;
187 struct btrfs_dev_item *dev_item;
188 struct btrfs_dev_extent *dev_extent;
189 u8 chunk_tree_uuid[BTRFS_UUID_SIZE];
199 int skinny_metadata = !!(features &
200 BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA);
202 first_free = BTRFS_SUPER_INFO_OFFSET + sectorsize * 2 - 1;
203 first_free &= ~((u64)sectorsize - 1);
205 memset(&super, 0, sizeof(super));
207 num_bytes = (num_bytes / sectorsize) * sectorsize;
209 if (uuid_parse(fs_uuid, super.fsid) != 0) {
210 fprintf(stderr, "could not parse UUID: %s\n", fs_uuid);
214 if (!test_uuid_unique(fs_uuid)) {
215 fprintf(stderr, "non-unique UUID: %s\n", fs_uuid);
220 uuid_generate(super.fsid);
222 uuid_generate(super.dev_item.uuid);
223 uuid_generate(chunk_tree_uuid);
225 btrfs_set_super_bytenr(&super, blocks[0]);
226 btrfs_set_super_num_devices(&super, 1);
227 btrfs_set_super_magic(&super, BTRFS_MAGIC);
228 btrfs_set_super_generation(&super, 1);
229 btrfs_set_super_root(&super, blocks[1]);
230 btrfs_set_super_chunk_root(&super, blocks[3]);
231 btrfs_set_super_total_bytes(&super, num_bytes);
232 btrfs_set_super_bytes_used(&super, 6 * leafsize);
233 btrfs_set_super_sectorsize(&super, sectorsize);
234 btrfs_set_super_leafsize(&super, leafsize);
235 btrfs_set_super_nodesize(&super, nodesize);
236 btrfs_set_super_stripesize(&super, stripesize);
237 btrfs_set_super_csum_type(&super, BTRFS_CSUM_TYPE_CRC32);
238 btrfs_set_super_chunk_root_generation(&super, 1);
239 btrfs_set_super_cache_generation(&super, -1);
240 btrfs_set_super_incompat_flags(&super, features);
242 strncpy(super.label, label, BTRFS_LABEL_SIZE - 1);
244 buf = malloc(sizeof(*buf) + max(sectorsize, leafsize));
246 /* create the tree of root objects */
247 memset(buf->data, 0, leafsize);
249 btrfs_set_header_bytenr(buf, blocks[1]);
250 btrfs_set_header_nritems(buf, 4);
251 btrfs_set_header_generation(buf, 1);
252 btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
253 btrfs_set_header_owner(buf, BTRFS_ROOT_TREE_OBJECTID);
254 write_extent_buffer(buf, super.fsid, btrfs_header_fsid(),
257 write_extent_buffer(buf, chunk_tree_uuid,
258 btrfs_header_chunk_tree_uuid(buf),
261 /* create the items for the root tree */
262 memset(&root_item, 0, sizeof(root_item));
263 inode_item = &root_item.inode;
264 btrfs_set_stack_inode_generation(inode_item, 1);
265 btrfs_set_stack_inode_size(inode_item, 3);
266 btrfs_set_stack_inode_nlink(inode_item, 1);
267 btrfs_set_stack_inode_nbytes(inode_item, leafsize);
268 btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
269 btrfs_set_root_refs(&root_item, 1);
270 btrfs_set_root_used(&root_item, leafsize);
271 btrfs_set_root_generation(&root_item, 1);
273 memset(&disk_key, 0, sizeof(disk_key));
274 btrfs_set_disk_key_type(&disk_key, BTRFS_ROOT_ITEM_KEY);
275 btrfs_set_disk_key_offset(&disk_key, 0);
278 itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize) - sizeof(root_item);
279 btrfs_set_root_bytenr(&root_item, blocks[2]);
280 btrfs_set_disk_key_objectid(&disk_key, BTRFS_EXTENT_TREE_OBJECTID);
281 btrfs_set_item_key(buf, &disk_key, nritems);
282 btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
283 btrfs_set_item_size(buf, btrfs_item_nr(nritems),
285 write_extent_buffer(buf, &root_item, btrfs_item_ptr_offset(buf,
286 nritems), sizeof(root_item));
289 itemoff = itemoff - sizeof(root_item);
290 btrfs_set_root_bytenr(&root_item, blocks[4]);
291 btrfs_set_disk_key_objectid(&disk_key, BTRFS_DEV_TREE_OBJECTID);
292 btrfs_set_item_key(buf, &disk_key, nritems);
293 btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
294 btrfs_set_item_size(buf, btrfs_item_nr(nritems),
296 write_extent_buffer(buf, &root_item,
297 btrfs_item_ptr_offset(buf, nritems),
301 itemoff = itemoff - sizeof(root_item);
302 btrfs_set_root_bytenr(&root_item, blocks[5]);
303 btrfs_set_disk_key_objectid(&disk_key, BTRFS_FS_TREE_OBJECTID);
304 btrfs_set_item_key(buf, &disk_key, nritems);
305 btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
306 btrfs_set_item_size(buf, btrfs_item_nr(nritems),
308 write_extent_buffer(buf, &root_item,
309 btrfs_item_ptr_offset(buf, nritems),
313 itemoff = itemoff - sizeof(root_item);
314 btrfs_set_root_bytenr(&root_item, blocks[6]);
315 btrfs_set_disk_key_objectid(&disk_key, BTRFS_CSUM_TREE_OBJECTID);
316 btrfs_set_item_key(buf, &disk_key, nritems);
317 btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
318 btrfs_set_item_size(buf, btrfs_item_nr(nritems),
320 write_extent_buffer(buf, &root_item,
321 btrfs_item_ptr_offset(buf, nritems),
326 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
327 ret = pwrite(fd, buf->data, leafsize, blocks[1]);
328 if (ret != leafsize) {
329 ret = (ret < 0 ? -errno : -EIO);
333 /* create the items for the extent tree */
334 memset(buf->data+sizeof(struct btrfs_header), 0,
335 leafsize-sizeof(struct btrfs_header));
337 itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize);
338 for (i = 1; i < 7; i++) {
339 item_size = sizeof(struct btrfs_extent_item);
340 if (!skinny_metadata)
341 item_size += sizeof(struct btrfs_tree_block_info);
343 BUG_ON(blocks[i] < first_free);
344 BUG_ON(blocks[i] < blocks[i - 1]);
346 /* create extent item */
347 itemoff -= item_size;
348 btrfs_set_disk_key_objectid(&disk_key, blocks[i]);
349 if (skinny_metadata) {
350 btrfs_set_disk_key_type(&disk_key,
351 BTRFS_METADATA_ITEM_KEY);
352 btrfs_set_disk_key_offset(&disk_key, 0);
354 btrfs_set_disk_key_type(&disk_key,
355 BTRFS_EXTENT_ITEM_KEY);
356 btrfs_set_disk_key_offset(&disk_key, leafsize);
358 btrfs_set_item_key(buf, &disk_key, nritems);
359 btrfs_set_item_offset(buf, btrfs_item_nr(nritems),
361 btrfs_set_item_size(buf, btrfs_item_nr(nritems),
363 extent_item = btrfs_item_ptr(buf, nritems,
364 struct btrfs_extent_item);
365 btrfs_set_extent_refs(buf, extent_item, 1);
366 btrfs_set_extent_generation(buf, extent_item, 1);
367 btrfs_set_extent_flags(buf, extent_item,
368 BTRFS_EXTENT_FLAG_TREE_BLOCK);
371 /* create extent ref */
372 ref_root = reference_root_table[i];
373 btrfs_set_disk_key_objectid(&disk_key, blocks[i]);
374 btrfs_set_disk_key_offset(&disk_key, ref_root);
375 btrfs_set_disk_key_type(&disk_key, BTRFS_TREE_BLOCK_REF_KEY);
376 btrfs_set_item_key(buf, &disk_key, nritems);
377 btrfs_set_item_offset(buf, btrfs_item_nr(nritems),
379 btrfs_set_item_size(buf, btrfs_item_nr(nritems), 0);
382 btrfs_set_header_bytenr(buf, blocks[2]);
383 btrfs_set_header_owner(buf, BTRFS_EXTENT_TREE_OBJECTID);
384 btrfs_set_header_nritems(buf, nritems);
385 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
386 ret = pwrite(fd, buf->data, leafsize, blocks[2]);
387 if (ret != leafsize) {
388 ret = (ret < 0 ? -errno : -EIO);
392 /* create the chunk tree */
393 memset(buf->data+sizeof(struct btrfs_header), 0,
394 leafsize-sizeof(struct btrfs_header));
396 item_size = sizeof(*dev_item);
397 itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize) - item_size;
399 /* first device 1 (there is no device 0) */
400 btrfs_set_disk_key_objectid(&disk_key, BTRFS_DEV_ITEMS_OBJECTID);
401 btrfs_set_disk_key_offset(&disk_key, 1);
402 btrfs_set_disk_key_type(&disk_key, BTRFS_DEV_ITEM_KEY);
403 btrfs_set_item_key(buf, &disk_key, nritems);
404 btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
405 btrfs_set_item_size(buf, btrfs_item_nr(nritems), item_size);
407 dev_item = btrfs_item_ptr(buf, nritems, struct btrfs_dev_item);
408 btrfs_set_device_id(buf, dev_item, 1);
409 btrfs_set_device_generation(buf, dev_item, 0);
410 btrfs_set_device_total_bytes(buf, dev_item, num_bytes);
411 btrfs_set_device_bytes_used(buf, dev_item,
412 BTRFS_MKFS_SYSTEM_GROUP_SIZE);
413 btrfs_set_device_io_align(buf, dev_item, sectorsize);
414 btrfs_set_device_io_width(buf, dev_item, sectorsize);
415 btrfs_set_device_sector_size(buf, dev_item, sectorsize);
416 btrfs_set_device_type(buf, dev_item, 0);
418 write_extent_buffer(buf, super.dev_item.uuid,
419 (unsigned long)btrfs_device_uuid(dev_item),
421 write_extent_buffer(buf, super.fsid,
422 (unsigned long)btrfs_device_fsid(dev_item),
424 read_extent_buffer(buf, &super.dev_item, (unsigned long)dev_item,
428 item_size = btrfs_chunk_item_size(1);
429 itemoff = itemoff - item_size;
431 /* then we have chunk 0 */
432 btrfs_set_disk_key_objectid(&disk_key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
433 btrfs_set_disk_key_offset(&disk_key, 0);
434 btrfs_set_disk_key_type(&disk_key, BTRFS_CHUNK_ITEM_KEY);
435 btrfs_set_item_key(buf, &disk_key, nritems);
436 btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
437 btrfs_set_item_size(buf, btrfs_item_nr(nritems), item_size);
439 chunk = btrfs_item_ptr(buf, nritems, struct btrfs_chunk);
440 btrfs_set_chunk_length(buf, chunk, BTRFS_MKFS_SYSTEM_GROUP_SIZE);
441 btrfs_set_chunk_owner(buf, chunk, BTRFS_EXTENT_TREE_OBJECTID);
442 btrfs_set_chunk_stripe_len(buf, chunk, 64 * 1024);
443 btrfs_set_chunk_type(buf, chunk, BTRFS_BLOCK_GROUP_SYSTEM);
444 btrfs_set_chunk_io_align(buf, chunk, sectorsize);
445 btrfs_set_chunk_io_width(buf, chunk, sectorsize);
446 btrfs_set_chunk_sector_size(buf, chunk, sectorsize);
447 btrfs_set_chunk_num_stripes(buf, chunk, 1);
448 btrfs_set_stripe_devid_nr(buf, chunk, 0, 1);
449 btrfs_set_stripe_offset_nr(buf, chunk, 0, 0);
452 write_extent_buffer(buf, super.dev_item.uuid,
453 (unsigned long)btrfs_stripe_dev_uuid(&chunk->stripe),
456 /* copy the key for the chunk to the system array */
457 ptr = super.sys_chunk_array;
458 array_size = sizeof(disk_key);
460 memcpy(ptr, &disk_key, sizeof(disk_key));
461 ptr += sizeof(disk_key);
463 /* copy the chunk to the system array */
464 read_extent_buffer(buf, ptr, (unsigned long)chunk, item_size);
465 array_size += item_size;
467 btrfs_set_super_sys_array_size(&super, array_size);
469 btrfs_set_header_bytenr(buf, blocks[3]);
470 btrfs_set_header_owner(buf, BTRFS_CHUNK_TREE_OBJECTID);
471 btrfs_set_header_nritems(buf, nritems);
472 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
473 ret = pwrite(fd, buf->data, leafsize, blocks[3]);
474 if (ret != leafsize) {
475 ret = (ret < 0 ? -errno : -EIO);
479 /* create the device tree */
480 memset(buf->data+sizeof(struct btrfs_header), 0,
481 leafsize-sizeof(struct btrfs_header));
483 itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize) -
484 sizeof(struct btrfs_dev_extent);
486 btrfs_set_disk_key_objectid(&disk_key, 1);
487 btrfs_set_disk_key_offset(&disk_key, 0);
488 btrfs_set_disk_key_type(&disk_key, BTRFS_DEV_EXTENT_KEY);
489 btrfs_set_item_key(buf, &disk_key, nritems);
490 btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
491 btrfs_set_item_size(buf, btrfs_item_nr(nritems),
492 sizeof(struct btrfs_dev_extent));
493 dev_extent = btrfs_item_ptr(buf, nritems, struct btrfs_dev_extent);
494 btrfs_set_dev_extent_chunk_tree(buf, dev_extent,
495 BTRFS_CHUNK_TREE_OBJECTID);
496 btrfs_set_dev_extent_chunk_objectid(buf, dev_extent,
497 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
498 btrfs_set_dev_extent_chunk_offset(buf, dev_extent, 0);
500 write_extent_buffer(buf, chunk_tree_uuid,
501 (unsigned long)btrfs_dev_extent_chunk_tree_uuid(dev_extent),
504 btrfs_set_dev_extent_length(buf, dev_extent,
505 BTRFS_MKFS_SYSTEM_GROUP_SIZE);
508 btrfs_set_header_bytenr(buf, blocks[4]);
509 btrfs_set_header_owner(buf, BTRFS_DEV_TREE_OBJECTID);
510 btrfs_set_header_nritems(buf, nritems);
511 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
512 ret = pwrite(fd, buf->data, leafsize, blocks[4]);
513 if (ret != leafsize) {
514 ret = (ret < 0 ? -errno : -EIO);
518 /* create the FS root */
519 memset(buf->data+sizeof(struct btrfs_header), 0,
520 leafsize-sizeof(struct btrfs_header));
521 btrfs_set_header_bytenr(buf, blocks[5]);
522 btrfs_set_header_owner(buf, BTRFS_FS_TREE_OBJECTID);
523 btrfs_set_header_nritems(buf, 0);
524 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
525 ret = pwrite(fd, buf->data, leafsize, blocks[5]);
526 if (ret != leafsize) {
527 ret = (ret < 0 ? -errno : -EIO);
530 /* finally create the csum root */
531 memset(buf->data+sizeof(struct btrfs_header), 0,
532 leafsize-sizeof(struct btrfs_header));
533 btrfs_set_header_bytenr(buf, blocks[6]);
534 btrfs_set_header_owner(buf, BTRFS_CSUM_TREE_OBJECTID);
535 btrfs_set_header_nritems(buf, 0);
536 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
537 ret = pwrite(fd, buf->data, leafsize, blocks[6]);
538 if (ret != leafsize) {
539 ret = (ret < 0 ? -errno : -EIO);
543 /* and write out the super block */
544 BUG_ON(sizeof(super) > sectorsize);
545 memset(buf->data, 0, sectorsize);
546 memcpy(buf->data, &super, sizeof(super));
547 buf->len = sectorsize;
548 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
549 ret = pwrite(fd, buf->data, sectorsize, blocks[0]);
550 if (ret != sectorsize) {
551 ret = (ret < 0 ? -errno : -EIO);
562 u64 btrfs_device_size(int fd, struct stat *st)
565 if (S_ISREG(st->st_mode)) {
568 if (!S_ISBLK(st->st_mode)) {
571 if (ioctl(fd, BLKGETSIZE64, &size) >= 0) {
577 static int zero_blocks(int fd, off_t start, size_t len)
579 char *buf = malloc(len);
586 written = pwrite(fd, buf, len, start);
593 #define ZERO_DEV_BYTES (2 * 1024 * 1024)
595 /* don't write outside the device by clamping the region to the device size */
596 static int zero_dev_clamped(int fd, off_t start, ssize_t len, u64 dev_size)
598 off_t end = max(start, start + len);
601 /* and don't overwrite the disk labels on sparc */
602 start = max(start, 1024);
603 end = max(end, 1024);
606 start = min_t(u64, start, dev_size);
607 end = min_t(u64, end, dev_size);
609 return zero_blocks(fd, start, end - start);
612 int btrfs_add_to_fsid(struct btrfs_trans_handle *trans,
613 struct btrfs_root *root, int fd, char *path,
614 u64 block_count, u32 io_width, u32 io_align,
617 struct btrfs_super_block *disk_super;
618 struct btrfs_super_block *super = root->fs_info->super_copy;
619 struct btrfs_device *device;
620 struct btrfs_dev_item *dev_item;
626 device = kzalloc(sizeof(*device), GFP_NOFS);
629 buf = kmalloc(sectorsize, GFP_NOFS);
634 BUG_ON(sizeof(*disk_super) > sectorsize);
635 memset(buf, 0, sectorsize);
637 disk_super = (struct btrfs_super_block *)buf;
638 dev_item = &disk_super->dev_item;
640 uuid_generate(device->uuid);
643 device->io_width = io_width;
644 device->io_align = io_align;
645 device->sector_size = sectorsize;
647 device->writeable = 1;
648 device->total_bytes = block_count;
649 device->bytes_used = 0;
650 device->total_ios = 0;
651 device->dev_root = root->fs_info->dev_root;
653 ret = btrfs_add_device(trans, root, device);
656 total_bytes = btrfs_super_total_bytes(super) + block_count;
657 btrfs_set_super_total_bytes(super, total_bytes);
659 num_devs = btrfs_super_num_devices(super) + 1;
660 btrfs_set_super_num_devices(super, num_devs);
662 memcpy(disk_super, super, sizeof(*disk_super));
664 printf("adding device %s id %llu\n", path,
665 (unsigned long long)device->devid);
667 btrfs_set_super_bytenr(disk_super, BTRFS_SUPER_INFO_OFFSET);
668 btrfs_set_stack_device_id(dev_item, device->devid);
669 btrfs_set_stack_device_type(dev_item, device->type);
670 btrfs_set_stack_device_io_align(dev_item, device->io_align);
671 btrfs_set_stack_device_io_width(dev_item, device->io_width);
672 btrfs_set_stack_device_sector_size(dev_item, device->sector_size);
673 btrfs_set_stack_device_total_bytes(dev_item, device->total_bytes);
674 btrfs_set_stack_device_bytes_used(dev_item, device->bytes_used);
675 memcpy(&dev_item->uuid, device->uuid, BTRFS_UUID_SIZE);
677 ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
678 BUG_ON(ret != sectorsize);
681 list_add(&device->dev_list, &root->fs_info->fs_devices->devices);
682 device->fs_devices = root->fs_info->fs_devices;
686 static void btrfs_wipe_existing_sb(int fd)
688 const char *off = NULL;
693 blkid_probe pr = NULL;
695 pr = blkid_new_probe();
699 if (blkid_probe_set_device(pr, fd, 0, 0))
702 rc = blkid_probe_lookup_value(pr, "SBMAGIC_OFFSET", &off, NULL);
704 rc = blkid_probe_lookup_value(pr, "SBMAGIC", NULL, &len);
706 if (rc || len == 0 || off == NULL)
709 offset = strtoll(off, NULL, 10);
710 if (len > sizeof(buf))
714 rc = pwrite(fd, buf, len, offset);
718 blkid_free_probe(pr);
722 int btrfs_prepare_device(int fd, char *file, int zero_end, u64 *block_count_ret,
723 u64 max_block_count, int *mixed, int discard)
729 ret = fstat(fd, &st);
731 fprintf(stderr, "unable to stat %s\n", file);
735 block_count = btrfs_device_size(fd, &st);
736 if (block_count == 0) {
737 fprintf(stderr, "unable to find %s size\n", file);
741 block_count = min(block_count, max_block_count);
743 if (block_count < BTRFS_MKFS_SMALL_VOLUME_SIZE && !(*mixed))
748 * We intentionally ignore errors from the discard ioctl. It
749 * is not necessary for the mkfs functionality but just an
752 if (discard_range(fd, 0, 0) == 0) {
753 fprintf(stderr, "Performing full device TRIM (%s) ...\n",
754 pretty_size(block_count));
755 discard_blocks(fd, 0, block_count);
759 ret = zero_dev_clamped(fd, 0, ZERO_DEV_BYTES, block_count);
760 for (i = 0 ; !ret && i < BTRFS_SUPER_MIRROR_MAX; i++)
761 ret = zero_dev_clamped(fd, btrfs_sb_offset(i),
762 BTRFS_SUPER_INFO_SIZE, block_count);
763 if (!ret && zero_end)
764 ret = zero_dev_clamped(fd, block_count - ZERO_DEV_BYTES,
765 ZERO_DEV_BYTES, block_count);
768 fprintf(stderr, "ERROR: failed to zero device '%s' - %s\n",
769 file, strerror(-ret));
773 btrfs_wipe_existing_sb(fd);
775 *block_count_ret = block_count;
779 int btrfs_make_root_dir(struct btrfs_trans_handle *trans,
780 struct btrfs_root *root, u64 objectid)
783 struct btrfs_inode_item inode_item;
784 time_t now = time(NULL);
786 memset(&inode_item, 0, sizeof(inode_item));
787 btrfs_set_stack_inode_generation(&inode_item, trans->transid);
788 btrfs_set_stack_inode_size(&inode_item, 0);
789 btrfs_set_stack_inode_nlink(&inode_item, 1);
790 btrfs_set_stack_inode_nbytes(&inode_item, root->leafsize);
791 btrfs_set_stack_inode_mode(&inode_item, S_IFDIR | 0755);
792 btrfs_set_stack_timespec_sec(&inode_item.atime, now);
793 btrfs_set_stack_timespec_nsec(&inode_item.atime, 0);
794 btrfs_set_stack_timespec_sec(&inode_item.ctime, now);
795 btrfs_set_stack_timespec_nsec(&inode_item.ctime, 0);
796 btrfs_set_stack_timespec_sec(&inode_item.mtime, now);
797 btrfs_set_stack_timespec_nsec(&inode_item.mtime, 0);
798 btrfs_set_stack_timespec_sec(&inode_item.otime, 0);
799 btrfs_set_stack_timespec_nsec(&inode_item.otime, 0);
801 if (root->fs_info->tree_root == root)
802 btrfs_set_super_root_dir(root->fs_info->super_copy, objectid);
804 ret = btrfs_insert_inode(trans, root, objectid, &inode_item);
808 ret = btrfs_insert_inode_ref(trans, root, "..", 2, objectid, objectid, 0);
812 btrfs_set_root_dirid(&root->root_item, objectid);
819 * checks if a path is a block device node
820 * Returns negative errno on failure, otherwise
821 * returns 1 for blockdev, 0 for not-blockdev
823 int is_block_device(const char *path)
827 if (stat(path, &statbuf) < 0)
830 return S_ISBLK(statbuf.st_mode);
834 * check if given path is a mount point
835 * return 1 if yes. 0 if no. -1 for error
837 int is_mount_point(const char *path)
843 f = setmntent("/proc/self/mounts", "r");
847 while ((mnt = getmntent(f)) != NULL) {
848 if (strcmp(mnt->mnt_dir, path))
858 * Find the mount point for a mounted device.
859 * On success, returns 0 with mountpoint in *mp.
860 * On failure, returns -errno (not mounted yields -EINVAL)
861 * Is noisy on failures, expects to be given a mounted device.
863 int get_btrfs_mount(const char *dev, char *mp, size_t mp_size)
868 ret = is_block_device(dev);
871 fprintf(stderr, "%s is not a block device\n", dev);
874 fprintf(stderr, "Could not check %s: %s\n",
875 dev, strerror(-ret));
880 fd = open(dev, O_RDONLY);
883 fprintf(stderr, "Could not open %s: %s\n", dev, strerror(errno));
887 ret = check_mounted_where(fd, dev, mp, mp_size, NULL);
890 } else { /* mounted, all good */
900 * Given a pathname, return a filehandle to:
901 * the original pathname or,
902 * if the pathname is a mounted btrfs device, to its mountpoint.
904 * On error, return -1, errno should be set.
906 int open_path_or_dev_mnt(const char *path, DIR **dirstream)
908 char mp[BTRFS_PATH_NAME_MAX + 1];
911 if (is_block_device(path)) {
914 ret = get_btrfs_mount(path, mp, sizeof(mp));
916 /* not a mounted btrfs dev */
920 fdmnt = open_file_or_dir(mp, dirstream);
922 fdmnt = open_file_or_dir(path, dirstream);
928 /* checks if a device is a loop device */
929 static int is_loop_device (const char* device) {
932 if(stat(device, &statbuf) < 0)
935 return (S_ISBLK(statbuf.st_mode) &&
936 MAJOR(statbuf.st_rdev) == LOOP_MAJOR);
940 /* Takes a loop device path (e.g. /dev/loop0) and returns
941 * the associated file (e.g. /images/my_btrfs.img) */
942 static int resolve_loop_device(const char* loop_dev, char* loop_file,
949 char real_loop_dev[PATH_MAX];
951 if (!realpath(loop_dev, real_loop_dev))
953 snprintf(p, PATH_MAX, "/sys/block/%s/loop/backing_file", strrchr(real_loop_dev, '/'));
954 if (!(f = fopen(p, "r")))
957 snprintf(fmt, 20, "%%%i[^\n]", max_len-1);
958 ret = fscanf(f, fmt, loop_file);
966 /* Checks whether a and b are identical or device
967 * files associated with the same block device
969 static int is_same_blk_file(const char* a, const char* b)
971 struct stat st_buf_a, st_buf_b;
972 char real_a[PATH_MAX];
973 char real_b[PATH_MAX];
975 if(!realpath(a, real_a))
978 if (!realpath(b, real_b))
981 /* Identical path? */
982 if(strcmp(real_a, real_b) == 0)
985 if(stat(a, &st_buf_a) < 0 ||
986 stat(b, &st_buf_b) < 0)
993 /* Same blockdevice? */
994 if(S_ISBLK(st_buf_a.st_mode) &&
995 S_ISBLK(st_buf_b.st_mode) &&
996 st_buf_a.st_rdev == st_buf_b.st_rdev)
1002 if (st_buf_a.st_dev == st_buf_b.st_dev &&
1003 st_buf_a.st_ino == st_buf_b.st_ino)
1011 /* checks if a and b are identical or device
1012 * files associated with the same block device or
1013 * if one file is a loop device that uses the other
1016 static int is_same_loop_file(const char* a, const char* b)
1018 char res_a[PATH_MAX];
1019 char res_b[PATH_MAX];
1020 const char* final_a = NULL;
1021 const char* final_b = NULL;
1024 /* Resolve a if it is a loop device */
1025 if((ret = is_loop_device(a)) < 0) {
1030 ret = resolve_loop_device(a, res_a, sizeof(res_a));
1041 /* Resolve b if it is a loop device */
1042 if ((ret = is_loop_device(b)) < 0) {
1047 ret = resolve_loop_device(b, res_b, sizeof(res_b));
1058 return is_same_blk_file(final_a, final_b);
1061 /* Checks if a file exists and is a block or regular file*/
1062 static int is_existing_blk_or_reg_file(const char* filename)
1066 if(stat(filename, &st_buf) < 0) {
1073 return (S_ISBLK(st_buf.st_mode) || S_ISREG(st_buf.st_mode));
1076 /* Checks if a file is used (directly or indirectly via a loop device)
1077 * by a device in fs_devices
1079 static int blk_file_in_dev_list(struct btrfs_fs_devices* fs_devices,
1083 struct list_head *head;
1084 struct list_head *cur;
1085 struct btrfs_device *device;
1087 head = &fs_devices->devices;
1088 list_for_each(cur, head) {
1089 device = list_entry(cur, struct btrfs_device, dev_list);
1091 if((ret = is_same_loop_file(device->name, file)))
1099 * Resolve a pathname to a device mapper node to /dev/mapper/<name>
1100 * Returns NULL on invalid input or malloc failure; Other failures
1101 * will be handled by the caller using the input pathame.
1103 char *canonicalize_dm_name(const char *ptname)
1107 char path[PATH_MAX], name[PATH_MAX], *res = NULL;
1109 if (!ptname || !*ptname)
1112 snprintf(path, sizeof(path), "/sys/block/%s/dm/name", ptname);
1113 if (!(f = fopen(path, "r")))
1116 /* read <name>\n from sysfs */
1117 if (fgets(name, sizeof(name), f) && (sz = strlen(name)) > 1) {
1118 name[sz - 1] = '\0';
1119 snprintf(path, sizeof(path), "/dev/mapper/%s", name);
1121 if (access(path, F_OK) == 0)
1129 * Resolve a pathname to a canonical device node, e.g. /dev/sda1 or
1130 * to a device mapper pathname.
1131 * Returns NULL on invalid input or malloc failure; Other failures
1132 * will be handled by the caller using the input pathame.
1134 char *canonicalize_path(const char *path)
1136 char *canonical, *p;
1138 if (!path || !*path)
1141 canonical = realpath(path, NULL);
1143 return strdup(path);
1144 p = strrchr(canonical, '/');
1145 if (p && strncmp(p, "/dm-", 4) == 0 && isdigit(*(p + 4))) {
1146 char *dm = canonicalize_dm_name(p + 1);
1157 * returns 1 if the device was mounted, < 0 on error or 0 if everything
1158 * is safe to continue.
1160 int check_mounted(const char* file)
1165 fd = open(file, O_RDONLY);
1167 fprintf (stderr, "check_mounted(): Could not open %s\n", file);
1171 ret = check_mounted_where(fd, file, NULL, 0, NULL);
1177 int check_mounted_where(int fd, const char *file, char *where, int size,
1178 struct btrfs_fs_devices **fs_dev_ret)
1183 struct btrfs_fs_devices *fs_devices_mnt = NULL;
1187 /* scan the initial device */
1188 ret = btrfs_scan_one_device(fd, file, &fs_devices_mnt,
1189 &total_devs, BTRFS_SUPER_INFO_OFFSET, 0);
1190 is_btrfs = (ret >= 0);
1192 /* scan other devices */
1193 if (is_btrfs && total_devs > 1) {
1194 ret = btrfs_scan_lblkid();
1199 /* iterate over the list of currently mountes filesystems */
1200 if ((f = setmntent ("/proc/self/mounts", "r")) == NULL)
1203 while ((mnt = getmntent (f)) != NULL) {
1205 if(strcmp(mnt->mnt_type, "btrfs") != 0)
1208 ret = blk_file_in_dev_list(fs_devices_mnt, mnt->mnt_fsname);
1210 /* ignore entries in the mount table that are not
1211 associated with a file*/
1212 if((ret = is_existing_blk_or_reg_file(mnt->mnt_fsname)) < 0)
1213 goto out_mntloop_err;
1217 ret = is_same_loop_file(file, mnt->mnt_fsname);
1221 goto out_mntloop_err;
1226 /* Did we find an entry in mnt table? */
1227 if (mnt && size && where) {
1228 strncpy(where, mnt->mnt_dir, size);
1232 *fs_dev_ret = fs_devices_mnt;
1234 ret = (mnt != NULL);
1242 struct pending_dir {
1243 struct list_head list;
1244 char name[PATH_MAX];
1247 int btrfs_register_one_device(const char *fname)
1249 struct btrfs_ioctl_vol_args args;
1254 fd = open("/dev/btrfs-control", O_RDWR);
1256 fprintf(stderr, "failed to open /dev/btrfs-control "
1257 "skipping device registration: %s\n",
1261 strncpy(args.name, fname, BTRFS_PATH_NAME_MAX);
1262 args.name[BTRFS_PATH_NAME_MAX-1] = 0;
1263 ret = ioctl(fd, BTRFS_IOC_SCAN_DEV, &args);
1266 fprintf(stderr, "ERROR: device scan failed '%s' - %s\n",
1267 fname, strerror(e));
1275 * Register all devices in the fs_uuid list created in the user
1276 * space. Ensure btrfs_scan_lblkid() is called before this func.
1278 int btrfs_register_all_devices(void)
1281 struct btrfs_fs_devices *fs_devices;
1282 struct btrfs_device *device;
1283 struct list_head *all_uuids;
1285 all_uuids = btrfs_scanned_uuids();
1287 list_for_each_entry(fs_devices, all_uuids, list) {
1288 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1289 if (strlen(device->name) != 0) {
1290 err = btrfs_register_one_device(device->name);
1301 int btrfs_device_already_in_root(struct btrfs_root *root, int fd,
1304 struct btrfs_super_block *disk_super;
1308 buf = malloc(BTRFS_SUPER_INFO_SIZE);
1313 ret = pread(fd, buf, BTRFS_SUPER_INFO_SIZE, super_offset);
1314 if (ret != BTRFS_SUPER_INFO_SIZE)
1318 disk_super = (struct btrfs_super_block *)buf;
1319 if (btrfs_super_magic(disk_super) != BTRFS_MAGIC)
1322 if (!memcmp(disk_super->fsid, root->fs_info->super_copy->fsid,
1331 static const char* unit_suffix_binary[] =
1332 { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"};
1333 static const char* unit_suffix_decimal[] =
1334 { "B", "kB", "MB", "GB", "TB", "PB", "EB"};
1336 int pretty_size_snprintf(u64 size, char *str, size_t str_size, unsigned unit_mode)
1342 const char** suffix = NULL;
1348 if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_RAW) {
1349 snprintf(str, str_size, "%llu", size);
1353 if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_BINARY) {
1356 suffix = unit_suffix_binary;
1357 } else if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_DECIMAL) {
1360 suffix = unit_suffix_decimal;
1365 fprintf(stderr, "INTERNAL ERROR: unknown unit base, mode %d\n",
1373 switch (unit_mode & UNITS_MODE_MASK) {
1374 case UNITS_TBYTES: base *= mult; num_divs++;
1375 case UNITS_GBYTES: base *= mult; num_divs++;
1376 case UNITS_MBYTES: base *= mult; num_divs++;
1377 case UNITS_KBYTES: num_divs++;
1384 while (size >= mult) {
1391 if (num_divs >= ARRAY_SIZE(unit_suffix_binary)) {
1393 printf("INTERNAL ERROR: unsupported unit suffix, index %d\n",
1398 fraction = (float)last_size / base;
1400 return snprintf(str, str_size, "%.2f%s", fraction, suffix[num_divs]);
1404 * __strncpy__null - strncpy with null termination
1405 * @dest: the target array
1406 * @src: the source string
1407 * @n: maximum bytes to copy (size of *dest)
1409 * Like strncpy, but ensures destination is null-terminated.
1411 * Copies the string pointed to by src, including the terminating null
1412 * byte ('\0'), to the buffer pointed to by dest, up to a maximum
1413 * of n bytes. Then ensure that dest is null-terminated.
1415 char *__strncpy__null(char *dest, const char *src, size_t n)
1417 strncpy(dest, src, n);
1424 * Checks to make sure that the label matches our requirements.
1426 0 if everything is safe and usable
1427 -1 if the label is too long
1429 static int check_label(const char *input)
1431 int len = strlen(input);
1433 if (len > BTRFS_LABEL_SIZE - 1) {
1434 fprintf(stderr, "ERROR: Label %s is too long (max %d)\n",
1435 input, BTRFS_LABEL_SIZE - 1);
1442 static int set_label_unmounted(const char *dev, const char *label)
1444 struct btrfs_trans_handle *trans;
1445 struct btrfs_root *root;
1448 ret = check_mounted(dev);
1450 fprintf(stderr, "FATAL: error checking %s mount status\n", dev);
1454 fprintf(stderr, "ERROR: dev %s is mounted, use mount point\n",
1459 /* Open the super_block at the default location
1460 * and as read-write.
1462 root = open_ctree(dev, 0, OPEN_CTREE_WRITES);
1463 if (!root) /* errors are printed by open_ctree() */
1466 trans = btrfs_start_transaction(root, 1);
1467 snprintf(root->fs_info->super_copy->label, BTRFS_LABEL_SIZE, "%s",
1469 btrfs_commit_transaction(trans, root);
1471 /* Now we close it since we are done. */
1476 static int set_label_mounted(const char *mount_path, const char *label)
1480 fd = open(mount_path, O_RDONLY | O_NOATIME);
1482 fprintf(stderr, "ERROR: unable to access '%s'\n", mount_path);
1486 if (ioctl(fd, BTRFS_IOC_SET_FSLABEL, label) < 0) {
1487 fprintf(stderr, "ERROR: unable to set label %s\n",
1497 static int get_label_unmounted(const char *dev, char *label)
1499 struct btrfs_root *root;
1502 ret = check_mounted(dev);
1504 fprintf(stderr, "FATAL: error checking %s mount status\n", dev);
1508 fprintf(stderr, "ERROR: dev %s is mounted, use mount point\n",
1513 /* Open the super_block at the default location
1516 root = open_ctree(dev, 0, 0);
1520 memcpy(label, root->fs_info->super_copy->label, BTRFS_LABEL_SIZE);
1522 /* Now we close it since we are done. */
1528 * If a partition is mounted, try to get the filesystem label via its
1529 * mounted path rather than device. Return the corresponding error
1530 * the user specified the device path.
1532 int get_label_mounted(const char *mount_path, char *labelp)
1534 char label[BTRFS_LABEL_SIZE];
1537 fd = open(mount_path, O_RDONLY | O_NOATIME);
1539 fprintf(stderr, "ERROR: unable to access '%s'\n", mount_path);
1543 memset(label, '\0', sizeof(label));
1544 if (ioctl(fd, BTRFS_IOC_GET_FSLABEL, label) < 0) {
1545 fprintf(stderr, "ERROR: unable get label %s\n", strerror(errno));
1550 strncpy(labelp, label, sizeof(label));
1555 int get_label(const char *btrfs_dev, char *label)
1559 ret = is_existing_blk_or_reg_file(btrfs_dev);
1561 ret = get_label_mounted(btrfs_dev, label);
1563 ret = get_label_unmounted(btrfs_dev, label);
1568 int set_label(const char *btrfs_dev, const char *label)
1572 if (check_label(label))
1575 ret = is_existing_blk_or_reg_file(btrfs_dev);
1577 ret = set_label_mounted(btrfs_dev, label);
1579 ret = set_label_unmounted(btrfs_dev, label);
1584 int btrfs_scan_block_devices(int run_ioctl)
1590 struct btrfs_fs_devices *tmp_devices;
1592 FILE *proc_partitions;
1600 proc_partitions = fopen("/proc/partitions","r");
1601 if (!proc_partitions) {
1602 fprintf(stderr, "Unable to open '/proc/partitions' for scanning\n");
1605 /* skip the header */
1606 for (i = 0; i < 2; i++)
1607 if (!fgets(buf, 1023, proc_partitions)) {
1609 "Unable to read '/proc/partitions' for scanning\n");
1610 fclose(proc_partitions);
1614 strcpy(fullpath,"/dev/");
1615 while(fgets(buf, 1023, proc_partitions)) {
1616 ret = sscanf(buf," %*d %*d %*d %99s", fullpath + 5);
1619 "failed to scan device name from /proc/partitions\n");
1624 * multipath and MD devices may register as a btrfs filesystem
1625 * both through the original block device and through
1626 * the special (/dev/mapper or /dev/mdX) entry.
1627 * This scans the special entries last
1629 special = strncmp(fullpath, "/dev/dm-", strlen("/dev/dm-")) == 0;
1631 special = strncmp(fullpath, "/dev/md", strlen("/dev/md")) == 0;
1633 if (scans == 0 && special)
1635 if (scans > 0 && !special)
1638 ret = lstat(fullpath, &st);
1640 fprintf(stderr, "failed to stat %s\n", fullpath);
1643 if (!S_ISBLK(st.st_mode)) {
1647 fd = open(fullpath, O_RDONLY);
1649 if (errno != ENOMEDIUM)
1650 fprintf(stderr, "failed to open %s: %s\n",
1651 fullpath, strerror(errno));
1654 ret = btrfs_scan_one_device(fd, fullpath, &tmp_devices,
1656 BTRFS_SUPER_INFO_OFFSET, 0);
1657 if (ret == 0 && run_ioctl > 0) {
1658 btrfs_register_one_device(fullpath);
1663 fclose(proc_partitions);
1673 * A not-so-good version fls64. No fascinating optimization since
1674 * no one except parse_size use it
1676 static int fls64(u64 x)
1680 for (i = 0; i <64; i++)
1681 if (x << i & (1ULL << 63))
1686 u64 parse_size(char *s)
1694 fprintf(stderr, "ERROR: Size value is empty\n");
1699 "ERROR: Size value '%s' is less equal than 0\n", s);
1702 ret = strtoull(s, &endptr, 10);
1704 fprintf(stderr, "ERROR: Size value '%s' is invalid\n", s);
1707 if (endptr[0] && endptr[1]) {
1708 fprintf(stderr, "ERROR: Illegal suffix contains character '%c' in wrong position\n",
1713 * strtoll returns LLONG_MAX when overflow, if this happens,
1714 * need to call strtoull to get the real size
1716 if (errno == ERANGE && ret == ULLONG_MAX) {
1718 "ERROR: Size value '%s' is too large for u64\n", s);
1722 c = tolower(endptr[0]);
1745 fprintf(stderr, "ERROR: Unknown size descriptor '%c'\n",
1750 /* Check whether ret * mult overflow */
1751 if (fls64(ret) + fls64(mult) - 1 > 64) {
1753 "ERROR: Size value '%s' is too large for u64\n", s);
1760 int open_file_or_dir3(const char *fname, DIR **dirstream, int open_flags)
1766 ret = stat(fname, &st);
1770 if (S_ISDIR(st.st_mode)) {
1771 *dirstream = opendir(fname);
1774 fd = dirfd(*dirstream);
1775 } else if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
1776 fd = open(fname, open_flags);
1779 * we set this on purpose, in case the caller output
1780 * strerror(errno) as success
1788 closedir(*dirstream);
1793 int open_file_or_dir(const char *fname, DIR **dirstream)
1795 return open_file_or_dir3(fname, dirstream, O_RDWR);
1798 void close_file_or_dir(int fd, DIR *dirstream)
1801 closedir(dirstream);
1806 int get_device_info(int fd, u64 devid,
1807 struct btrfs_ioctl_dev_info_args *di_args)
1811 di_args->devid = devid;
1812 memset(&di_args->uuid, '\0', sizeof(di_args->uuid));
1814 ret = ioctl(fd, BTRFS_IOC_DEV_INFO, di_args);
1815 return ret ? -errno : 0;
1819 * For a given path, fill in the ioctl fs_ and info_ args.
1820 * If the path is a btrfs mountpoint, fill info for all devices.
1821 * If the path is a btrfs device, fill in only that device.
1823 * The path provided must be either on a mounted btrfs fs,
1824 * or be a mounted btrfs device.
1826 * Returns 0 on success, or a negative errno.
1828 int get_fs_info(char *path, struct btrfs_ioctl_fs_info_args *fi_args,
1829 struct btrfs_ioctl_dev_info_args **di_ret)
1835 struct btrfs_fs_devices *fs_devices_mnt = NULL;
1836 struct btrfs_ioctl_dev_info_args *di_args;
1837 char mp[BTRFS_PATH_NAME_MAX + 1];
1838 DIR *dirstream = NULL;
1840 memset(fi_args, 0, sizeof(*fi_args));
1842 if (is_block_device(path)) {
1843 struct btrfs_super_block *disk_super;
1844 char buf[BTRFS_SUPER_INFO_SIZE];
1847 /* Ensure it's mounted, then set path to the mountpoint */
1848 fd = open(path, O_RDONLY);
1851 fprintf(stderr, "Couldn't open %s: %s\n",
1852 path, strerror(errno));
1855 ret = check_mounted_where(fd, path, mp, sizeof(mp),
1864 /* Only fill in this one device */
1865 fi_args->num_devices = 1;
1867 disk_super = (struct btrfs_super_block *)buf;
1868 ret = btrfs_read_dev_super(fd, disk_super,
1869 BTRFS_SUPER_INFO_OFFSET, 0);
1874 devid = btrfs_stack_device_id(&disk_super->dev_item);
1876 fi_args->max_id = devid;
1879 memcpy(fi_args->fsid, fs_devices_mnt->fsid, BTRFS_FSID_SIZE);
1883 /* at this point path must not be for a block device */
1884 fd = open_file_or_dir(path, &dirstream);
1890 /* fill in fi_args if not just a single device */
1891 if (fi_args->num_devices != 1) {
1892 ret = ioctl(fd, BTRFS_IOC_FS_INFO, fi_args);
1899 if (!fi_args->num_devices)
1902 di_args = *di_ret = malloc((fi_args->num_devices) * sizeof(*di_args));
1908 for (; i <= fi_args->max_id; ++i) {
1909 BUG_ON(ndevs >= fi_args->num_devices);
1910 ret = get_device_info(fd, i, &di_args[ndevs]);
1919 * only when the only dev we wanted to find is not there then
1920 * let any error be returned
1922 if (fi_args->num_devices != 1) {
1928 close_file_or_dir(fd, dirstream);
1932 #define isoctal(c) (((c) & ~7) == '0')
1934 static inline void translate(char *f, char *t)
1936 while (*f != '\0') {
1938 isoctal(f[1]) && isoctal(f[2]) && isoctal(f[3])) {
1939 *t++ = 64*(f[1] & 7) + 8*(f[2] & 7) + (f[3] & 7);
1949 * Checks if the swap device.
1950 * Returns 1 if swap device, < 0 on error or 0 if not swap device.
1952 static int is_swap_device(const char *file)
1963 if (stat(file, &st_buf) < 0)
1965 if (S_ISBLK(st_buf.st_mode))
1966 dev = st_buf.st_rdev;
1967 else if (S_ISREG(st_buf.st_mode)) {
1968 dev = st_buf.st_dev;
1969 ino = st_buf.st_ino;
1973 if ((f = fopen("/proc/swaps", "r")) == NULL)
1976 /* skip the first line */
1977 if (fgets(tmp, sizeof(tmp), f) == NULL)
1980 while (fgets(tmp, sizeof(tmp), f) != NULL) {
1981 if ((cp = strchr(tmp, ' ')) != NULL)
1983 if ((cp = strchr(tmp, '\t')) != NULL)
1985 translate(tmp, buf);
1986 if (stat(buf, &st_buf) != 0)
1988 if (S_ISBLK(st_buf.st_mode)) {
1989 if (dev == st_buf.st_rdev) {
1993 } else if (S_ISREG(st_buf.st_mode)) {
1994 if (dev == st_buf.st_dev && ino == st_buf.st_ino) {
2008 * Check for existing filesystem or partition table on device.
2010 * 1 for existing fs or partition
2011 * 0 for nothing found
2012 * -1 for internal error
2019 blkid_probe pr = NULL;
2023 if (!device || !*device)
2026 ret = -1; /* will reset on success of all setup calls */
2028 pr = blkid_new_probe_from_filename(device);
2032 size = blkid_probe_get_size(pr);
2036 /* nothing to overwrite on a 0-length device */
2042 ret = blkid_probe_enable_partitions(pr, 1);
2046 ret = blkid_do_fullprobe(pr);
2051 * Blkid returns 1 for nothing found and 0 when it finds a signature,
2052 * but we want the exact opposite, so reverse the return value here.
2054 * In addition print some useful diagnostics about what actually is
2062 if (!blkid_probe_lookup_value(pr, "TYPE", &type, NULL)) {
2064 "%s appears to contain an existing "
2065 "filesystem (%s).\n", device, type);
2066 } else if (!blkid_probe_lookup_value(pr, "PTTYPE", &type, NULL)) {
2068 "%s appears to contain a partition "
2069 "table (%s).\n", device, type);
2072 "%s appears to contain something weird "
2073 "according to blkid\n", device);
2079 blkid_free_probe(pr);
2082 "probe of %s failed, cannot detect "
2083 "existing filesystem.\n", device);
2087 static int group_profile_devs_min(u64 flag)
2089 switch (flag & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
2090 case 0: /* single */
2091 case BTRFS_BLOCK_GROUP_DUP:
2093 case BTRFS_BLOCK_GROUP_RAID0:
2094 case BTRFS_BLOCK_GROUP_RAID1:
2095 case BTRFS_BLOCK_GROUP_RAID5:
2097 case BTRFS_BLOCK_GROUP_RAID6:
2099 case BTRFS_BLOCK_GROUP_RAID10:
2106 int test_num_disk_vs_raid(u64 metadata_profile, u64 data_profile,
2107 u64 dev_cnt, int mixed, char *estr)
2115 allowed |= BTRFS_BLOCK_GROUP_RAID10;
2117 allowed |= BTRFS_BLOCK_GROUP_RAID6;
2119 allowed |= BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
2120 BTRFS_BLOCK_GROUP_RAID5;
2123 allowed |= BTRFS_BLOCK_GROUP_DUP;
2127 ((metadata_profile | data_profile) & BTRFS_BLOCK_GROUP_DUP)) {
2129 "DUP is not allowed when FS has multiple devices\n");
2132 if (metadata_profile & ~allowed) {
2134 "unable to create FS with metadata profile %s "
2135 "(have %llu devices but %d devices are required)\n",
2136 btrfs_group_profile_str(metadata_profile), dev_cnt,
2137 group_profile_devs_min(metadata_profile));
2140 if (data_profile & ~allowed) {
2142 "unable to create FS with data profile %s "
2143 "(have %llu devices but %d devices are required)\n",
2144 btrfs_group_profile_str(data_profile), dev_cnt,
2145 group_profile_devs_min(data_profile));
2149 if (!mixed && (data_profile & BTRFS_BLOCK_GROUP_DUP)) {
2151 "dup for data is allowed only in mixed mode");
2157 /* Check if disk is suitable for btrfs
2159 * 1: something is wrong, estr provides the error
2162 int test_dev_for_mkfs(char *file, int force_overwrite, char *estr)
2168 ret = is_swap_device(file);
2170 snprintf(estr, sz, "error checking %s status: %s\n", file,
2175 snprintf(estr, sz, "%s is a swap device\n", file);
2178 if (!force_overwrite) {
2179 if (check_overwrite(file)) {
2180 snprintf(estr, sz, "Use the -f option to force overwrite.\n");
2184 ret = check_mounted(file);
2186 snprintf(estr, sz, "error checking %s mount status\n",
2191 snprintf(estr, sz, "%s is mounted\n", file);
2194 /* check if the device is busy */
2195 fd = open(file, O_RDWR|O_EXCL);
2197 snprintf(estr, sz, "unable to open %s: %s\n", file,
2201 if (fstat(fd, &st)) {
2202 snprintf(estr, sz, "unable to stat %s: %s\n", file,
2207 if (!S_ISBLK(st.st_mode)) {
2208 fprintf(stderr, "'%s' is not a block device\n", file);
2216 int btrfs_scan_lblkid()
2221 struct btrfs_fs_devices *tmp_devices;
2222 blkid_dev_iterate iter = NULL;
2223 blkid_dev dev = NULL;
2224 blkid_cache cache = NULL;
2225 char path[PATH_MAX];
2227 if (btrfs_scan_done)
2230 if (blkid_get_cache(&cache, 0) < 0) {
2231 printf("ERROR: lblkid cache get failed\n");
2234 blkid_probe_all(cache);
2235 iter = blkid_dev_iterate_begin(cache);
2236 blkid_dev_set_search(iter, "TYPE", "btrfs");
2237 while (blkid_dev_next(iter, &dev) == 0) {
2238 dev = blkid_verify(cache, dev);
2241 /* if we are here its definitely a btrfs disk*/
2242 strncpy(path, blkid_dev_devname(dev), PATH_MAX);
2244 fd = open(path, O_RDONLY);
2246 printf("ERROR: could not open %s\n", path);
2249 ret = btrfs_scan_one_device(fd, path, &tmp_devices,
2250 &num_devices, BTRFS_SUPER_INFO_OFFSET, 0);
2252 printf("ERROR: could not scan %s\n", path);
2259 blkid_dev_iterate_end(iter);
2260 blkid_put_cache(cache);
2262 btrfs_scan_done = 1;
2267 int is_vol_small(char *file)
2274 fd = open(file, O_RDONLY);
2277 if (fstat(fd, &st) < 0) {
2282 size = btrfs_device_size(fd, &st);
2287 if (size < BTRFS_MKFS_SMALL_VOLUME_SIZE) {
2297 * This reads a line from the stdin and only returns non-zero if the
2298 * first whitespace delimited token is a case insensitive match with yes
2301 int ask_user(char *question)
2303 char buf[30] = {0,};
2304 char *saveptr = NULL;
2307 printf("%s [y/N]: ", question);
2309 return fgets(buf, sizeof(buf) - 1, stdin) &&
2310 (answer = strtok_r(buf, " \t\n\r", &saveptr)) &&
2311 (!strcasecmp(answer, "yes") || !strcasecmp(answer, "y"));
2316 * - file or directory return the containing tree root id
2317 * - subvolume return its own tree id
2318 * - BTRFS_EMPTY_SUBVOL_DIR_OBJECTID (directory with ino == 2) the result is
2319 * undefined and function returns -1
2321 int lookup_ino_rootid(int fd, u64 *rootid)
2323 struct btrfs_ioctl_ino_lookup_args args;
2327 memset(&args, 0, sizeof(args));
2329 args.objectid = BTRFS_FIRST_FREE_OBJECTID;
2331 ret = ioctl(fd, BTRFS_IOC_INO_LOOKUP, &args);
2334 fprintf(stderr, "ERROR: Failed to lookup root id - %s\n",
2339 *rootid = args.treeid;
2345 * return 0 if a btrfs mount point is found
2346 * return 1 if a mount point is found but not btrfs
2347 * return <0 if something goes wrong
2349 int find_mount_root(const char *path, char **mount_root)
2357 int longest_matchlen = 0;
2358 char *longest_match = NULL;
2360 fd = open(path, O_RDONLY | O_NOATIME);
2365 mnttab = setmntent("/proc/self/mounts", "r");
2369 while ((ent = getmntent(mnttab))) {
2370 len = strlen(ent->mnt_dir);
2371 if (strncmp(ent->mnt_dir, path, len) == 0) {
2372 /* match found and use the latest match */
2373 if (longest_matchlen <= len) {
2374 free(longest_match);
2375 longest_matchlen = len;
2376 longest_match = strdup(ent->mnt_dir);
2377 not_btrfs = strcmp(ent->mnt_type, "btrfs");
2386 free(longest_match);
2391 *mount_root = realpath(longest_match, NULL);
2395 free(longest_match);
2399 int test_minimum_size(const char *file, u32 leafsize)
2402 struct stat statbuf;
2404 fd = open(file, O_RDONLY);
2407 if (stat(file, &statbuf) < 0) {
2411 if (btrfs_device_size(fd, &statbuf) < btrfs_min_dev_size(leafsize)) {
2420 * test if name is a correct subvolume name
2421 * this function return
2422 * 0-> name is not a correct subvolume name
2423 * 1-> name is a correct subvolume name
2425 int test_issubvolname(const char *name)
2427 return name[0] != '\0' && !strchr(name, '/') &&
2428 strcmp(name, ".") && strcmp(name, "..");
2432 * test if path is a directory
2433 * this function return
2434 * 0-> path exists but it is not a directory
2435 * 1-> path exists and it is a directory
2436 * -1 -> path is unaccessible
2438 int test_isdir(const char *path)
2443 ret = stat(path, &st);
2447 return S_ISDIR(st.st_mode);
2450 void units_set_mode(unsigned *units, unsigned mode)
2452 unsigned base = *units & UNITS_MODE_MASK;
2454 *units = base | mode;
2457 void units_set_base(unsigned *units, unsigned base)
2459 unsigned mode = *units & ~UNITS_MODE_MASK;
2461 *units = base | mode;
2464 int find_next_key(struct btrfs_path *path, struct btrfs_key *key)
2468 for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2469 if (!path->nodes[level])
2471 if (path->slots[level] + 1 >=
2472 btrfs_header_nritems(path->nodes[level]))
2475 btrfs_item_key_to_cpu(path->nodes[level], key,
2476 path->slots[level] + 1);
2478 btrfs_node_key_to_cpu(path->nodes[level], key,
2479 path->slots[level] + 1);
2485 char* btrfs_group_type_str(u64 flag)
2487 u64 mask = BTRFS_BLOCK_GROUP_TYPE_MASK |
2488 BTRFS_SPACE_INFO_GLOBAL_RSV;
2490 switch (flag & mask) {
2491 case BTRFS_BLOCK_GROUP_DATA:
2493 case BTRFS_BLOCK_GROUP_SYSTEM:
2495 case BTRFS_BLOCK_GROUP_METADATA:
2497 case BTRFS_BLOCK_GROUP_DATA|BTRFS_BLOCK_GROUP_METADATA:
2498 return "Data+Metadata";
2499 case BTRFS_SPACE_INFO_GLOBAL_RSV:
2500 return "GlobalReserve";
2506 char* btrfs_group_profile_str(u64 flag)
2508 switch (flag & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
2511 case BTRFS_BLOCK_GROUP_RAID0:
2513 case BTRFS_BLOCK_GROUP_RAID1:
2515 case BTRFS_BLOCK_GROUP_RAID5:
2517 case BTRFS_BLOCK_GROUP_RAID6:
2519 case BTRFS_BLOCK_GROUP_DUP:
2521 case BTRFS_BLOCK_GROUP_RAID10:
2528 u64 disk_size(char *path)
2532 if (statfs(path, &sfs) < 0)
2535 return sfs.f_bsize * sfs.f_blocks;
2538 u64 get_partition_size(char *dev)
2541 int fd = open(dev, O_RDONLY);
2545 if (ioctl(fd, BLKGETSIZE64, &result) < 0) {