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 char argv0_buf[ARGV0_BUF_SIZE] = "btrfs";
57 void fixup_argv0(char **argv, const char *token)
59 int len = strlen(argv0_buf);
61 snprintf(argv0_buf + len, sizeof(argv0_buf) - len, " %s", token);
65 void set_argv0(char **argv)
67 sprintf(argv0_buf, "%s", argv[0]);
70 int check_argc_exact(int nargs, int expected)
73 fprintf(stderr, "%s: too few arguments\n", argv0_buf);
75 fprintf(stderr, "%s: too many arguments\n", argv0_buf);
77 return nargs != expected;
80 int check_argc_min(int nargs, int expected)
82 if (nargs < expected) {
83 fprintf(stderr, "%s: too few arguments\n", argv0_buf);
90 int check_argc_max(int nargs, int expected)
92 if (nargs > expected) {
93 fprintf(stderr, "%s: too many arguments\n", argv0_buf);
102 * Discard the given range in one go
104 static int discard_range(int fd, u64 start, u64 len)
106 u64 range[2] = { start, len };
108 if (ioctl(fd, BLKDISCARD, &range) < 0)
114 * Discard blocks in the given range in 1G chunks, the process is interruptible
116 static int discard_blocks(int fd, u64 start, u64 len)
120 u64 chunk_size = min_t(u64, len, 1*1024*1024*1024);
123 ret = discard_range(fd, start, chunk_size);
133 static u64 reference_root_table[] = {
134 [1] = BTRFS_ROOT_TREE_OBJECTID,
135 [2] = BTRFS_EXTENT_TREE_OBJECTID,
136 [3] = BTRFS_CHUNK_TREE_OBJECTID,
137 [4] = BTRFS_DEV_TREE_OBJECTID,
138 [5] = BTRFS_FS_TREE_OBJECTID,
139 [6] = BTRFS_CSUM_TREE_OBJECTID,
142 int test_uuid_unique(char *fs_uuid)
145 blkid_dev_iterate iter = NULL;
146 blkid_dev dev = NULL;
147 blkid_cache cache = NULL;
149 if (blkid_get_cache(&cache, 0) < 0) {
150 printf("ERROR: lblkid cache get failed\n");
153 blkid_probe_all(cache);
154 iter = blkid_dev_iterate_begin(cache);
155 blkid_dev_set_search(iter, "UUID", fs_uuid);
157 while (blkid_dev_next(iter, &dev) == 0) {
158 dev = blkid_verify(cache, dev);
165 blkid_dev_iterate_end(iter);
166 blkid_put_cache(cache);
171 int make_btrfs(int fd, const char *device, const char *label, char *fs_uuid,
172 u64 blocks[7], u64 num_bytes, u32 nodesize,
173 u32 leafsize, u32 sectorsize, u32 stripesize, u64 features)
175 struct btrfs_super_block super;
176 struct extent_buffer *buf = NULL;
177 struct btrfs_root_item root_item;
178 struct btrfs_disk_key disk_key;
179 struct btrfs_extent_item *extent_item;
180 struct btrfs_inode_item *inode_item;
181 struct btrfs_chunk *chunk;
182 struct btrfs_dev_item *dev_item;
183 struct btrfs_dev_extent *dev_extent;
184 u8 chunk_tree_uuid[BTRFS_UUID_SIZE];
194 int skinny_metadata = !!(features &
195 BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA);
197 first_free = BTRFS_SUPER_INFO_OFFSET + sectorsize * 2 - 1;
198 first_free &= ~((u64)sectorsize - 1);
200 memset(&super, 0, sizeof(super));
202 num_bytes = (num_bytes / sectorsize) * sectorsize;
204 if (uuid_parse(fs_uuid, super.fsid) != 0) {
205 fprintf(stderr, "could not parse UUID: %s\n", fs_uuid);
209 if (!test_uuid_unique(fs_uuid)) {
210 fprintf(stderr, "non-unique UUID: %s\n", fs_uuid);
215 uuid_generate(super.fsid);
217 uuid_generate(super.dev_item.uuid);
218 uuid_generate(chunk_tree_uuid);
220 btrfs_set_super_bytenr(&super, blocks[0]);
221 btrfs_set_super_num_devices(&super, 1);
222 btrfs_set_super_magic(&super, BTRFS_MAGIC);
223 btrfs_set_super_generation(&super, 1);
224 btrfs_set_super_root(&super, blocks[1]);
225 btrfs_set_super_chunk_root(&super, blocks[3]);
226 btrfs_set_super_total_bytes(&super, num_bytes);
227 btrfs_set_super_bytes_used(&super, 6 * leafsize);
228 btrfs_set_super_sectorsize(&super, sectorsize);
229 btrfs_set_super_leafsize(&super, leafsize);
230 btrfs_set_super_nodesize(&super, nodesize);
231 btrfs_set_super_stripesize(&super, stripesize);
232 btrfs_set_super_csum_type(&super, BTRFS_CSUM_TYPE_CRC32);
233 btrfs_set_super_chunk_root_generation(&super, 1);
234 btrfs_set_super_cache_generation(&super, -1);
235 btrfs_set_super_incompat_flags(&super, features);
237 strncpy(super.label, label, BTRFS_LABEL_SIZE - 1);
239 buf = malloc(sizeof(*buf) + max(sectorsize, leafsize));
241 /* create the tree of root objects */
242 memset(buf->data, 0, leafsize);
244 btrfs_set_header_bytenr(buf, blocks[1]);
245 btrfs_set_header_nritems(buf, 4);
246 btrfs_set_header_generation(buf, 1);
247 btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
248 btrfs_set_header_owner(buf, BTRFS_ROOT_TREE_OBJECTID);
249 write_extent_buffer(buf, super.fsid, btrfs_header_fsid(),
252 write_extent_buffer(buf, chunk_tree_uuid,
253 btrfs_header_chunk_tree_uuid(buf),
256 /* create the items for the root tree */
257 memset(&root_item, 0, sizeof(root_item));
258 inode_item = &root_item.inode;
259 btrfs_set_stack_inode_generation(inode_item, 1);
260 btrfs_set_stack_inode_size(inode_item, 3);
261 btrfs_set_stack_inode_nlink(inode_item, 1);
262 btrfs_set_stack_inode_nbytes(inode_item, leafsize);
263 btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
264 btrfs_set_root_refs(&root_item, 1);
265 btrfs_set_root_used(&root_item, leafsize);
266 btrfs_set_root_generation(&root_item, 1);
268 memset(&disk_key, 0, sizeof(disk_key));
269 btrfs_set_disk_key_type(&disk_key, BTRFS_ROOT_ITEM_KEY);
270 btrfs_set_disk_key_offset(&disk_key, 0);
273 itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize) - sizeof(root_item);
274 btrfs_set_root_bytenr(&root_item, blocks[2]);
275 btrfs_set_disk_key_objectid(&disk_key, BTRFS_EXTENT_TREE_OBJECTID);
276 btrfs_set_item_key(buf, &disk_key, nritems);
277 btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
278 btrfs_set_item_size(buf, btrfs_item_nr(nritems),
280 write_extent_buffer(buf, &root_item, btrfs_item_ptr_offset(buf,
281 nritems), sizeof(root_item));
284 itemoff = itemoff - sizeof(root_item);
285 btrfs_set_root_bytenr(&root_item, blocks[4]);
286 btrfs_set_disk_key_objectid(&disk_key, BTRFS_DEV_TREE_OBJECTID);
287 btrfs_set_item_key(buf, &disk_key, nritems);
288 btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
289 btrfs_set_item_size(buf, btrfs_item_nr(nritems),
291 write_extent_buffer(buf, &root_item,
292 btrfs_item_ptr_offset(buf, nritems),
296 itemoff = itemoff - sizeof(root_item);
297 btrfs_set_root_bytenr(&root_item, blocks[5]);
298 btrfs_set_disk_key_objectid(&disk_key, BTRFS_FS_TREE_OBJECTID);
299 btrfs_set_item_key(buf, &disk_key, nritems);
300 btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
301 btrfs_set_item_size(buf, btrfs_item_nr(nritems),
303 write_extent_buffer(buf, &root_item,
304 btrfs_item_ptr_offset(buf, nritems),
308 itemoff = itemoff - sizeof(root_item);
309 btrfs_set_root_bytenr(&root_item, blocks[6]);
310 btrfs_set_disk_key_objectid(&disk_key, BTRFS_CSUM_TREE_OBJECTID);
311 btrfs_set_item_key(buf, &disk_key, nritems);
312 btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
313 btrfs_set_item_size(buf, btrfs_item_nr(nritems),
315 write_extent_buffer(buf, &root_item,
316 btrfs_item_ptr_offset(buf, nritems),
321 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
322 ret = pwrite(fd, buf->data, leafsize, blocks[1]);
323 if (ret != leafsize) {
324 ret = (ret < 0 ? -errno : -EIO);
328 /* create the items for the extent tree */
329 memset(buf->data+sizeof(struct btrfs_header), 0,
330 leafsize-sizeof(struct btrfs_header));
332 itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize);
333 for (i = 1; i < 7; i++) {
334 item_size = sizeof(struct btrfs_extent_item);
335 if (!skinny_metadata)
336 item_size += sizeof(struct btrfs_tree_block_info);
338 BUG_ON(blocks[i] < first_free);
339 BUG_ON(blocks[i] < blocks[i - 1]);
341 /* create extent item */
342 itemoff -= item_size;
343 btrfs_set_disk_key_objectid(&disk_key, blocks[i]);
344 if (skinny_metadata) {
345 btrfs_set_disk_key_type(&disk_key,
346 BTRFS_METADATA_ITEM_KEY);
347 btrfs_set_disk_key_offset(&disk_key, 0);
349 btrfs_set_disk_key_type(&disk_key,
350 BTRFS_EXTENT_ITEM_KEY);
351 btrfs_set_disk_key_offset(&disk_key, leafsize);
353 btrfs_set_item_key(buf, &disk_key, nritems);
354 btrfs_set_item_offset(buf, btrfs_item_nr(nritems),
356 btrfs_set_item_size(buf, btrfs_item_nr(nritems),
358 extent_item = btrfs_item_ptr(buf, nritems,
359 struct btrfs_extent_item);
360 btrfs_set_extent_refs(buf, extent_item, 1);
361 btrfs_set_extent_generation(buf, extent_item, 1);
362 btrfs_set_extent_flags(buf, extent_item,
363 BTRFS_EXTENT_FLAG_TREE_BLOCK);
366 /* create extent ref */
367 ref_root = reference_root_table[i];
368 btrfs_set_disk_key_objectid(&disk_key, blocks[i]);
369 btrfs_set_disk_key_offset(&disk_key, ref_root);
370 btrfs_set_disk_key_type(&disk_key, BTRFS_TREE_BLOCK_REF_KEY);
371 btrfs_set_item_key(buf, &disk_key, nritems);
372 btrfs_set_item_offset(buf, btrfs_item_nr(nritems),
374 btrfs_set_item_size(buf, btrfs_item_nr(nritems), 0);
377 btrfs_set_header_bytenr(buf, blocks[2]);
378 btrfs_set_header_owner(buf, BTRFS_EXTENT_TREE_OBJECTID);
379 btrfs_set_header_nritems(buf, nritems);
380 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
381 ret = pwrite(fd, buf->data, leafsize, blocks[2]);
382 if (ret != leafsize) {
383 ret = (ret < 0 ? -errno : -EIO);
387 /* create the chunk tree */
388 memset(buf->data+sizeof(struct btrfs_header), 0,
389 leafsize-sizeof(struct btrfs_header));
391 item_size = sizeof(*dev_item);
392 itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize) - item_size;
394 /* first device 1 (there is no device 0) */
395 btrfs_set_disk_key_objectid(&disk_key, BTRFS_DEV_ITEMS_OBJECTID);
396 btrfs_set_disk_key_offset(&disk_key, 1);
397 btrfs_set_disk_key_type(&disk_key, BTRFS_DEV_ITEM_KEY);
398 btrfs_set_item_key(buf, &disk_key, nritems);
399 btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
400 btrfs_set_item_size(buf, btrfs_item_nr(nritems), item_size);
402 dev_item = btrfs_item_ptr(buf, nritems, struct btrfs_dev_item);
403 btrfs_set_device_id(buf, dev_item, 1);
404 btrfs_set_device_generation(buf, dev_item, 0);
405 btrfs_set_device_total_bytes(buf, dev_item, num_bytes);
406 btrfs_set_device_bytes_used(buf, dev_item,
407 BTRFS_MKFS_SYSTEM_GROUP_SIZE);
408 btrfs_set_device_io_align(buf, dev_item, sectorsize);
409 btrfs_set_device_io_width(buf, dev_item, sectorsize);
410 btrfs_set_device_sector_size(buf, dev_item, sectorsize);
411 btrfs_set_device_type(buf, dev_item, 0);
413 write_extent_buffer(buf, super.dev_item.uuid,
414 (unsigned long)btrfs_device_uuid(dev_item),
416 write_extent_buffer(buf, super.fsid,
417 (unsigned long)btrfs_device_fsid(dev_item),
419 read_extent_buffer(buf, &super.dev_item, (unsigned long)dev_item,
423 item_size = btrfs_chunk_item_size(1);
424 itemoff = itemoff - item_size;
426 /* then we have chunk 0 */
427 btrfs_set_disk_key_objectid(&disk_key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
428 btrfs_set_disk_key_offset(&disk_key, 0);
429 btrfs_set_disk_key_type(&disk_key, BTRFS_CHUNK_ITEM_KEY);
430 btrfs_set_item_key(buf, &disk_key, nritems);
431 btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
432 btrfs_set_item_size(buf, btrfs_item_nr(nritems), item_size);
434 chunk = btrfs_item_ptr(buf, nritems, struct btrfs_chunk);
435 btrfs_set_chunk_length(buf, chunk, BTRFS_MKFS_SYSTEM_GROUP_SIZE);
436 btrfs_set_chunk_owner(buf, chunk, BTRFS_EXTENT_TREE_OBJECTID);
437 btrfs_set_chunk_stripe_len(buf, chunk, 64 * 1024);
438 btrfs_set_chunk_type(buf, chunk, BTRFS_BLOCK_GROUP_SYSTEM);
439 btrfs_set_chunk_io_align(buf, chunk, sectorsize);
440 btrfs_set_chunk_io_width(buf, chunk, sectorsize);
441 btrfs_set_chunk_sector_size(buf, chunk, sectorsize);
442 btrfs_set_chunk_num_stripes(buf, chunk, 1);
443 btrfs_set_stripe_devid_nr(buf, chunk, 0, 1);
444 btrfs_set_stripe_offset_nr(buf, chunk, 0, 0);
447 write_extent_buffer(buf, super.dev_item.uuid,
448 (unsigned long)btrfs_stripe_dev_uuid(&chunk->stripe),
451 /* copy the key for the chunk to the system array */
452 ptr = super.sys_chunk_array;
453 array_size = sizeof(disk_key);
455 memcpy(ptr, &disk_key, sizeof(disk_key));
456 ptr += sizeof(disk_key);
458 /* copy the chunk to the system array */
459 read_extent_buffer(buf, ptr, (unsigned long)chunk, item_size);
460 array_size += item_size;
462 btrfs_set_super_sys_array_size(&super, array_size);
464 btrfs_set_header_bytenr(buf, blocks[3]);
465 btrfs_set_header_owner(buf, BTRFS_CHUNK_TREE_OBJECTID);
466 btrfs_set_header_nritems(buf, nritems);
467 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
468 ret = pwrite(fd, buf->data, leafsize, blocks[3]);
469 if (ret != leafsize) {
470 ret = (ret < 0 ? -errno : -EIO);
474 /* create the device tree */
475 memset(buf->data+sizeof(struct btrfs_header), 0,
476 leafsize-sizeof(struct btrfs_header));
478 itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize) -
479 sizeof(struct btrfs_dev_extent);
481 btrfs_set_disk_key_objectid(&disk_key, 1);
482 btrfs_set_disk_key_offset(&disk_key, 0);
483 btrfs_set_disk_key_type(&disk_key, BTRFS_DEV_EXTENT_KEY);
484 btrfs_set_item_key(buf, &disk_key, nritems);
485 btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
486 btrfs_set_item_size(buf, btrfs_item_nr(nritems),
487 sizeof(struct btrfs_dev_extent));
488 dev_extent = btrfs_item_ptr(buf, nritems, struct btrfs_dev_extent);
489 btrfs_set_dev_extent_chunk_tree(buf, dev_extent,
490 BTRFS_CHUNK_TREE_OBJECTID);
491 btrfs_set_dev_extent_chunk_objectid(buf, dev_extent,
492 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
493 btrfs_set_dev_extent_chunk_offset(buf, dev_extent, 0);
495 write_extent_buffer(buf, chunk_tree_uuid,
496 (unsigned long)btrfs_dev_extent_chunk_tree_uuid(dev_extent),
499 btrfs_set_dev_extent_length(buf, dev_extent,
500 BTRFS_MKFS_SYSTEM_GROUP_SIZE);
503 btrfs_set_header_bytenr(buf, blocks[4]);
504 btrfs_set_header_owner(buf, BTRFS_DEV_TREE_OBJECTID);
505 btrfs_set_header_nritems(buf, nritems);
506 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
507 ret = pwrite(fd, buf->data, leafsize, blocks[4]);
508 if (ret != leafsize) {
509 ret = (ret < 0 ? -errno : -EIO);
513 /* create the FS root */
514 memset(buf->data+sizeof(struct btrfs_header), 0,
515 leafsize-sizeof(struct btrfs_header));
516 btrfs_set_header_bytenr(buf, blocks[5]);
517 btrfs_set_header_owner(buf, BTRFS_FS_TREE_OBJECTID);
518 btrfs_set_header_nritems(buf, 0);
519 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
520 ret = pwrite(fd, buf->data, leafsize, blocks[5]);
521 if (ret != leafsize) {
522 ret = (ret < 0 ? -errno : -EIO);
525 /* finally create the csum root */
526 memset(buf->data+sizeof(struct btrfs_header), 0,
527 leafsize-sizeof(struct btrfs_header));
528 btrfs_set_header_bytenr(buf, blocks[6]);
529 btrfs_set_header_owner(buf, BTRFS_CSUM_TREE_OBJECTID);
530 btrfs_set_header_nritems(buf, 0);
531 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
532 ret = pwrite(fd, buf->data, leafsize, blocks[6]);
533 if (ret != leafsize) {
534 ret = (ret < 0 ? -errno : -EIO);
538 /* and write out the super block */
539 BUG_ON(sizeof(super) > sectorsize);
540 memset(buf->data, 0, sectorsize);
541 memcpy(buf->data, &super, sizeof(super));
542 buf->len = sectorsize;
543 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
544 ret = pwrite(fd, buf->data, sectorsize, blocks[0]);
545 if (ret != sectorsize) {
546 ret = (ret < 0 ? -errno : -EIO);
557 u64 btrfs_device_size(int fd, struct stat *st)
560 if (S_ISREG(st->st_mode)) {
563 if (!S_ISBLK(st->st_mode)) {
566 if (ioctl(fd, BLKGETSIZE64, &size) >= 0) {
572 static int zero_blocks(int fd, off_t start, size_t len)
574 char *buf = malloc(len);
581 written = pwrite(fd, buf, len, start);
588 #define ZERO_DEV_BYTES (2 * 1024 * 1024)
590 /* don't write outside the device by clamping the region to the device size */
591 static int zero_dev_clamped(int fd, off_t start, ssize_t len, u64 dev_size)
593 off_t end = max(start, start + len);
596 /* and don't overwrite the disk labels on sparc */
597 start = max(start, 1024);
598 end = max(end, 1024);
601 start = min_t(u64, start, dev_size);
602 end = min_t(u64, end, dev_size);
604 return zero_blocks(fd, start, end - start);
607 int btrfs_add_to_fsid(struct btrfs_trans_handle *trans,
608 struct btrfs_root *root, int fd, char *path,
609 u64 block_count, u32 io_width, u32 io_align,
612 struct btrfs_super_block *disk_super;
613 struct btrfs_super_block *super = root->fs_info->super_copy;
614 struct btrfs_device *device;
615 struct btrfs_dev_item *dev_item;
621 device = kzalloc(sizeof(*device), GFP_NOFS);
624 buf = kmalloc(sectorsize, GFP_NOFS);
629 BUG_ON(sizeof(*disk_super) > sectorsize);
630 memset(buf, 0, sectorsize);
632 disk_super = (struct btrfs_super_block *)buf;
633 dev_item = &disk_super->dev_item;
635 uuid_generate(device->uuid);
638 device->io_width = io_width;
639 device->io_align = io_align;
640 device->sector_size = sectorsize;
642 device->writeable = 1;
643 device->total_bytes = block_count;
644 device->bytes_used = 0;
645 device->total_ios = 0;
646 device->dev_root = root->fs_info->dev_root;
648 ret = btrfs_add_device(trans, root, device);
651 total_bytes = btrfs_super_total_bytes(super) + block_count;
652 btrfs_set_super_total_bytes(super, total_bytes);
654 num_devs = btrfs_super_num_devices(super) + 1;
655 btrfs_set_super_num_devices(super, num_devs);
657 memcpy(disk_super, super, sizeof(*disk_super));
659 printf("adding device %s id %llu\n", path,
660 (unsigned long long)device->devid);
662 btrfs_set_super_bytenr(disk_super, BTRFS_SUPER_INFO_OFFSET);
663 btrfs_set_stack_device_id(dev_item, device->devid);
664 btrfs_set_stack_device_type(dev_item, device->type);
665 btrfs_set_stack_device_io_align(dev_item, device->io_align);
666 btrfs_set_stack_device_io_width(dev_item, device->io_width);
667 btrfs_set_stack_device_sector_size(dev_item, device->sector_size);
668 btrfs_set_stack_device_total_bytes(dev_item, device->total_bytes);
669 btrfs_set_stack_device_bytes_used(dev_item, device->bytes_used);
670 memcpy(&dev_item->uuid, device->uuid, BTRFS_UUID_SIZE);
672 ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
673 BUG_ON(ret != sectorsize);
676 list_add(&device->dev_list, &root->fs_info->fs_devices->devices);
677 device->fs_devices = root->fs_info->fs_devices;
681 int btrfs_prepare_device(int fd, char *file, int zero_end, u64 *block_count_ret,
682 u64 max_block_count, int *mixed, int discard)
688 ret = fstat(fd, &st);
690 fprintf(stderr, "unable to stat %s\n", file);
694 block_count = btrfs_device_size(fd, &st);
695 if (block_count == 0) {
696 fprintf(stderr, "unable to find %s size\n", file);
700 block_count = min(block_count, max_block_count);
702 if (block_count < BTRFS_MKFS_SMALL_VOLUME_SIZE && !(*mixed)) {
703 printf("SMALL VOLUME: forcing mixed metadata/data groups\n");
709 * We intentionally ignore errors from the discard ioctl. It
710 * is not necessary for the mkfs functionality but just an
713 if (discard_range(fd, 0, 0) == 0) {
714 fprintf(stderr, "Performing full device TRIM (%s) ...\n",
715 pretty_size(block_count));
716 discard_blocks(fd, 0, block_count);
720 ret = zero_dev_clamped(fd, 0, ZERO_DEV_BYTES, block_count);
721 for (i = 0 ; !ret && i < BTRFS_SUPER_MIRROR_MAX; i++)
722 ret = zero_dev_clamped(fd, btrfs_sb_offset(i),
723 BTRFS_SUPER_INFO_SIZE, block_count);
724 if (!ret && zero_end)
725 ret = zero_dev_clamped(fd, block_count - ZERO_DEV_BYTES,
726 ZERO_DEV_BYTES, block_count);
729 fprintf(stderr, "ERROR: failed to zero device '%s' - %s\n",
730 file, strerror(-ret));
734 *block_count_ret = block_count;
738 int btrfs_make_root_dir(struct btrfs_trans_handle *trans,
739 struct btrfs_root *root, u64 objectid)
742 struct btrfs_inode_item inode_item;
743 time_t now = time(NULL);
745 memset(&inode_item, 0, sizeof(inode_item));
746 btrfs_set_stack_inode_generation(&inode_item, trans->transid);
747 btrfs_set_stack_inode_size(&inode_item, 0);
748 btrfs_set_stack_inode_nlink(&inode_item, 1);
749 btrfs_set_stack_inode_nbytes(&inode_item, root->leafsize);
750 btrfs_set_stack_inode_mode(&inode_item, S_IFDIR | 0755);
751 btrfs_set_stack_timespec_sec(&inode_item.atime, now);
752 btrfs_set_stack_timespec_nsec(&inode_item.atime, 0);
753 btrfs_set_stack_timespec_sec(&inode_item.ctime, now);
754 btrfs_set_stack_timespec_nsec(&inode_item.ctime, 0);
755 btrfs_set_stack_timespec_sec(&inode_item.mtime, now);
756 btrfs_set_stack_timespec_nsec(&inode_item.mtime, 0);
757 btrfs_set_stack_timespec_sec(&inode_item.otime, 0);
758 btrfs_set_stack_timespec_nsec(&inode_item.otime, 0);
760 if (root->fs_info->tree_root == root)
761 btrfs_set_super_root_dir(root->fs_info->super_copy, objectid);
763 ret = btrfs_insert_inode(trans, root, objectid, &inode_item);
767 ret = btrfs_insert_inode_ref(trans, root, "..", 2, objectid, objectid, 0);
771 btrfs_set_root_dirid(&root->root_item, objectid);
778 * checks if a path is a block device node
779 * Returns negative errno on failure, otherwise
780 * returns 1 for blockdev, 0 for not-blockdev
782 int is_block_device(const char *path)
786 if (stat(path, &statbuf) < 0)
789 return S_ISBLK(statbuf.st_mode);
793 * check if given path is a mount point
794 * return 1 if yes. 0 if no. -1 for error
796 int is_mount_point(const char *path)
802 f = setmntent("/proc/self/mounts", "r");
806 while ((mnt = getmntent(f)) != NULL) {
807 if (strcmp(mnt->mnt_dir, path))
817 * Find the mount point for a mounted device.
818 * On success, returns 0 with mountpoint in *mp.
819 * On failure, returns -errno (not mounted yields -EINVAL)
820 * Is noisy on failures, expects to be given a mounted device.
822 int get_btrfs_mount(const char *dev, char *mp, size_t mp_size)
827 ret = is_block_device(dev);
830 fprintf(stderr, "%s is not a block device\n", dev);
833 fprintf(stderr, "Could not check %s: %s\n",
834 dev, strerror(-ret));
839 fd = open(dev, O_RDONLY);
842 fprintf(stderr, "Could not open %s: %s\n", dev, strerror(errno));
846 ret = check_mounted_where(fd, dev, mp, mp_size, NULL);
849 } else { /* mounted, all good */
859 * Given a pathname, return a filehandle to:
860 * the original pathname or,
861 * if the pathname is a mounted btrfs device, to its mountpoint.
863 * On error, return -1, errno should be set.
865 int open_path_or_dev_mnt(const char *path, DIR **dirstream)
867 char mp[BTRFS_PATH_NAME_MAX + 1];
870 if (is_block_device(path)) {
873 ret = get_btrfs_mount(path, mp, sizeof(mp));
875 /* not a mounted btrfs dev */
879 fdmnt = open_file_or_dir(mp, dirstream);
881 fdmnt = open_file_or_dir(path, dirstream);
887 /* checks if a device is a loop device */
888 static int is_loop_device (const char* device) {
891 if(stat(device, &statbuf) < 0)
894 return (S_ISBLK(statbuf.st_mode) &&
895 MAJOR(statbuf.st_rdev) == LOOP_MAJOR);
899 /* Takes a loop device path (e.g. /dev/loop0) and returns
900 * the associated file (e.g. /images/my_btrfs.img) */
901 static int resolve_loop_device(const char* loop_dev, char* loop_file,
908 char real_loop_dev[PATH_MAX];
910 if (!realpath(loop_dev, real_loop_dev))
912 snprintf(p, PATH_MAX, "/sys/block/%s/loop/backing_file", strrchr(real_loop_dev, '/'));
913 if (!(f = fopen(p, "r")))
916 snprintf(fmt, 20, "%%%i[^\n]", max_len-1);
917 ret = fscanf(f, fmt, loop_file);
925 /* Checks whether a and b are identical or device
926 * files associated with the same block device
928 static int is_same_blk_file(const char* a, const char* b)
930 struct stat st_buf_a, st_buf_b;
931 char real_a[PATH_MAX];
932 char real_b[PATH_MAX];
934 if(!realpath(a, real_a))
937 if (!realpath(b, real_b))
940 /* Identical path? */
941 if(strcmp(real_a, real_b) == 0)
944 if(stat(a, &st_buf_a) < 0 ||
945 stat(b, &st_buf_b) < 0)
952 /* Same blockdevice? */
953 if(S_ISBLK(st_buf_a.st_mode) &&
954 S_ISBLK(st_buf_b.st_mode) &&
955 st_buf_a.st_rdev == st_buf_b.st_rdev)
961 if (st_buf_a.st_dev == st_buf_b.st_dev &&
962 st_buf_a.st_ino == st_buf_b.st_ino)
970 /* checks if a and b are identical or device
971 * files associated with the same block device or
972 * if one file is a loop device that uses the other
975 static int is_same_loop_file(const char* a, const char* b)
977 char res_a[PATH_MAX];
978 char res_b[PATH_MAX];
979 const char* final_a = NULL;
980 const char* final_b = NULL;
983 /* Resolve a if it is a loop device */
984 if((ret = is_loop_device(a)) < 0) {
989 ret = resolve_loop_device(a, res_a, sizeof(res_a));
1000 /* Resolve b if it is a loop device */
1001 if ((ret = is_loop_device(b)) < 0) {
1006 ret = resolve_loop_device(b, res_b, sizeof(res_b));
1017 return is_same_blk_file(final_a, final_b);
1020 /* Checks if a file exists and is a block or regular file*/
1021 static int is_existing_blk_or_reg_file(const char* filename)
1025 if(stat(filename, &st_buf) < 0) {
1032 return (S_ISBLK(st_buf.st_mode) || S_ISREG(st_buf.st_mode));
1035 /* Checks if a file is used (directly or indirectly via a loop device)
1036 * by a device in fs_devices
1038 static int blk_file_in_dev_list(struct btrfs_fs_devices* fs_devices,
1042 struct list_head *head;
1043 struct list_head *cur;
1044 struct btrfs_device *device;
1046 head = &fs_devices->devices;
1047 list_for_each(cur, head) {
1048 device = list_entry(cur, struct btrfs_device, dev_list);
1050 if((ret = is_same_loop_file(device->name, file)))
1058 * Resolve a pathname to a device mapper node to /dev/mapper/<name>
1059 * Returns NULL on invalid input or malloc failure; Other failures
1060 * will be handled by the caller using the input pathame.
1062 char *canonicalize_dm_name(const char *ptname)
1066 char path[PATH_MAX], name[PATH_MAX], *res = NULL;
1068 if (!ptname || !*ptname)
1071 snprintf(path, sizeof(path), "/sys/block/%s/dm/name", ptname);
1072 if (!(f = fopen(path, "r")))
1075 /* read <name>\n from sysfs */
1076 if (fgets(name, sizeof(name), f) && (sz = strlen(name)) > 1) {
1077 name[sz - 1] = '\0';
1078 snprintf(path, sizeof(path), "/dev/mapper/%s", name);
1080 if (access(path, F_OK) == 0)
1088 * Resolve a pathname to a canonical device node, e.g. /dev/sda1 or
1089 * to a device mapper pathname.
1090 * Returns NULL on invalid input or malloc failure; Other failures
1091 * will be handled by the caller using the input pathame.
1093 char *canonicalize_path(const char *path)
1095 char *canonical, *p;
1097 if (!path || !*path)
1100 canonical = realpath(path, NULL);
1102 return strdup(path);
1103 p = strrchr(canonical, '/');
1104 if (p && strncmp(p, "/dm-", 4) == 0 && isdigit(*(p + 4))) {
1105 char *dm = canonicalize_dm_name(p + 1);
1116 * returns 1 if the device was mounted, < 0 on error or 0 if everything
1117 * is safe to continue.
1119 int check_mounted(const char* file)
1124 fd = open(file, O_RDONLY);
1126 fprintf (stderr, "check_mounted(): Could not open %s\n", file);
1130 ret = check_mounted_where(fd, file, NULL, 0, NULL);
1136 int check_mounted_where(int fd, const char *file, char *where, int size,
1137 struct btrfs_fs_devices **fs_dev_ret)
1142 struct btrfs_fs_devices *fs_devices_mnt = NULL;
1146 /* scan the initial device */
1147 ret = btrfs_scan_one_device(fd, file, &fs_devices_mnt,
1148 &total_devs, BTRFS_SUPER_INFO_OFFSET, 0);
1149 is_btrfs = (ret >= 0);
1151 /* scan other devices */
1152 if (is_btrfs && total_devs > 1) {
1153 if ((ret = btrfs_scan_for_fsid(!BTRFS_UPDATE_KERNEL)))
1157 /* iterate over the list of currently mountes filesystems */
1158 if ((f = setmntent ("/proc/self/mounts", "r")) == NULL)
1161 while ((mnt = getmntent (f)) != NULL) {
1163 if(strcmp(mnt->mnt_type, "btrfs") != 0)
1166 ret = blk_file_in_dev_list(fs_devices_mnt, mnt->mnt_fsname);
1168 /* ignore entries in the mount table that are not
1169 associated with a file*/
1170 if((ret = is_existing_blk_or_reg_file(mnt->mnt_fsname)) < 0)
1171 goto out_mntloop_err;
1175 ret = is_same_loop_file(file, mnt->mnt_fsname);
1179 goto out_mntloop_err;
1184 /* Did we find an entry in mnt table? */
1185 if (mnt && size && where) {
1186 strncpy(where, mnt->mnt_dir, size);
1190 *fs_dev_ret = fs_devices_mnt;
1192 ret = (mnt != NULL);
1200 struct pending_dir {
1201 struct list_head list;
1202 char name[PATH_MAX];
1205 void btrfs_register_one_device(char *fname)
1207 struct btrfs_ioctl_vol_args args;
1212 fd = open("/dev/btrfs-control", O_RDONLY);
1214 fprintf(stderr, "failed to open /dev/btrfs-control "
1215 "skipping device registration: %s\n",
1219 strncpy(args.name, fname, BTRFS_PATH_NAME_MAX);
1220 args.name[BTRFS_PATH_NAME_MAX-1] = 0;
1221 ret = ioctl(fd, BTRFS_IOC_SCAN_DEV, &args);
1224 fprintf(stderr, "ERROR: device scan failed '%s' - %s\n",
1225 fname, strerror(e));
1230 int btrfs_scan_one_dir(char *dirname, int run_ioctl)
1233 struct dirent *dirent;
1234 struct pending_dir *pending;
1240 struct list_head pending_list;
1241 struct btrfs_fs_devices *tmp_devices;
1244 INIT_LIST_HEAD(&pending_list);
1246 pending = malloc(sizeof(*pending));
1249 strcpy(pending->name, dirname);
1252 dirname_len = strlen(pending->name);
1253 fullpath = malloc(PATH_MAX);
1254 dirname = pending->name;
1260 dirp = opendir(dirname);
1262 fprintf(stderr, "Unable to open %s for scanning\n", dirname);
1267 dirent = readdir(dirp);
1270 if (dirent->d_name[0] == '.')
1272 if (dirname_len + strlen(dirent->d_name) + 2 > PATH_MAX) {
1276 snprintf(fullpath, PATH_MAX, "%s/%s", dirname, dirent->d_name);
1277 ret = lstat(fullpath, &st);
1279 fprintf(stderr, "failed to stat %s\n", fullpath);
1282 if (S_ISLNK(st.st_mode))
1284 if (S_ISDIR(st.st_mode)) {
1285 struct pending_dir *next = malloc(sizeof(*next));
1290 strcpy(next->name, fullpath);
1291 list_add_tail(&next->list, &pending_list);
1293 if (!S_ISBLK(st.st_mode)) {
1296 fd = open(fullpath, O_RDONLY);
1298 /* ignore the following errors:
1299 ENXIO (device don't exists)
1300 ENOMEDIUM (No medium found ->
1301 like a cd tray empty)
1303 if(errno != ENXIO && errno != ENOMEDIUM)
1304 fprintf(stderr, "failed to read %s: %s\n",
1305 fullpath, strerror(errno));
1308 ret = btrfs_scan_one_device(fd, fullpath, &tmp_devices,
1310 BTRFS_SUPER_INFO_OFFSET, 0);
1311 if (ret == 0 && run_ioctl > 0) {
1312 btrfs_register_one_device(fullpath);
1316 if (!list_empty(&pending_list)) {
1318 pending = list_entry(pending_list.next, struct pending_dir,
1321 list_del(&pending->list);
1330 while (!list_empty(&pending_list)) {
1331 pending = list_entry(pending_list.next, struct pending_dir,
1333 list_del(&pending->list);
1341 int btrfs_scan_for_fsid(int run_ioctls)
1345 ret = scan_for_btrfs(BTRFS_SCAN_PROC, run_ioctls);
1347 ret = scan_for_btrfs(BTRFS_SCAN_DEV, run_ioctls);
1351 int btrfs_device_already_in_root(struct btrfs_root *root, int fd,
1354 struct btrfs_super_block *disk_super;
1358 buf = malloc(BTRFS_SUPER_INFO_SIZE);
1363 ret = pread(fd, buf, BTRFS_SUPER_INFO_SIZE, super_offset);
1364 if (ret != BTRFS_SUPER_INFO_SIZE)
1368 disk_super = (struct btrfs_super_block *)buf;
1369 if (btrfs_super_magic(disk_super) != BTRFS_MAGIC)
1372 if (!memcmp(disk_super->fsid, root->fs_info->super_copy->fsid,
1381 static char *size_strs[] = { "", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"};
1382 int pretty_size_snprintf(u64 size, char *str, size_t str_bytes)
1394 u64 last_size = size;
1396 while(size >= 1024){
1402 if (num_divs >= ARRAY_SIZE(size_strs)) {
1406 fraction = (float)last_size / 1024;
1408 return snprintf(str, str_bytes, "%.2f%s", fraction,
1409 size_strs[num_divs]);
1413 * __strncpy__null - strncpy with null termination
1414 * @dest: the target array
1415 * @src: the source string
1416 * @n: maximum bytes to copy (size of *dest)
1418 * Like strncpy, but ensures destination is null-terminated.
1420 * Copies the string pointed to by src, including the terminating null
1421 * byte ('\0'), to the buffer pointed to by dest, up to a maximum
1422 * of n bytes. Then ensure that dest is null-terminated.
1424 char *__strncpy__null(char *dest, const char *src, size_t n)
1426 strncpy(dest, src, n);
1433 * Checks to make sure that the label matches our requirements.
1435 0 if everything is safe and usable
1436 -1 if the label is too long
1438 static int check_label(const char *input)
1440 int len = strlen(input);
1442 if (len > BTRFS_LABEL_SIZE - 1) {
1443 fprintf(stderr, "ERROR: Label %s is too long (max %d)\n",
1444 input, BTRFS_LABEL_SIZE - 1);
1451 static int set_label_unmounted(const char *dev, const char *label)
1453 struct btrfs_trans_handle *trans;
1454 struct btrfs_root *root;
1457 ret = check_mounted(dev);
1459 fprintf(stderr, "FATAL: error checking %s mount status\n", dev);
1463 fprintf(stderr, "ERROR: dev %s is mounted, use mount point\n",
1468 /* Open the super_block at the default location
1469 * and as read-write.
1471 root = open_ctree(dev, 0, OPEN_CTREE_WRITES);
1472 if (!root) /* errors are printed by open_ctree() */
1475 trans = btrfs_start_transaction(root, 1);
1476 snprintf(root->fs_info->super_copy->label, BTRFS_LABEL_SIZE, "%s",
1478 btrfs_commit_transaction(trans, root);
1480 /* Now we close it since we are done. */
1485 static int set_label_mounted(const char *mount_path, const char *label)
1489 fd = open(mount_path, O_RDONLY | O_NOATIME);
1491 fprintf(stderr, "ERROR: unable to access '%s'\n", mount_path);
1495 if (ioctl(fd, BTRFS_IOC_SET_FSLABEL, label) < 0) {
1496 fprintf(stderr, "ERROR: unable to set label %s\n",
1506 static int get_label_unmounted(const char *dev, char *label)
1508 struct btrfs_root *root;
1511 ret = check_mounted(dev);
1513 fprintf(stderr, "FATAL: error checking %s mount status\n", dev);
1517 fprintf(stderr, "ERROR: dev %s is mounted, use mount point\n",
1522 /* Open the super_block at the default location
1525 root = open_ctree(dev, 0, 0);
1529 memcpy(label, root->fs_info->super_copy->label, BTRFS_LABEL_SIZE);
1531 /* Now we close it since we are done. */
1537 * If a partition is mounted, try to get the filesystem label via its
1538 * mounted path rather than device. Return the corresponding error
1539 * the user specified the device path.
1541 int get_label_mounted(const char *mount_path, char *labelp)
1543 char label[BTRFS_LABEL_SIZE];
1546 fd = open(mount_path, O_RDONLY | O_NOATIME);
1548 fprintf(stderr, "ERROR: unable to access '%s'\n", mount_path);
1552 memset(label, '\0', sizeof(label));
1553 if (ioctl(fd, BTRFS_IOC_GET_FSLABEL, label) < 0) {
1554 fprintf(stderr, "ERROR: unable get label %s\n", strerror(errno));
1559 strncpy(labelp, label, sizeof(label));
1564 int get_label(const char *btrfs_dev, char *label)
1568 if (is_existing_blk_or_reg_file(btrfs_dev))
1569 ret = get_label_unmounted(btrfs_dev, label);
1571 ret = get_label_mounted(btrfs_dev, label);
1576 int set_label(const char *btrfs_dev, const char *label)
1578 if (check_label(label))
1581 return is_existing_blk_or_reg_file(btrfs_dev) ?
1582 set_label_unmounted(btrfs_dev, label) :
1583 set_label_mounted(btrfs_dev, label);
1586 int btrfs_scan_block_devices(int run_ioctl)
1592 struct btrfs_fs_devices *tmp_devices;
1594 FILE *proc_partitions;
1602 proc_partitions = fopen("/proc/partitions","r");
1603 if (!proc_partitions) {
1604 fprintf(stderr, "Unable to open '/proc/partitions' for scanning\n");
1607 /* skip the header */
1608 for (i = 0; i < 2; i++)
1609 if (!fgets(buf, 1023, proc_partitions)) {
1611 "Unable to read '/proc/partitions' for scanning\n");
1612 fclose(proc_partitions);
1616 strcpy(fullpath,"/dev/");
1617 while(fgets(buf, 1023, proc_partitions)) {
1618 i = sscanf(buf," %*d %*d %*d %99s", fullpath+5);
1621 * multipath and MD devices may register as a btrfs filesystem
1622 * both through the original block device and through
1623 * the special (/dev/mapper or /dev/mdX) entry.
1624 * This scans the special entries last
1626 special = strncmp(fullpath, "/dev/dm-", strlen("/dev/dm-")) == 0;
1628 special = strncmp(fullpath, "/dev/md", strlen("/dev/md")) == 0;
1630 if (scans == 0 && special)
1632 if (scans > 0 && !special)
1635 ret = lstat(fullpath, &st);
1637 fprintf(stderr, "failed to stat %s\n", fullpath);
1640 if (!S_ISBLK(st.st_mode)) {
1644 fd = open(fullpath, O_RDONLY);
1646 if (errno != ENOMEDIUM)
1647 fprintf(stderr, "failed to open %s: %s\n",
1648 fullpath, strerror(errno));
1651 ret = btrfs_scan_one_device(fd, fullpath, &tmp_devices,
1653 BTRFS_SUPER_INFO_OFFSET, 0);
1654 if (ret == 0 && run_ioctl > 0) {
1655 btrfs_register_one_device(fullpath);
1660 fclose(proc_partitions);
1670 * A not-so-good version fls64. No fascinating optimization since
1671 * no one except parse_size use it
1673 static int fls64(u64 x)
1677 for (i = 0; i <64; i++)
1678 if (x << i & (1UL << 63))
1683 u64 parse_size(char *s)
1691 fprintf(stderr, "ERROR: Size value is empty\n");
1696 "ERROR: Size value '%s' is less equal than 0\n", s);
1699 ret = strtoull(s, &endptr, 10);
1701 fprintf(stderr, "ERROR: Size value '%s' is invalid\n", s);
1704 if (endptr[0] && endptr[1]) {
1705 fprintf(stderr, "ERROR: Illegal suffix contains character '%c' in wrong position\n",
1710 * strtoll returns LLONG_MAX when overflow, if this happens,
1711 * need to call strtoull to get the real size
1713 if (errno == ERANGE && ret == ULLONG_MAX) {
1715 "ERROR: Size value '%s' is too large for u64\n", s);
1719 c = tolower(endptr[0]);
1742 fprintf(stderr, "ERROR: Unknown size descriptor '%c'\n",
1747 /* Check whether ret * mult overflow */
1748 if (fls64(ret) + fls64(mult) - 1 > 64) {
1750 "ERROR: Size value '%s' is too large for u64\n", s);
1757 int open_file_or_dir3(const char *fname, DIR **dirstream, int open_flags)
1763 ret = stat(fname, &st);
1767 if (S_ISDIR(st.st_mode)) {
1768 *dirstream = opendir(fname);
1771 fd = dirfd(*dirstream);
1772 } else if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
1773 fd = open(fname, open_flags);
1776 * we set this on purpose, in case the caller output
1777 * strerror(errno) as success
1785 closedir(*dirstream);
1790 int open_file_or_dir(const char *fname, DIR **dirstream)
1792 return open_file_or_dir3(fname, dirstream, O_RDWR);
1795 void close_file_or_dir(int fd, DIR *dirstream)
1798 closedir(dirstream);
1803 int get_device_info(int fd, u64 devid,
1804 struct btrfs_ioctl_dev_info_args *di_args)
1808 di_args->devid = devid;
1809 memset(&di_args->uuid, '\0', sizeof(di_args->uuid));
1811 ret = ioctl(fd, BTRFS_IOC_DEV_INFO, di_args);
1812 return ret ? -errno : 0;
1816 * For a given path, fill in the ioctl fs_ and info_ args.
1817 * If the path is a btrfs mountpoint, fill info for all devices.
1818 * If the path is a btrfs device, fill in only that device.
1820 * The path provided must be either on a mounted btrfs fs,
1821 * or be a mounted btrfs device.
1823 * Returns 0 on success, or a negative errno.
1825 int get_fs_info(char *path, struct btrfs_ioctl_fs_info_args *fi_args,
1826 struct btrfs_ioctl_dev_info_args **di_ret)
1832 struct btrfs_fs_devices *fs_devices_mnt = NULL;
1833 struct btrfs_ioctl_dev_info_args *di_args;
1834 char mp[BTRFS_PATH_NAME_MAX + 1];
1835 DIR *dirstream = NULL;
1837 memset(fi_args, 0, sizeof(*fi_args));
1839 if (is_block_device(path)) {
1840 struct btrfs_super_block *disk_super;
1841 char buf[BTRFS_SUPER_INFO_SIZE];
1844 /* Ensure it's mounted, then set path to the mountpoint */
1845 fd = open(path, O_RDONLY);
1848 fprintf(stderr, "Couldn't open %s: %s\n",
1849 path, strerror(errno));
1852 ret = check_mounted_where(fd, path, mp, sizeof(mp),
1861 /* Only fill in this one device */
1862 fi_args->num_devices = 1;
1864 disk_super = (struct btrfs_super_block *)buf;
1865 ret = btrfs_read_dev_super(fd, disk_super,
1866 BTRFS_SUPER_INFO_OFFSET, 0);
1871 devid = btrfs_stack_device_id(&disk_super->dev_item);
1873 fi_args->max_id = devid;
1876 memcpy(fi_args->fsid, fs_devices_mnt->fsid, BTRFS_FSID_SIZE);
1880 /* at this point path must not be for a block device */
1881 fd = open_file_or_dir(path, &dirstream);
1887 /* fill in fi_args if not just a single device */
1888 if (fi_args->num_devices != 1) {
1889 ret = ioctl(fd, BTRFS_IOC_FS_INFO, fi_args);
1896 if (!fi_args->num_devices)
1899 di_args = *di_ret = malloc(fi_args->num_devices * sizeof(*di_args));
1905 for (; i <= fi_args->max_id; ++i) {
1906 BUG_ON(ndevs >= fi_args->num_devices);
1907 ret = get_device_info(fd, i, &di_args[ndevs]);
1916 * only when the only dev we wanted to find is not there then
1917 * let any error be returned
1919 if (fi_args->num_devices != 1) {
1925 close_file_or_dir(fd, dirstream);
1929 #define isoctal(c) (((c) & ~7) == '0')
1931 static inline void translate(char *f, char *t)
1933 while (*f != '\0') {
1935 isoctal(f[1]) && isoctal(f[2]) && isoctal(f[3])) {
1936 *t++ = 64*(f[1] & 7) + 8*(f[2] & 7) + (f[3] & 7);
1946 * Checks if the swap device.
1947 * Returns 1 if swap device, < 0 on error or 0 if not swap device.
1949 static int is_swap_device(const char *file)
1960 if (stat(file, &st_buf) < 0)
1962 if (S_ISBLK(st_buf.st_mode))
1963 dev = st_buf.st_rdev;
1964 else if (S_ISREG(st_buf.st_mode)) {
1965 dev = st_buf.st_dev;
1966 ino = st_buf.st_ino;
1970 if ((f = fopen("/proc/swaps", "r")) == NULL)
1973 /* skip the first line */
1974 if (fgets(tmp, sizeof(tmp), f) == NULL)
1977 while (fgets(tmp, sizeof(tmp), f) != NULL) {
1978 if ((cp = strchr(tmp, ' ')) != NULL)
1980 if ((cp = strchr(tmp, '\t')) != NULL)
1982 translate(tmp, buf);
1983 if (stat(buf, &st_buf) != 0)
1985 if (S_ISBLK(st_buf.st_mode)) {
1986 if (dev == st_buf.st_rdev) {
1990 } else if (S_ISREG(st_buf.st_mode)) {
1991 if (dev == st_buf.st_dev && ino == st_buf.st_ino) {
2005 * Check for existing filesystem or partition table on device.
2007 * 1 for existing fs or partition
2008 * 0 for nothing found
2009 * -1 for internal error
2016 blkid_probe pr = NULL;
2020 if (!device || !*device)
2023 ret = -1; /* will reset on success of all setup calls */
2025 pr = blkid_new_probe_from_filename(device);
2029 size = blkid_probe_get_size(pr);
2033 /* nothing to overwrite on a 0-length device */
2039 ret = blkid_probe_enable_partitions(pr, 1);
2043 ret = blkid_do_fullprobe(pr);
2048 * Blkid returns 1 for nothing found and 0 when it finds a signature,
2049 * but we want the exact opposite, so reverse the return value here.
2051 * In addition print some useful diagnostics about what actually is
2059 if (!blkid_probe_lookup_value(pr, "TYPE", &type, NULL)) {
2061 "%s appears to contain an existing "
2062 "filesystem (%s).\n", device, type);
2063 } else if (!blkid_probe_lookup_value(pr, "PTTYPE", &type, NULL)) {
2065 "%s appears to contain a partition "
2066 "table (%s).\n", device, type);
2069 "%s appears to contain something weird "
2070 "according to blkid\n", device);
2076 blkid_free_probe(pr);
2079 "probe of %s failed, cannot detect "
2080 "existing filesystem.\n", device);
2084 int test_num_disk_vs_raid(u64 metadata_profile, u64 data_profile,
2085 u64 dev_cnt, int mixed, char *estr)
2093 allowed |= BTRFS_BLOCK_GROUP_RAID10;
2095 allowed |= BTRFS_BLOCK_GROUP_RAID6;
2097 allowed |= BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
2098 BTRFS_BLOCK_GROUP_RAID5;
2101 allowed |= BTRFS_BLOCK_GROUP_DUP;
2104 if (metadata_profile & ~allowed) {
2105 snprintf(estr, sz, "unable to create FS with metadata "
2106 "profile %llu (have %llu devices)\n",
2107 metadata_profile, dev_cnt);
2110 if (data_profile & ~allowed) {
2111 snprintf(estr, sz, "unable to create FS with data "
2112 "profile %llu (have %llu devices)\n",
2113 metadata_profile, dev_cnt);
2117 if (!mixed && (data_profile & BTRFS_BLOCK_GROUP_DUP)) {
2119 "dup for data is allowed only in mixed mode");
2125 /* Check if disk is suitable for btrfs
2127 * 1: something is wrong, estr provides the error
2130 int test_dev_for_mkfs(char *file, int force_overwrite, char *estr)
2136 ret = is_swap_device(file);
2138 snprintf(estr, sz, "error checking %s status: %s\n", file,
2143 snprintf(estr, sz, "%s is a swap device\n", file);
2146 if (!force_overwrite) {
2147 if (check_overwrite(file)) {
2148 snprintf(estr, sz, "Use the -f option to force overwrite.\n");
2152 ret = check_mounted(file);
2154 snprintf(estr, sz, "error checking %s mount status\n",
2159 snprintf(estr, sz, "%s is mounted\n", file);
2162 /* check if the device is busy */
2163 fd = open(file, O_RDWR|O_EXCL);
2165 snprintf(estr, sz, "unable to open %s: %s\n", file,
2169 if (fstat(fd, &st)) {
2170 snprintf(estr, sz, "unable to stat %s: %s\n", file,
2175 if (!S_ISBLK(st.st_mode)) {
2176 fprintf(stderr, "'%s' is not a block device\n", file);
2184 int btrfs_scan_lblkid(int update_kernel)
2189 struct btrfs_fs_devices *tmp_devices;
2190 blkid_dev_iterate iter = NULL;
2191 blkid_dev dev = NULL;
2192 blkid_cache cache = NULL;
2193 char path[PATH_MAX];
2195 if (blkid_get_cache(&cache, 0) < 0) {
2196 printf("ERROR: lblkid cache get failed\n");
2199 blkid_probe_all(cache);
2200 iter = blkid_dev_iterate_begin(cache);
2201 blkid_dev_set_search(iter, "TYPE", "btrfs");
2202 while (blkid_dev_next(iter, &dev) == 0) {
2203 dev = blkid_verify(cache, dev);
2206 /* if we are here its definitely a btrfs disk*/
2207 strncpy(path, blkid_dev_devname(dev), PATH_MAX);
2209 fd = open(path, O_RDONLY);
2211 printf("ERROR: could not open %s\n", path);
2214 ret = btrfs_scan_one_device(fd, path, &tmp_devices,
2215 &num_devices, BTRFS_SUPER_INFO_OFFSET, 0);
2217 printf("ERROR: could not scan %s\n", path);
2224 btrfs_register_one_device(path);
2226 blkid_dev_iterate_end(iter);
2227 blkid_put_cache(cache);
2232 * scans devs for the btrfs
2234 int scan_for_btrfs(int where, int update_kernel)
2239 case BTRFS_SCAN_PROC:
2240 ret = btrfs_scan_block_devices(update_kernel);
2242 case BTRFS_SCAN_DEV:
2243 ret = btrfs_scan_one_dir("/dev", update_kernel);
2245 case BTRFS_SCAN_LBLKID:
2246 ret = btrfs_scan_lblkid(update_kernel);
2252 int is_vol_small(char *file)
2259 fd = open(file, O_RDONLY);
2262 if (fstat(fd, &st) < 0) {
2267 size = btrfs_device_size(fd, &st);
2272 if (size < BTRFS_MKFS_SMALL_VOLUME_SIZE) {
2282 * This reads a line from the stdin and only returns non-zero if the
2283 * first whitespace delimited token is a case insensitive match with yes
2286 int ask_user(char *question)
2288 char buf[30] = {0,};
2289 char *saveptr = NULL;
2292 printf("%s [y/N]: ", question);
2294 return fgets(buf, sizeof(buf) - 1, stdin) &&
2295 (answer = strtok_r(buf, " \t\n\r", &saveptr)) &&
2296 (!strcasecmp(answer, "yes") || !strcasecmp(answer, "y"));
2301 * - file or directory return the containing tree root id
2302 * - subvolume return it's own tree id
2303 * - BTRFS_EMPTY_SUBVOL_DIR_OBJECTID (directory with ino == 2) the result is
2304 * undefined and function returns -1
2306 int lookup_ino_rootid(int fd, u64 *rootid)
2308 struct btrfs_ioctl_ino_lookup_args args;
2312 memset(&args, 0, sizeof(args));
2314 args.objectid = BTRFS_FIRST_FREE_OBJECTID;
2316 ret = ioctl(fd, BTRFS_IOC_INO_LOOKUP, &args);
2319 fprintf(stderr, "ERROR: Failed to lookup root id - %s\n",
2324 *rootid = args.treeid;
2329 int find_mount_root(const char *path, char **mount_root)
2336 int longest_matchlen = 0;
2337 char *longest_match = NULL;
2339 fd = open(path, O_RDONLY | O_NOATIME);
2344 mnttab = setmntent("/proc/self/mounts", "r");
2348 while ((ent = getmntent(mnttab))) {
2349 len = strlen(ent->mnt_dir);
2350 if (strncmp(ent->mnt_dir, path, len) == 0) {
2352 if (longest_matchlen < len) {
2353 free(longest_match);
2354 longest_matchlen = len;
2355 longest_match = strdup(ent->mnt_dir);
2361 if (!longest_match) {
2363 "ERROR: Failed to find mount root for path %s.\n",
2369 *mount_root = realpath(longest_match, NULL);
2373 free(longest_match);
2377 int test_minimum_size(const char *file, u32 leafsize)
2380 struct stat statbuf;
2382 fd = open(file, O_RDONLY);
2385 if (stat(file, &statbuf) < 0) {
2389 if (btrfs_device_size(fd, &statbuf) < btrfs_min_dev_size(leafsize)) {