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 */
28 #include <sys/ioctl.h>
29 #include <sys/mount.h>
31 #include <sys/types.h>
33 #include <uuid/uuid.h>
39 #include <linux/loop.h>
40 #include <linux/major.h>
41 #include <linux/kdev_t.h>
43 #include "kerncompat.h"
44 #include "radix-tree.h"
47 #include "transaction.h"
54 #define BLKGETSIZE64 0
55 static inline int ioctl(int fd, int define, u64 *size) { return 0; }
59 #define BLKDISCARD _IO(0x12,119)
63 discard_blocks(int fd, u64 start, u64 len)
65 u64 range[2] = { start, len };
67 if (ioctl(fd, BLKDISCARD, &range) < 0)
72 static u64 reference_root_table[] = {
73 [1] = BTRFS_ROOT_TREE_OBJECTID,
74 [2] = BTRFS_EXTENT_TREE_OBJECTID,
75 [3] = BTRFS_CHUNK_TREE_OBJECTID,
76 [4] = BTRFS_DEV_TREE_OBJECTID,
77 [5] = BTRFS_FS_TREE_OBJECTID,
78 [6] = BTRFS_CSUM_TREE_OBJECTID,
81 int make_btrfs(int fd, const char *device, const char *label,
82 u64 blocks[7], u64 num_bytes, u32 nodesize,
83 u32 leafsize, u32 sectorsize, u32 stripesize)
85 struct btrfs_super_block super;
86 struct extent_buffer *buf;
87 struct btrfs_root_item root_item;
88 struct btrfs_disk_key disk_key;
89 struct btrfs_extent_item *extent_item;
90 struct btrfs_inode_item *inode_item;
91 struct btrfs_chunk *chunk;
92 struct btrfs_dev_item *dev_item;
93 struct btrfs_dev_extent *dev_extent;
94 u8 chunk_tree_uuid[BTRFS_UUID_SIZE];
105 first_free = BTRFS_SUPER_INFO_OFFSET + sectorsize * 2 - 1;
106 first_free &= ~((u64)sectorsize - 1);
108 memset(&super, 0, sizeof(super));
110 num_bytes = (num_bytes / sectorsize) * sectorsize;
111 uuid_generate(super.fsid);
112 uuid_generate(super.dev_item.uuid);
113 uuid_generate(chunk_tree_uuid);
115 btrfs_set_super_bytenr(&super, blocks[0]);
116 btrfs_set_super_num_devices(&super, 1);
117 super.magic = cpu_to_le64(BTRFS_MAGIC);
118 btrfs_set_super_generation(&super, 1);
119 btrfs_set_super_root(&super, blocks[1]);
120 btrfs_set_super_chunk_root(&super, blocks[3]);
121 btrfs_set_super_total_bytes(&super, num_bytes);
122 btrfs_set_super_bytes_used(&super, 6 * leafsize);
123 btrfs_set_super_sectorsize(&super, sectorsize);
124 btrfs_set_super_leafsize(&super, leafsize);
125 btrfs_set_super_nodesize(&super, nodesize);
126 btrfs_set_super_stripesize(&super, stripesize);
127 btrfs_set_super_csum_type(&super, BTRFS_CSUM_TYPE_CRC32);
128 btrfs_set_super_chunk_root_generation(&super, 1);
129 btrfs_set_super_cache_generation(&super, -1);
131 strncpy(super.label, label, BTRFS_LABEL_SIZE - 1);
133 buf = malloc(sizeof(*buf) + max(sectorsize, leafsize));
135 /* create the tree of root objects */
136 memset(buf->data, 0, leafsize);
138 btrfs_set_header_bytenr(buf, blocks[1]);
139 btrfs_set_header_nritems(buf, 4);
140 btrfs_set_header_generation(buf, 1);
141 btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
142 btrfs_set_header_owner(buf, BTRFS_ROOT_TREE_OBJECTID);
143 write_extent_buffer(buf, super.fsid, (unsigned long)
144 btrfs_header_fsid(buf), BTRFS_FSID_SIZE);
146 write_extent_buffer(buf, chunk_tree_uuid, (unsigned long)
147 btrfs_header_chunk_tree_uuid(buf),
150 /* create the items for the root tree */
151 memset(&root_item, 0, sizeof(root_item));
152 inode_item = &root_item.inode;
153 btrfs_set_stack_inode_generation(inode_item, 1);
154 btrfs_set_stack_inode_size(inode_item, 3);
155 btrfs_set_stack_inode_nlink(inode_item, 1);
156 btrfs_set_stack_inode_nbytes(inode_item, leafsize);
157 btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
158 btrfs_set_root_refs(&root_item, 1);
159 btrfs_set_root_used(&root_item, leafsize);
160 btrfs_set_root_generation(&root_item, 1);
162 memset(&disk_key, 0, sizeof(disk_key));
163 btrfs_set_disk_key_type(&disk_key, BTRFS_ROOT_ITEM_KEY);
164 btrfs_set_disk_key_offset(&disk_key, 0);
167 itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize) - sizeof(root_item);
168 btrfs_set_root_bytenr(&root_item, blocks[2]);
169 btrfs_set_disk_key_objectid(&disk_key, BTRFS_EXTENT_TREE_OBJECTID);
170 btrfs_set_item_key(buf, &disk_key, nritems);
171 btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems), itemoff);
172 btrfs_set_item_size(buf, btrfs_item_nr(buf, nritems),
174 write_extent_buffer(buf, &root_item, btrfs_item_ptr_offset(buf,
175 nritems), sizeof(root_item));
178 itemoff = itemoff - sizeof(root_item);
179 btrfs_set_root_bytenr(&root_item, blocks[4]);
180 btrfs_set_disk_key_objectid(&disk_key, BTRFS_DEV_TREE_OBJECTID);
181 btrfs_set_item_key(buf, &disk_key, nritems);
182 btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems), itemoff);
183 btrfs_set_item_size(buf, btrfs_item_nr(buf, nritems),
185 write_extent_buffer(buf, &root_item,
186 btrfs_item_ptr_offset(buf, nritems),
190 itemoff = itemoff - sizeof(root_item);
191 btrfs_set_root_bytenr(&root_item, blocks[5]);
192 btrfs_set_disk_key_objectid(&disk_key, BTRFS_FS_TREE_OBJECTID);
193 btrfs_set_item_key(buf, &disk_key, nritems);
194 btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems), itemoff);
195 btrfs_set_item_size(buf, btrfs_item_nr(buf, nritems),
197 write_extent_buffer(buf, &root_item,
198 btrfs_item_ptr_offset(buf, nritems),
202 itemoff = itemoff - sizeof(root_item);
203 btrfs_set_root_bytenr(&root_item, blocks[6]);
204 btrfs_set_disk_key_objectid(&disk_key, BTRFS_CSUM_TREE_OBJECTID);
205 btrfs_set_item_key(buf, &disk_key, nritems);
206 btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems), itemoff);
207 btrfs_set_item_size(buf, btrfs_item_nr(buf, nritems),
209 write_extent_buffer(buf, &root_item,
210 btrfs_item_ptr_offset(buf, nritems),
215 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
216 ret = pwrite(fd, buf->data, leafsize, blocks[1]);
217 BUG_ON(ret != leafsize);
219 /* create the items for the extent tree */
220 memset(buf->data+sizeof(struct btrfs_header), 0,
221 leafsize-sizeof(struct btrfs_header));
223 itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize);
224 for (i = 1; i < 7; i++) {
225 BUG_ON(blocks[i] < first_free);
226 BUG_ON(blocks[i] < blocks[i - 1]);
228 /* create extent item */
229 itemoff -= sizeof(struct btrfs_extent_item) +
230 sizeof(struct btrfs_tree_block_info);
231 btrfs_set_disk_key_objectid(&disk_key, blocks[i]);
232 btrfs_set_disk_key_offset(&disk_key, leafsize);
233 btrfs_set_disk_key_type(&disk_key, BTRFS_EXTENT_ITEM_KEY);
234 btrfs_set_item_key(buf, &disk_key, nritems);
235 btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems),
237 btrfs_set_item_size(buf, btrfs_item_nr(buf, nritems),
238 sizeof(struct btrfs_extent_item) +
239 sizeof(struct btrfs_tree_block_info));
240 extent_item = btrfs_item_ptr(buf, nritems,
241 struct btrfs_extent_item);
242 btrfs_set_extent_refs(buf, extent_item, 1);
243 btrfs_set_extent_generation(buf, extent_item, 1);
244 btrfs_set_extent_flags(buf, extent_item,
245 BTRFS_EXTENT_FLAG_TREE_BLOCK);
248 /* create extent ref */
249 ref_root = reference_root_table[i];
250 btrfs_set_disk_key_objectid(&disk_key, blocks[i]);
251 btrfs_set_disk_key_offset(&disk_key, ref_root);
252 btrfs_set_disk_key_type(&disk_key, BTRFS_TREE_BLOCK_REF_KEY);
253 btrfs_set_item_key(buf, &disk_key, nritems);
254 btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems),
256 btrfs_set_item_size(buf, btrfs_item_nr(buf, nritems), 0);
259 btrfs_set_header_bytenr(buf, blocks[2]);
260 btrfs_set_header_owner(buf, BTRFS_EXTENT_TREE_OBJECTID);
261 btrfs_set_header_nritems(buf, nritems);
262 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
263 ret = pwrite(fd, buf->data, leafsize, blocks[2]);
264 BUG_ON(ret != leafsize);
266 /* create the chunk tree */
267 memset(buf->data+sizeof(struct btrfs_header), 0,
268 leafsize-sizeof(struct btrfs_header));
270 item_size = sizeof(*dev_item);
271 itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize) - item_size;
273 /* first device 1 (there is no device 0) */
274 btrfs_set_disk_key_objectid(&disk_key, BTRFS_DEV_ITEMS_OBJECTID);
275 btrfs_set_disk_key_offset(&disk_key, 1);
276 btrfs_set_disk_key_type(&disk_key, BTRFS_DEV_ITEM_KEY);
277 btrfs_set_item_key(buf, &disk_key, nritems);
278 btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems), itemoff);
279 btrfs_set_item_size(buf, btrfs_item_nr(buf, nritems), item_size);
281 dev_item = btrfs_item_ptr(buf, nritems, struct btrfs_dev_item);
282 btrfs_set_device_id(buf, dev_item, 1);
283 btrfs_set_device_generation(buf, dev_item, 0);
284 btrfs_set_device_total_bytes(buf, dev_item, num_bytes);
285 btrfs_set_device_bytes_used(buf, dev_item,
286 BTRFS_MKFS_SYSTEM_GROUP_SIZE);
287 btrfs_set_device_io_align(buf, dev_item, sectorsize);
288 btrfs_set_device_io_width(buf, dev_item, sectorsize);
289 btrfs_set_device_sector_size(buf, dev_item, sectorsize);
290 btrfs_set_device_type(buf, dev_item, 0);
292 write_extent_buffer(buf, super.dev_item.uuid,
293 (unsigned long)btrfs_device_uuid(dev_item),
295 write_extent_buffer(buf, super.fsid,
296 (unsigned long)btrfs_device_fsid(dev_item),
298 read_extent_buffer(buf, &super.dev_item, (unsigned long)dev_item,
302 item_size = btrfs_chunk_item_size(1);
303 itemoff = itemoff - item_size;
305 /* then we have chunk 0 */
306 btrfs_set_disk_key_objectid(&disk_key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
307 btrfs_set_disk_key_offset(&disk_key, 0);
308 btrfs_set_disk_key_type(&disk_key, BTRFS_CHUNK_ITEM_KEY);
309 btrfs_set_item_key(buf, &disk_key, nritems);
310 btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems), itemoff);
311 btrfs_set_item_size(buf, btrfs_item_nr(buf, nritems), item_size);
313 chunk = btrfs_item_ptr(buf, nritems, struct btrfs_chunk);
314 btrfs_set_chunk_length(buf, chunk, BTRFS_MKFS_SYSTEM_GROUP_SIZE);
315 btrfs_set_chunk_owner(buf, chunk, BTRFS_EXTENT_TREE_OBJECTID);
316 btrfs_set_chunk_stripe_len(buf, chunk, 64 * 1024);
317 btrfs_set_chunk_type(buf, chunk, BTRFS_BLOCK_GROUP_SYSTEM);
318 btrfs_set_chunk_io_align(buf, chunk, sectorsize);
319 btrfs_set_chunk_io_width(buf, chunk, sectorsize);
320 btrfs_set_chunk_sector_size(buf, chunk, sectorsize);
321 btrfs_set_chunk_num_stripes(buf, chunk, 1);
322 btrfs_set_stripe_devid_nr(buf, chunk, 0, 1);
323 btrfs_set_stripe_offset_nr(buf, chunk, 0, 0);
326 write_extent_buffer(buf, super.dev_item.uuid,
327 (unsigned long)btrfs_stripe_dev_uuid(&chunk->stripe),
330 /* copy the key for the chunk to the system array */
331 ptr = super.sys_chunk_array;
332 array_size = sizeof(disk_key);
334 memcpy(ptr, &disk_key, sizeof(disk_key));
335 ptr += sizeof(disk_key);
337 /* copy the chunk to the system array */
338 read_extent_buffer(buf, ptr, (unsigned long)chunk, item_size);
339 array_size += item_size;
341 btrfs_set_super_sys_array_size(&super, array_size);
343 btrfs_set_header_bytenr(buf, blocks[3]);
344 btrfs_set_header_owner(buf, BTRFS_CHUNK_TREE_OBJECTID);
345 btrfs_set_header_nritems(buf, nritems);
346 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
347 ret = pwrite(fd, buf->data, leafsize, blocks[3]);
349 /* create the device tree */
350 memset(buf->data+sizeof(struct btrfs_header), 0,
351 leafsize-sizeof(struct btrfs_header));
353 itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize) -
354 sizeof(struct btrfs_dev_extent);
356 btrfs_set_disk_key_objectid(&disk_key, 1);
357 btrfs_set_disk_key_offset(&disk_key, 0);
358 btrfs_set_disk_key_type(&disk_key, BTRFS_DEV_EXTENT_KEY);
359 btrfs_set_item_key(buf, &disk_key, nritems);
360 btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems), itemoff);
361 btrfs_set_item_size(buf, btrfs_item_nr(buf, nritems),
362 sizeof(struct btrfs_dev_extent));
363 dev_extent = btrfs_item_ptr(buf, nritems, struct btrfs_dev_extent);
364 btrfs_set_dev_extent_chunk_tree(buf, dev_extent,
365 BTRFS_CHUNK_TREE_OBJECTID);
366 btrfs_set_dev_extent_chunk_objectid(buf, dev_extent,
367 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
368 btrfs_set_dev_extent_chunk_offset(buf, dev_extent, 0);
370 write_extent_buffer(buf, chunk_tree_uuid,
371 (unsigned long)btrfs_dev_extent_chunk_tree_uuid(dev_extent),
374 btrfs_set_dev_extent_length(buf, dev_extent,
375 BTRFS_MKFS_SYSTEM_GROUP_SIZE);
378 btrfs_set_header_bytenr(buf, blocks[4]);
379 btrfs_set_header_owner(buf, BTRFS_DEV_TREE_OBJECTID);
380 btrfs_set_header_nritems(buf, nritems);
381 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
382 ret = pwrite(fd, buf->data, leafsize, blocks[4]);
384 /* create the FS root */
385 memset(buf->data+sizeof(struct btrfs_header), 0,
386 leafsize-sizeof(struct btrfs_header));
387 btrfs_set_header_bytenr(buf, blocks[5]);
388 btrfs_set_header_owner(buf, BTRFS_FS_TREE_OBJECTID);
389 btrfs_set_header_nritems(buf, 0);
390 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
391 ret = pwrite(fd, buf->data, leafsize, blocks[5]);
392 BUG_ON(ret != leafsize);
394 /* finally create the csum root */
395 memset(buf->data+sizeof(struct btrfs_header), 0,
396 leafsize-sizeof(struct btrfs_header));
397 btrfs_set_header_bytenr(buf, blocks[6]);
398 btrfs_set_header_owner(buf, BTRFS_CSUM_TREE_OBJECTID);
399 btrfs_set_header_nritems(buf, 0);
400 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
401 ret = pwrite(fd, buf->data, leafsize, blocks[6]);
402 BUG_ON(ret != leafsize);
404 /* and write out the super block */
405 BUG_ON(sizeof(super) > sectorsize);
406 memset(buf->data, 0, sectorsize);
407 memcpy(buf->data, &super, sizeof(super));
408 buf->len = sectorsize;
409 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
410 ret = pwrite(fd, buf->data, sectorsize, blocks[0]);
411 BUG_ON(ret != sectorsize);
418 static u64 device_size(int fd, struct stat *st)
421 if (S_ISREG(st->st_mode)) {
424 if (!S_ISBLK(st->st_mode)) {
427 if (ioctl(fd, BLKGETSIZE64, &size) >= 0) {
433 static int zero_blocks(int fd, off_t start, size_t len)
435 char *buf = malloc(len);
442 written = pwrite(fd, buf, len, start);
449 static int zero_dev_start(int fd)
452 size_t len = 2 * 1024 * 1024;
455 /* don't overwrite the disk labels on sparc */
459 return zero_blocks(fd, start, len);
462 static int zero_dev_end(int fd, u64 dev_size)
464 size_t len = 2 * 1024 * 1024;
465 off_t start = dev_size - len;
467 return zero_blocks(fd, start, len);
470 int btrfs_add_to_fsid(struct btrfs_trans_handle *trans,
471 struct btrfs_root *root, int fd, char *path,
472 u64 block_count, u32 io_width, u32 io_align,
475 struct btrfs_super_block *disk_super;
476 struct btrfs_super_block *super = &root->fs_info->super_copy;
477 struct btrfs_device *device;
478 struct btrfs_dev_item *dev_item;
484 device = kmalloc(sizeof(*device), GFP_NOFS);
487 buf = kmalloc(sectorsize, GFP_NOFS);
492 BUG_ON(sizeof(*disk_super) > sectorsize);
493 memset(buf, 0, sectorsize);
495 disk_super = (struct btrfs_super_block *)buf;
496 dev_item = &disk_super->dev_item;
498 uuid_generate(device->uuid);
501 device->io_width = io_width;
502 device->io_align = io_align;
503 device->sector_size = sectorsize;
505 device->writeable = 1;
506 device->total_bytes = block_count;
507 device->bytes_used = 0;
508 device->total_ios = 0;
509 device->dev_root = root->fs_info->dev_root;
511 ret = btrfs_add_device(trans, root, device);
514 total_bytes = btrfs_super_total_bytes(super) + block_count;
515 btrfs_set_super_total_bytes(super, total_bytes);
517 num_devs = btrfs_super_num_devices(super) + 1;
518 btrfs_set_super_num_devices(super, num_devs);
520 memcpy(disk_super, super, sizeof(*disk_super));
522 printf("adding device %s id %llu\n", path,
523 (unsigned long long)device->devid);
525 btrfs_set_super_bytenr(disk_super, BTRFS_SUPER_INFO_OFFSET);
526 btrfs_set_stack_device_id(dev_item, device->devid);
527 btrfs_set_stack_device_type(dev_item, device->type);
528 btrfs_set_stack_device_io_align(dev_item, device->io_align);
529 btrfs_set_stack_device_io_width(dev_item, device->io_width);
530 btrfs_set_stack_device_sector_size(dev_item, device->sector_size);
531 btrfs_set_stack_device_total_bytes(dev_item, device->total_bytes);
532 btrfs_set_stack_device_bytes_used(dev_item, device->bytes_used);
533 memcpy(&dev_item->uuid, device->uuid, BTRFS_UUID_SIZE);
535 ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
536 BUG_ON(ret != sectorsize);
539 list_add(&device->dev_list, &root->fs_info->fs_devices->devices);
540 device->fs_devices = root->fs_info->fs_devices;
544 int btrfs_prepare_device(int fd, char *file, int zero_end, u64 *block_count_ret,
545 u64 max_block_count, int *mixed, int nodiscard)
552 ret = fstat(fd, &st);
554 fprintf(stderr, "unable to stat %s\n", file);
558 block_count = device_size(fd, &st);
559 if (block_count == 0) {
560 fprintf(stderr, "unable to find %s size\n", file);
564 block_count = min(block_count, max_block_count);
567 if (block_count < 1024 * 1024 * 1024 && !(*mixed)) {
568 printf("SMALL VOLUME: forcing mixed metadata/data groups\n");
574 * We intentionally ignore errors from the discard ioctl. It is
575 * not necessary for the mkfs functionality but just an optimization.
577 discard_blocks(fd, 0, block_count);
580 ret = zero_dev_start(fd);
582 fprintf(stderr, "failed to zero device start %d\n", ret);
586 for (i = 0 ; i < BTRFS_SUPER_MIRROR_MAX; i++) {
587 bytenr = btrfs_sb_offset(i);
588 if (bytenr >= block_count)
590 zero_blocks(fd, bytenr, BTRFS_SUPER_INFO_SIZE);
594 ret = zero_dev_end(fd, block_count);
596 fprintf(stderr, "failed to zero device end %d\n", ret);
600 *block_count_ret = block_count;
604 int btrfs_make_root_dir(struct btrfs_trans_handle *trans,
605 struct btrfs_root *root, u64 objectid)
608 struct btrfs_inode_item inode_item;
609 time_t now = time(NULL);
611 memset(&inode_item, 0, sizeof(inode_item));
612 btrfs_set_stack_inode_generation(&inode_item, trans->transid);
613 btrfs_set_stack_inode_size(&inode_item, 0);
614 btrfs_set_stack_inode_nlink(&inode_item, 1);
615 btrfs_set_stack_inode_nbytes(&inode_item, root->leafsize);
616 btrfs_set_stack_inode_mode(&inode_item, S_IFDIR | 0755);
617 btrfs_set_stack_timespec_sec(&inode_item.atime, now);
618 btrfs_set_stack_timespec_nsec(&inode_item.atime, 0);
619 btrfs_set_stack_timespec_sec(&inode_item.ctime, now);
620 btrfs_set_stack_timespec_nsec(&inode_item.ctime, 0);
621 btrfs_set_stack_timespec_sec(&inode_item.mtime, now);
622 btrfs_set_stack_timespec_nsec(&inode_item.mtime, 0);
623 btrfs_set_stack_timespec_sec(&inode_item.otime, 0);
624 btrfs_set_stack_timespec_nsec(&inode_item.otime, 0);
626 if (root->fs_info->tree_root == root)
627 btrfs_set_super_root_dir(&root->fs_info->super_copy, objectid);
629 ret = btrfs_insert_inode(trans, root, objectid, &inode_item);
633 ret = btrfs_insert_inode_ref(trans, root, "..", 2, objectid, objectid, 0);
637 btrfs_set_root_dirid(&root->root_item, objectid);
643 /* checks if a device is a loop device */
644 int is_loop_device (const char* device) {
647 if(stat(device, &statbuf) < 0)
650 return (S_ISBLK(statbuf.st_mode) &&
651 MAJOR(statbuf.st_rdev) == LOOP_MAJOR);
655 /* Takes a loop device path (e.g. /dev/loop0) and returns
656 * the associated file (e.g. /images/my_btrfs.img) */
657 int resolve_loop_device(const char* loop_dev, char* loop_file, int max_len)
663 char real_loop_dev[PATH_MAX];
665 if (!realpath(loop_dev, real_loop_dev))
667 snprintf(p, PATH_MAX, "/sys/block/%s/loop/backing_file", strrchr(real_loop_dev, '/'));
668 if (!(f = fopen(p, "r")))
671 snprintf(fmt, 20, "%%%i[^\n]", max_len-1);
672 ret = fscanf(f, fmt, loop_file);
680 /* Checks whether a and b are identical or device
681 * files associated with the same block device
683 int is_same_blk_file(const char* a, const char* b)
685 struct stat st_buf_a, st_buf_b;
686 char real_a[PATH_MAX];
687 char real_b[PATH_MAX];
689 if(!realpath(a, real_a) ||
690 !realpath(b, real_b))
695 /* Identical path? */
696 if(strcmp(real_a, real_b) == 0)
699 if(stat(a, &st_buf_a) < 0 ||
700 stat(b, &st_buf_b) < 0)
707 /* Same blockdevice? */
708 if(S_ISBLK(st_buf_a.st_mode) &&
709 S_ISBLK(st_buf_b.st_mode) &&
710 st_buf_a.st_rdev == st_buf_b.st_rdev)
716 if (st_buf_a.st_dev == st_buf_b.st_dev &&
717 st_buf_a.st_ino == st_buf_b.st_ino)
725 /* checks if a and b are identical or device
726 * files associated with the same block device or
727 * if one file is a loop device that uses the other
730 int is_same_loop_file(const char* a, const char* b)
732 char res_a[PATH_MAX];
733 char res_b[PATH_MAX];
738 /* Resolve a if it is a loop device */
739 if((ret = is_loop_device(a)) < 0) {
744 if ((ret = resolve_loop_device(a, res_a, sizeof(res_a))) < 0)
752 /* Resolve b if it is a loop device */
753 if ((ret = is_loop_device(b)) < 0) {
758 if((ret = resolve_loop_device(b, res_b, sizeof(res_b))) < 0)
766 return is_same_blk_file(final_a, final_b);
769 /* Checks if a file exists and is a block or regular file*/
770 int is_existing_blk_or_reg_file(const char* filename)
774 if(stat(filename, &st_buf) < 0) {
781 return (S_ISBLK(st_buf.st_mode) || S_ISREG(st_buf.st_mode));
784 /* Checks if a file is used (directly or indirectly via a loop device)
785 * by a device in fs_devices
787 int blk_file_in_dev_list(struct btrfs_fs_devices* fs_devices, const char* file)
790 struct list_head *head;
791 struct list_head *cur;
792 struct btrfs_device *device;
794 head = &fs_devices->devices;
795 list_for_each(cur, head) {
796 device = list_entry(cur, struct btrfs_device, dev_list);
798 if((ret = is_same_loop_file(device->name, file)))
806 * returns 1 if the device was mounted, < 0 on error or 0 if everything
807 * is safe to continue.
809 int check_mounted(const char* file)
814 fd = open(file, O_RDONLY);
816 fprintf (stderr, "check_mounted(): Could not open %s\n", file);
820 ret = check_mounted_where(fd, file, NULL, 0, NULL);
826 int check_mounted_where(int fd, const char *file, char *where, int size,
827 struct btrfs_fs_devices **fs_dev_ret)
832 struct btrfs_fs_devices *fs_devices_mnt = NULL;
836 /* scan the initial device */
837 ret = btrfs_scan_one_device(fd, file, &fs_devices_mnt,
838 &total_devs, BTRFS_SUPER_INFO_OFFSET);
839 is_btrfs = (ret >= 0);
841 /* scan other devices */
842 if (is_btrfs && total_devs > 1) {
843 if((ret = btrfs_scan_for_fsid(fs_devices_mnt, total_devs, 1)))
847 /* iterate over the list of currently mountes filesystems */
848 if ((f = setmntent ("/proc/mounts", "r")) == NULL)
851 while ((mnt = getmntent (f)) != NULL) {
853 if(strcmp(mnt->mnt_type, "btrfs") != 0)
856 ret = blk_file_in_dev_list(fs_devices_mnt, mnt->mnt_fsname);
858 /* ignore entries in the mount table that are not
859 associated with a file*/
860 if((ret = is_existing_blk_or_reg_file(mnt->mnt_fsname)) < 0)
861 goto out_mntloop_err;
865 ret = is_same_loop_file(file, mnt->mnt_fsname);
869 goto out_mntloop_err;
874 /* Did we find an entry in mnt table? */
875 if (mnt && size && where) {
876 strncpy(where, mnt->mnt_dir, size);
880 *fs_dev_ret = fs_devices_mnt;
890 /* Gets the mount point of btrfs filesystem that is using the specified device.
891 * Returns 0 is everything is good, <0 if we have an error.
892 * TODO: Fix this fucntion and check_mounted to work with multiple drive BTRFS
895 int get_mountpt(char *dev, char *mntpt, size_t size)
901 f = setmntent("/proc/mounts", "r");
905 while ((mnt = getmntent(f)) != NULL )
907 if (strcmp(dev, mnt->mnt_fsname) == 0)
909 strncpy(mntpt, mnt->mnt_dir, size);
918 /* We didn't find an entry so lets report an error */
926 struct list_head list;
930 void btrfs_register_one_device(char *fname)
932 struct btrfs_ioctl_vol_args args;
937 fd = open("/dev/btrfs-control", O_RDONLY);
939 fprintf(stderr, "failed to open /dev/btrfs-control "
940 "skipping device registration\n");
943 strncpy(args.name, fname, BTRFS_PATH_NAME_MAX);
944 args.name[BTRFS_PATH_NAME_MAX-1] = 0;
945 ret = ioctl(fd, BTRFS_IOC_SCAN_DEV, &args);
948 fprintf(stderr, "ERROR: device scan failed '%s' - %s\n",
954 int btrfs_scan_one_dir(char *dirname, int run_ioctl)
957 struct dirent *dirent;
958 struct pending_dir *pending;
964 struct list_head pending_list;
965 struct btrfs_fs_devices *tmp_devices;
968 INIT_LIST_HEAD(&pending_list);
970 pending = malloc(sizeof(*pending));
973 strcpy(pending->name, dirname);
976 dirname_len = strlen(pending->name);
977 fullpath = malloc(PATH_MAX);
978 dirname = pending->name;
984 dirp = opendir(dirname);
986 fprintf(stderr, "Unable to open %s for scanning\n", dirname);
991 dirent = readdir(dirp);
994 if (dirent->d_name[0] == '.')
996 if (dirname_len + strlen(dirent->d_name) + 2 > PATH_MAX) {
1000 snprintf(fullpath, PATH_MAX, "%s/%s", dirname, dirent->d_name);
1001 ret = lstat(fullpath, &st);
1003 fprintf(stderr, "failed to stat %s\n", fullpath);
1006 if (S_ISLNK(st.st_mode))
1008 if (S_ISDIR(st.st_mode)) {
1009 struct pending_dir *next = malloc(sizeof(*next));
1014 strcpy(next->name, fullpath);
1015 list_add_tail(&next->list, &pending_list);
1017 if (!S_ISBLK(st.st_mode)) {
1020 fd = open(fullpath, O_RDONLY);
1022 /* ignore the following errors:
1023 ENXIO (device don't exists)
1024 ENOMEDIUM (No medium found ->
1025 like a cd tray empty)
1027 if(errno != ENXIO && errno != ENOMEDIUM)
1028 fprintf(stderr, "failed to read %s: %s\n",
1029 fullpath, strerror(errno));
1032 ret = btrfs_scan_one_device(fd, fullpath, &tmp_devices,
1034 BTRFS_SUPER_INFO_OFFSET);
1035 if (ret == 0 && run_ioctl > 0) {
1036 btrfs_register_one_device(fullpath);
1040 if (!list_empty(&pending_list)) {
1042 pending = list_entry(pending_list.next, struct pending_dir,
1045 list_del(&pending->list);
1059 int btrfs_scan_for_fsid(struct btrfs_fs_devices *fs_devices, u64 total_devs,
1064 ret = btrfs_scan_block_devices(run_ioctls);
1066 ret = btrfs_scan_one_dir("/dev", run_ioctls);
1070 int btrfs_device_already_in_root(struct btrfs_root *root, int fd,
1073 struct btrfs_super_block *disk_super;
1077 buf = malloc(BTRFS_SUPER_INFO_SIZE);
1082 ret = pread(fd, buf, BTRFS_SUPER_INFO_SIZE, super_offset);
1083 if (ret != BTRFS_SUPER_INFO_SIZE)
1087 disk_super = (struct btrfs_super_block *)buf;
1088 if (disk_super->magic != cpu_to_le64(BTRFS_MAGIC))
1091 if (!memcmp(disk_super->fsid, root->fs_info->super_copy.fsid,
1100 static char *size_strs[] = { "", "KB", "MB", "GB", "TB",
1101 "PB", "EB", "ZB", "YB"};
1102 char *pretty_sizes(u64 size)
1105 int pretty_len = 16;
1113 u64 last_size = size;
1115 while(size >= 1024){
1121 if (num_divs >= ARRAY_SIZE(size_strs))
1123 fraction = (float)last_size / 1024;
1125 pretty = malloc(pretty_len);
1126 snprintf(pretty, pretty_len, "%.2f%s", fraction, size_strs[num_divs]);
1131 * __strncpy__null - strncpy with null termination
1132 * @dest: the target array
1133 * @src: the source string
1134 * @n: maximum bytes to copy (size of *dest)
1136 * Like strncpy, but ensures destination is null-terminated.
1138 * Copies the string pointed to by src, including the terminating null
1139 * byte ('\0'), to the buffer pointed to by dest, up to a maximum
1140 * of n bytes. Then ensure that dest is null-terminated.
1142 char *__strncpy__null(char *dest, const char *src, size_t n)
1144 strncpy(dest, src, n);
1151 * Checks to make sure that the label matches our requirements.
1153 0 if everything is safe and usable
1154 -1 if the label is too long
1156 static int check_label(const char *input)
1158 int len = strlen(input);
1160 if (len > BTRFS_LABEL_SIZE - 1) {
1161 fprintf(stderr, "ERROR: Label %s is too long (max %d)\n",
1162 input, BTRFS_LABEL_SIZE - 1);
1169 static int set_label_unmounted(const char *dev, const char *label)
1171 struct btrfs_trans_handle *trans;
1172 struct btrfs_root *root;
1175 ret = check_mounted(dev);
1177 fprintf(stderr, "FATAL: error checking %s mount status\n", dev);
1181 fprintf(stderr, "ERROR: dev %s is mounted, use mount point\n",
1186 /* Open the super_block at the default location
1187 * and as read-write.
1189 root = open_ctree(dev, 0, 1);
1190 if (!root) /* errors are printed by open_ctree() */
1193 trans = btrfs_start_transaction(root, 1);
1194 snprintf(root->fs_info->super_copy.label, BTRFS_LABEL_SIZE, "%s",
1196 btrfs_commit_transaction(trans, root);
1198 /* Now we close it since we are done. */
1203 static int set_label_mounted(const char *mount_path, const char *label)
1207 fd = open(mount_path, O_RDONLY | O_NOATIME);
1209 fprintf(stderr, "ERROR: unable access to '%s'\n", mount_path);
1213 if (ioctl(fd, BTRFS_IOC_SET_FSLABEL, label) < 0) {
1214 fprintf(stderr, "ERROR: unable to set label %s\n",
1223 static int get_label_unmounted(const char *dev)
1225 struct btrfs_root *root;
1228 ret = check_mounted(dev);
1230 fprintf(stderr, "FATAL: error checking %s mount status\n", dev);
1234 fprintf(stderr, "ERROR: dev %s is mounted, use mount point\n",
1239 /* Open the super_block at the default location
1242 root = open_ctree(dev, 0, 0);
1246 fprintf(stdout, "%s\n", root->fs_info->super_copy.label);
1248 /* Now we close it since we are done. */
1254 * If a partition is mounted, try to get the filesystem label via its
1255 * mounted path rather than device. Return the corresponding error
1256 * the user specified the device path.
1258 static int get_label_mounted(const char *mount_path)
1260 char label[BTRFS_LABEL_SIZE];
1263 fd = open(mount_path, O_RDONLY | O_NOATIME);
1265 fprintf(stderr, "ERROR: unable access to '%s'\n", mount_path);
1269 memset(label, '\0', sizeof(label));
1270 if (ioctl(fd, BTRFS_IOC_GET_FSLABEL, label) < 0) {
1271 fprintf(stderr, "ERROR: unable get label %s\n", strerror(errno));
1276 fprintf(stdout, "%s\n", label);
1280 int get_label(const char *btrfs_dev)
1282 return is_existing_blk_or_reg_file(btrfs_dev) ?
1283 get_label_unmounted(btrfs_dev) :
1284 get_label_mounted(btrfs_dev);
1287 int set_label(const char *btrfs_dev, const char *label)
1289 if (check_label(label))
1292 return is_existing_blk_or_reg_file(btrfs_dev) ?
1293 set_label_unmounted(btrfs_dev, label) :
1294 set_label_mounted(btrfs_dev, label);
1297 int btrfs_scan_block_devices(int run_ioctl)
1303 struct btrfs_fs_devices *tmp_devices;
1305 FILE *proc_partitions;
1313 proc_partitions = fopen("/proc/partitions","r");
1314 if (!proc_partitions) {
1315 fprintf(stderr, "Unable to open '/proc/partitions' for scanning\n");
1318 /* skip the header */
1319 for (i = 0; i < 2; i++)
1320 if (!fgets(buf, 1023, proc_partitions)) {
1322 "Unable to read '/proc/partitions' for scanning\n");
1323 fclose(proc_partitions);
1327 strcpy(fullpath,"/dev/");
1328 while(fgets(buf, 1023, proc_partitions)) {
1329 i = sscanf(buf," %*d %*d %*d %99s", fullpath+5);
1332 * multipath and MD devices may register as a btrfs filesystem
1333 * both through the original block device and through
1334 * the special (/dev/mapper or /dev/mdX) entry.
1335 * This scans the special entries last
1337 special = strncmp(fullpath, "/dev/dm-", strlen("/dev/dm-")) == 0;
1339 special = strncmp(fullpath, "/dev/md", strlen("/dev/md")) == 0;
1341 if (scans == 0 && special)
1343 if (scans > 0 && !special)
1346 ret = lstat(fullpath, &st);
1348 fprintf(stderr, "failed to stat %s\n", fullpath);
1351 if (!S_ISBLK(st.st_mode)) {
1355 fd = open(fullpath, O_RDONLY);
1357 fprintf(stderr, "failed to open %s: %s\n",
1358 fullpath, strerror(errno));
1361 ret = btrfs_scan_one_device(fd, fullpath, &tmp_devices,
1363 BTRFS_SUPER_INFO_OFFSET);
1364 if (ret == 0 && run_ioctl > 0) {
1365 btrfs_register_one_device(fullpath);
1370 fclose(proc_partitions);
1379 u64 parse_size(char *s)
1385 for (i = 0; s && s[i] && isdigit(s[i]); i++) ;
1387 fprintf(stderr, "ERROR: size value is empty\n");
1409 fprintf(stderr, "ERROR: Unknown size descriptor "
1414 if (s[i] && s[i+1]) {
1415 fprintf(stderr, "ERROR: Illegal suffix contains "
1416 "character '%c' in wrong position\n",
1420 return strtoull(s, NULL, 10) * mult;
1423 int open_file_or_dir(const char *fname)
1430 ret = stat(fname, &st);
1434 if (S_ISDIR(st.st_mode)) {
1435 dirstream = opendir(fname);
1439 fd = dirfd(dirstream);
1441 fd = open(fname, O_RDWR);
1449 int get_device_info(int fd, u64 devid,
1450 struct btrfs_ioctl_dev_info_args *di_args)
1454 di_args->devid = devid;
1455 memset(&di_args->uuid, '\0', sizeof(di_args->uuid));
1457 ret = ioctl(fd, BTRFS_IOC_DEV_INFO, di_args);
1458 return ret ? -errno : 0;
1461 int get_fs_info(int fd, char *path, struct btrfs_ioctl_fs_info_args *fi_args,
1462 struct btrfs_ioctl_dev_info_args **di_ret)
1467 struct btrfs_fs_devices *fs_devices_mnt = NULL;
1468 struct btrfs_ioctl_dev_info_args *di_args;
1469 char mp[BTRFS_PATH_NAME_MAX + 1];
1471 memset(fi_args, 0, sizeof(*fi_args));
1473 ret = ioctl(fd, BTRFS_IOC_FS_INFO, fi_args);
1474 if (ret && (errno == EINVAL || errno == ENOTTY)) {
1475 /* path is not a mounted btrfs. Try if it's a device */
1476 ret = check_mounted_where(fd, path, mp, sizeof(mp),
1482 fi_args->num_devices = 1;
1483 fi_args->max_id = fs_devices_mnt->latest_devid;
1484 i = fs_devices_mnt->latest_devid;
1485 memcpy(fi_args->fsid, fs_devices_mnt->fsid, BTRFS_FSID_SIZE);
1487 fd = open_file_or_dir(mp);
1494 if (!fi_args->num_devices)
1497 di_args = *di_ret = malloc(fi_args->num_devices * sizeof(*di_args));
1501 for (; i <= fi_args->max_id; ++i) {
1502 BUG_ON(ndevs >= fi_args->num_devices);
1503 ret = get_device_info(fd, i, &di_args[ndevs]);
1516 #define isoctal(c) (((c) & ~7) == '0')
1518 static inline void translate(char *f, char *t)
1520 while (*f != '\0') {
1522 isoctal(f[1]) && isoctal(f[2]) && isoctal(f[3])) {
1523 *t++ = 64*(f[1] & 7) + 8*(f[2] & 7) + (f[3] & 7);
1533 * Checks if the swap device.
1534 * Returns 1 if swap device, < 0 on error or 0 if not swap device.
1536 int is_swap_device(const char *file)
1547 if (stat(file, &st_buf) < 0)
1549 if (S_ISBLK(st_buf.st_mode))
1550 dev = st_buf.st_rdev;
1551 else if (S_ISREG(st_buf.st_mode)) {
1552 dev = st_buf.st_dev;
1553 ino = st_buf.st_ino;
1557 if ((f = fopen("/proc/swaps", "r")) == NULL)
1560 /* skip the first line */
1561 if (fgets(tmp, sizeof(tmp), f) == NULL)
1564 while (fgets(tmp, sizeof(tmp), f) != NULL) {
1565 if ((cp = strchr(tmp, ' ')) != NULL)
1567 if ((cp = strchr(tmp, '\t')) != NULL)
1569 translate(tmp, buf);
1570 if (stat(buf, &st_buf) != 0)
1572 if (S_ISBLK(st_buf.st_mode)) {
1573 if (dev == st_buf.st_rdev) {
1577 } else if (S_ISREG(st_buf.st_mode)) {
1578 if (dev == st_buf.st_dev && ino == st_buf.st_ino) {