35e17b8b5c92ec67c76515dc444a968e28946401
[platform/upstream/btrfs-progs.git] / utils.c
1 /*
2  * Copyright (C) 2007 Oracle.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18
19 #define _XOPEN_SOURCE 600
20 #define __USE_XOPEN2K
21 #include <stdio.h>
22 #include <stdlib.h>
23 #ifndef __CHECKER__
24 #include <sys/ioctl.h>
25 #include <sys/mount.h>
26 #endif
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <uuid/uuid.h>
30 #include <dirent.h>
31 #include <fcntl.h>
32 #include <unistd.h>
33 #include <mntent.h>
34 #include <linux/loop.h>
35 #include <linux/major.h>
36 #include <linux/kdev_t.h>
37 #include <limits.h>
38 #include "kerncompat.h"
39 #include "radix-tree.h"
40 #include "ctree.h"
41 #include "disk-io.h"
42 #include "transaction.h"
43 #include "crc32c.h"
44 #include "utils.h"
45 #include "volumes.h"
46 #include "ioctl.h"
47
48 #ifdef __CHECKER__
49 #define BLKGETSIZE64 0
50 static inline int ioctl(int fd, int define, u64 *size) { return 0; }
51 #endif
52
53 static u64 reference_root_table[] = {
54         [1] =   BTRFS_ROOT_TREE_OBJECTID,
55         [2] =   BTRFS_EXTENT_TREE_OBJECTID,
56         [3] =   BTRFS_CHUNK_TREE_OBJECTID,
57         [4] =   BTRFS_DEV_TREE_OBJECTID,
58         [5] =   BTRFS_FS_TREE_OBJECTID,
59         [6] =   BTRFS_CSUM_TREE_OBJECTID,
60 };
61
62 int make_btrfs(int fd, const char *device, const char *label,
63                u64 blocks[7], u64 num_bytes, u32 nodesize,
64                u32 leafsize, u32 sectorsize, u32 stripesize)
65 {
66         struct btrfs_super_block super;
67         struct extent_buffer *buf;
68         struct btrfs_root_item root_item;
69         struct btrfs_disk_key disk_key;
70         struct btrfs_extent_item *extent_item;
71         struct btrfs_inode_item *inode_item;
72         struct btrfs_chunk *chunk;
73         struct btrfs_dev_item *dev_item;
74         struct btrfs_dev_extent *dev_extent;
75         u8 chunk_tree_uuid[BTRFS_UUID_SIZE];
76         u8 *ptr;
77         int i;
78         int ret;
79         u32 itemoff;
80         u32 nritems = 0;
81         u64 first_free;
82         u64 ref_root;
83         u32 array_size;
84         u32 item_size;
85
86         first_free = BTRFS_SUPER_INFO_OFFSET + sectorsize * 2 - 1;
87         first_free &= ~((u64)sectorsize - 1);
88
89         memset(&super, 0, sizeof(super));
90
91         num_bytes = (num_bytes / sectorsize) * sectorsize;
92         uuid_generate(super.fsid);
93         uuid_generate(super.dev_item.uuid);
94         uuid_generate(chunk_tree_uuid);
95
96         btrfs_set_super_bytenr(&super, blocks[0]);
97         btrfs_set_super_num_devices(&super, 1);
98         strncpy((char *)&super.magic, BTRFS_MAGIC, sizeof(super.magic));
99         btrfs_set_super_generation(&super, 1);
100         btrfs_set_super_root(&super, blocks[1]);
101         btrfs_set_super_chunk_root(&super, blocks[3]);
102         btrfs_set_super_total_bytes(&super, num_bytes);
103         btrfs_set_super_bytes_used(&super, 6 * leafsize);
104         btrfs_set_super_sectorsize(&super, sectorsize);
105         btrfs_set_super_leafsize(&super, leafsize);
106         btrfs_set_super_nodesize(&super, nodesize);
107         btrfs_set_super_stripesize(&super, stripesize);
108         btrfs_set_super_csum_type(&super, BTRFS_CSUM_TYPE_CRC32);
109         btrfs_set_super_chunk_root_generation(&super, 1);
110         btrfs_set_super_cache_generation(&super, -1);
111         if (label)
112                 strncpy(super.label, label, BTRFS_LABEL_SIZE - 1);
113
114         buf = malloc(sizeof(*buf) + max(sectorsize, leafsize));
115
116         /* create the tree of root objects */
117         memset(buf->data, 0, leafsize);
118         buf->len = leafsize;
119         btrfs_set_header_bytenr(buf, blocks[1]);
120         btrfs_set_header_nritems(buf, 4);
121         btrfs_set_header_generation(buf, 1);
122         btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
123         btrfs_set_header_owner(buf, BTRFS_ROOT_TREE_OBJECTID);
124         write_extent_buffer(buf, super.fsid, (unsigned long)
125                             btrfs_header_fsid(buf), BTRFS_FSID_SIZE);
126
127         write_extent_buffer(buf, chunk_tree_uuid, (unsigned long)
128                             btrfs_header_chunk_tree_uuid(buf),
129                             BTRFS_UUID_SIZE);
130
131         /* create the items for the root tree */
132         memset(&root_item, 0, sizeof(root_item));
133         inode_item = &root_item.inode;
134         btrfs_set_stack_inode_generation(inode_item, 1);
135         btrfs_set_stack_inode_size(inode_item, 3);
136         btrfs_set_stack_inode_nlink(inode_item, 1);
137         btrfs_set_stack_inode_nbytes(inode_item, leafsize);
138         btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
139         btrfs_set_root_refs(&root_item, 1);
140         btrfs_set_root_used(&root_item, leafsize);
141         btrfs_set_root_generation(&root_item, 1);
142
143         memset(&disk_key, 0, sizeof(disk_key));
144         btrfs_set_disk_key_type(&disk_key, BTRFS_ROOT_ITEM_KEY);
145         btrfs_set_disk_key_offset(&disk_key, 0);
146         nritems = 0;
147
148         itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize) - sizeof(root_item);
149         btrfs_set_root_bytenr(&root_item, blocks[2]);
150         btrfs_set_disk_key_objectid(&disk_key, BTRFS_EXTENT_TREE_OBJECTID);
151         btrfs_set_item_key(buf, &disk_key, nritems);
152         btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems), itemoff);
153         btrfs_set_item_size(buf, btrfs_item_nr(buf, nritems),
154                             sizeof(root_item));
155         write_extent_buffer(buf, &root_item, btrfs_item_ptr_offset(buf,
156                             nritems), sizeof(root_item));
157         nritems++;
158
159         itemoff = itemoff - sizeof(root_item);
160         btrfs_set_root_bytenr(&root_item, blocks[4]);
161         btrfs_set_disk_key_objectid(&disk_key, BTRFS_DEV_TREE_OBJECTID);
162         btrfs_set_item_key(buf, &disk_key, nritems);
163         btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems), itemoff);
164         btrfs_set_item_size(buf, btrfs_item_nr(buf, nritems),
165                             sizeof(root_item));
166         write_extent_buffer(buf, &root_item,
167                             btrfs_item_ptr_offset(buf, nritems),
168                             sizeof(root_item));
169         nritems++;
170
171         itemoff = itemoff - sizeof(root_item);
172         btrfs_set_root_bytenr(&root_item, blocks[5]);
173         btrfs_set_disk_key_objectid(&disk_key, BTRFS_FS_TREE_OBJECTID);
174         btrfs_set_item_key(buf, &disk_key, nritems);
175         btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems), itemoff);
176         btrfs_set_item_size(buf, btrfs_item_nr(buf, nritems),
177                             sizeof(root_item));
178         write_extent_buffer(buf, &root_item,
179                             btrfs_item_ptr_offset(buf, nritems),
180                             sizeof(root_item));
181         nritems++;
182
183         itemoff = itemoff - sizeof(root_item);
184         btrfs_set_root_bytenr(&root_item, blocks[6]);
185         btrfs_set_disk_key_objectid(&disk_key, BTRFS_CSUM_TREE_OBJECTID);
186         btrfs_set_item_key(buf, &disk_key, nritems);
187         btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems), itemoff);
188         btrfs_set_item_size(buf, btrfs_item_nr(buf, nritems),
189                             sizeof(root_item));
190         write_extent_buffer(buf, &root_item,
191                             btrfs_item_ptr_offset(buf, nritems),
192                             sizeof(root_item));
193         nritems++;
194
195
196         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
197         ret = pwrite(fd, buf->data, leafsize, blocks[1]);
198         BUG_ON(ret != leafsize);
199
200         /* create the items for the extent tree */
201         nritems = 0;
202         itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize);
203         for (i = 1; i < 7; i++) {
204                 BUG_ON(blocks[i] < first_free);
205                 BUG_ON(blocks[i] < blocks[i - 1]);
206
207                 /* create extent item */
208                 itemoff -= sizeof(struct btrfs_extent_item) +
209                            sizeof(struct btrfs_tree_block_info);
210                 btrfs_set_disk_key_objectid(&disk_key, blocks[i]);
211                 btrfs_set_disk_key_offset(&disk_key, leafsize);
212                 btrfs_set_disk_key_type(&disk_key, BTRFS_EXTENT_ITEM_KEY);
213                 btrfs_set_item_key(buf, &disk_key, nritems);
214                 btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems),
215                                       itemoff);
216                 btrfs_set_item_size(buf, btrfs_item_nr(buf, nritems),
217                                     sizeof(struct btrfs_extent_item) +
218                                     sizeof(struct btrfs_tree_block_info));
219                 extent_item = btrfs_item_ptr(buf, nritems,
220                                              struct btrfs_extent_item);
221                 btrfs_set_extent_refs(buf, extent_item, 1);
222                 btrfs_set_extent_generation(buf, extent_item, 1);
223                 btrfs_set_extent_flags(buf, extent_item,
224                                        BTRFS_EXTENT_FLAG_TREE_BLOCK);
225                 nritems++;
226
227                 /* create extent ref */
228                 ref_root = reference_root_table[i];
229                 btrfs_set_disk_key_objectid(&disk_key, blocks[i]);
230                 btrfs_set_disk_key_offset(&disk_key, ref_root);
231                 btrfs_set_disk_key_type(&disk_key, BTRFS_TREE_BLOCK_REF_KEY);
232                 btrfs_set_item_key(buf, &disk_key, nritems);
233                 btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems),
234                                       itemoff);
235                 btrfs_set_item_size(buf, btrfs_item_nr(buf, nritems), 0);
236                 nritems++;
237         }
238         btrfs_set_header_bytenr(buf, blocks[2]);
239         btrfs_set_header_owner(buf, BTRFS_EXTENT_TREE_OBJECTID);
240         btrfs_set_header_nritems(buf, nritems);
241         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
242         ret = pwrite(fd, buf->data, leafsize, blocks[2]);
243         BUG_ON(ret != leafsize);
244
245         /* create the chunk tree */
246         nritems = 0;
247         item_size = sizeof(*dev_item);
248         itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize) - item_size;
249
250         /* first device 1 (there is no device 0) */
251         btrfs_set_disk_key_objectid(&disk_key, BTRFS_DEV_ITEMS_OBJECTID);
252         btrfs_set_disk_key_offset(&disk_key, 1);
253         btrfs_set_disk_key_type(&disk_key, BTRFS_DEV_ITEM_KEY);
254         btrfs_set_item_key(buf, &disk_key, nritems);
255         btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems), itemoff);
256         btrfs_set_item_size(buf, btrfs_item_nr(buf, nritems), item_size);
257
258         dev_item = btrfs_item_ptr(buf, nritems, struct btrfs_dev_item);
259         btrfs_set_device_id(buf, dev_item, 1);
260         btrfs_set_device_generation(buf, dev_item, 0);
261         btrfs_set_device_total_bytes(buf, dev_item, num_bytes);
262         btrfs_set_device_bytes_used(buf, dev_item,
263                                     BTRFS_MKFS_SYSTEM_GROUP_SIZE);
264         btrfs_set_device_io_align(buf, dev_item, sectorsize);
265         btrfs_set_device_io_width(buf, dev_item, sectorsize);
266         btrfs_set_device_sector_size(buf, dev_item, sectorsize);
267         btrfs_set_device_type(buf, dev_item, 0);
268
269         write_extent_buffer(buf, super.dev_item.uuid,
270                             (unsigned long)btrfs_device_uuid(dev_item),
271                             BTRFS_UUID_SIZE);
272         write_extent_buffer(buf, super.fsid,
273                             (unsigned long)btrfs_device_fsid(dev_item),
274                             BTRFS_UUID_SIZE);
275         read_extent_buffer(buf, &super.dev_item, (unsigned long)dev_item,
276                            sizeof(*dev_item));
277
278         nritems++;
279         item_size = btrfs_chunk_item_size(1);
280         itemoff = itemoff - item_size;
281
282         /* then we have chunk 0 */
283         btrfs_set_disk_key_objectid(&disk_key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
284         btrfs_set_disk_key_offset(&disk_key, 0);
285         btrfs_set_disk_key_type(&disk_key, BTRFS_CHUNK_ITEM_KEY);
286         btrfs_set_item_key(buf, &disk_key, nritems);
287         btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems), itemoff);
288         btrfs_set_item_size(buf, btrfs_item_nr(buf,  nritems), item_size);
289
290         chunk = btrfs_item_ptr(buf, nritems, struct btrfs_chunk);
291         btrfs_set_chunk_length(buf, chunk, BTRFS_MKFS_SYSTEM_GROUP_SIZE);
292         btrfs_set_chunk_owner(buf, chunk, BTRFS_EXTENT_TREE_OBJECTID);
293         btrfs_set_chunk_stripe_len(buf, chunk, 64 * 1024);
294         btrfs_set_chunk_type(buf, chunk, BTRFS_BLOCK_GROUP_SYSTEM);
295         btrfs_set_chunk_io_align(buf, chunk, sectorsize);
296         btrfs_set_chunk_io_width(buf, chunk, sectorsize);
297         btrfs_set_chunk_sector_size(buf, chunk, sectorsize);
298         btrfs_set_chunk_num_stripes(buf, chunk, 1);
299         btrfs_set_stripe_devid_nr(buf, chunk, 0, 1);
300         btrfs_set_stripe_offset_nr(buf, chunk, 0, 0);
301         nritems++;
302
303         write_extent_buffer(buf, super.dev_item.uuid,
304                             (unsigned long)btrfs_stripe_dev_uuid(&chunk->stripe),
305                             BTRFS_UUID_SIZE);
306
307         /* copy the key for the chunk to the system array */
308         ptr = super.sys_chunk_array;
309         array_size = sizeof(disk_key);
310
311         memcpy(ptr, &disk_key, sizeof(disk_key));
312         ptr += sizeof(disk_key);
313
314         /* copy the chunk to the system array */
315         read_extent_buffer(buf, ptr, (unsigned long)chunk, item_size);
316         array_size += item_size;
317         ptr += item_size;
318         btrfs_set_super_sys_array_size(&super, array_size);
319
320         btrfs_set_header_bytenr(buf, blocks[3]);
321         btrfs_set_header_owner(buf, BTRFS_CHUNK_TREE_OBJECTID);
322         btrfs_set_header_nritems(buf, nritems);
323         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
324         ret = pwrite(fd, buf->data, leafsize, blocks[3]);
325
326         /* create the device tree */
327         nritems = 0;
328         itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize) -
329                 sizeof(struct btrfs_dev_extent);
330
331         btrfs_set_disk_key_objectid(&disk_key, 1);
332         btrfs_set_disk_key_offset(&disk_key, 0);
333         btrfs_set_disk_key_type(&disk_key, BTRFS_DEV_EXTENT_KEY);
334         btrfs_set_item_key(buf, &disk_key, nritems);
335         btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems), itemoff);
336         btrfs_set_item_size(buf, btrfs_item_nr(buf,  nritems),
337                             sizeof(struct btrfs_dev_extent));
338         dev_extent = btrfs_item_ptr(buf, nritems, struct btrfs_dev_extent);
339         btrfs_set_dev_extent_chunk_tree(buf, dev_extent,
340                                         BTRFS_CHUNK_TREE_OBJECTID);
341         btrfs_set_dev_extent_chunk_objectid(buf, dev_extent,
342                                         BTRFS_FIRST_CHUNK_TREE_OBJECTID);
343         btrfs_set_dev_extent_chunk_offset(buf, dev_extent, 0);
344
345         write_extent_buffer(buf, chunk_tree_uuid,
346                     (unsigned long)btrfs_dev_extent_chunk_tree_uuid(dev_extent),
347                     BTRFS_UUID_SIZE);
348
349         btrfs_set_dev_extent_length(buf, dev_extent,
350                                     BTRFS_MKFS_SYSTEM_GROUP_SIZE);
351         nritems++;
352
353         btrfs_set_header_bytenr(buf, blocks[4]);
354         btrfs_set_header_owner(buf, BTRFS_DEV_TREE_OBJECTID);
355         btrfs_set_header_nritems(buf, nritems);
356         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
357         ret = pwrite(fd, buf->data, leafsize, blocks[4]);
358
359         /* create the FS root */
360         btrfs_set_header_bytenr(buf, blocks[5]);
361         btrfs_set_header_owner(buf, BTRFS_FS_TREE_OBJECTID);
362         btrfs_set_header_nritems(buf, 0);
363         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
364         ret = pwrite(fd, buf->data, leafsize, blocks[5]);
365         BUG_ON(ret != leafsize);
366
367         /* finally create the csum root */
368         btrfs_set_header_bytenr(buf, blocks[6]);
369         btrfs_set_header_owner(buf, BTRFS_CSUM_TREE_OBJECTID);
370         btrfs_set_header_nritems(buf, 0);
371         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
372         ret = pwrite(fd, buf->data, leafsize, blocks[6]);
373         BUG_ON(ret != leafsize);
374
375         /* and write out the super block */
376         BUG_ON(sizeof(super) > sectorsize);
377         memset(buf->data, 0, sectorsize);
378         memcpy(buf->data, &super, sizeof(super));
379         buf->len = sectorsize;
380         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
381         ret = pwrite(fd, buf->data, sectorsize, blocks[0]);
382         BUG_ON(ret != sectorsize);
383
384
385         free(buf);
386         return 0;
387 }
388
389 static u64 device_size(int fd, struct stat *st)
390 {
391         u64 size;
392         if (S_ISREG(st->st_mode)) {
393                 return st->st_size;
394         }
395         if (!S_ISBLK(st->st_mode)) {
396                 return 0;
397         }
398         if (ioctl(fd, BLKGETSIZE64, &size) >= 0) {
399                 return size;
400         }
401         return 0;
402 }
403
404 static int zero_blocks(int fd, off_t start, size_t len)
405 {
406         char *buf = malloc(len);
407         int ret = 0;
408         ssize_t written;
409
410         if (!buf)
411                 return -ENOMEM;
412         memset(buf, 0, len);
413         written = pwrite(fd, buf, len, start);
414         if (written != len)
415                 ret = -EIO;
416         free(buf);
417         return ret;
418 }
419
420 static int zero_dev_start(int fd)
421 {
422         off_t start = 0;
423         size_t len = 2 * 1024 * 1024;
424
425 #ifdef __sparc__
426         /* don't overwrite the disk labels on sparc */
427         start = 1024;
428         len -= 1024;
429 #endif
430         return zero_blocks(fd, start, len);
431 }
432
433 static int zero_dev_end(int fd, u64 dev_size)
434 {
435         size_t len = 2 * 1024 * 1024;
436         off_t start = dev_size - len;
437
438         return zero_blocks(fd, start, len);
439 }
440
441 int btrfs_add_to_fsid(struct btrfs_trans_handle *trans,
442                       struct btrfs_root *root, int fd, char *path,
443                       u64 block_count, u32 io_width, u32 io_align,
444                       u32 sectorsize)
445 {
446         struct btrfs_super_block *disk_super;
447         struct btrfs_super_block *super = &root->fs_info->super_copy;
448         struct btrfs_device *device;
449         struct btrfs_dev_item *dev_item;
450         char *buf;
451         u64 total_bytes;
452         u64 num_devs;
453         int ret;
454
455         device = kmalloc(sizeof(*device), GFP_NOFS);
456         if (!device)
457                 return -ENOMEM;
458         buf = kmalloc(sectorsize, GFP_NOFS);
459         if (!buf) {
460                 kfree(device);
461                 return -ENOMEM;
462         }
463         BUG_ON(sizeof(*disk_super) > sectorsize);
464         memset(buf, 0, sectorsize);
465
466         disk_super = (struct btrfs_super_block *)buf;
467         dev_item = &disk_super->dev_item;
468
469         uuid_generate(device->uuid);
470         device->devid = 0;
471         device->type = 0;
472         device->io_width = io_width;
473         device->io_align = io_align;
474         device->sector_size = sectorsize;
475         device->fd = fd;
476         device->writeable = 1;
477         device->total_bytes = block_count;
478         device->bytes_used = 0;
479         device->total_ios = 0;
480         device->dev_root = root->fs_info->dev_root;
481
482         ret = btrfs_add_device(trans, root, device);
483         BUG_ON(ret);
484
485         total_bytes = btrfs_super_total_bytes(super) + block_count;
486         btrfs_set_super_total_bytes(super, total_bytes);
487
488         num_devs = btrfs_super_num_devices(super) + 1;
489         btrfs_set_super_num_devices(super, num_devs);
490
491         memcpy(disk_super, super, sizeof(*disk_super));
492
493         printf("adding device %s id %llu\n", path,
494                (unsigned long long)device->devid);
495
496         btrfs_set_super_bytenr(disk_super, BTRFS_SUPER_INFO_OFFSET);
497         btrfs_set_stack_device_id(dev_item, device->devid);
498         btrfs_set_stack_device_type(dev_item, device->type);
499         btrfs_set_stack_device_io_align(dev_item, device->io_align);
500         btrfs_set_stack_device_io_width(dev_item, device->io_width);
501         btrfs_set_stack_device_sector_size(dev_item, device->sector_size);
502         btrfs_set_stack_device_total_bytes(dev_item, device->total_bytes);
503         btrfs_set_stack_device_bytes_used(dev_item, device->bytes_used);
504         memcpy(&dev_item->uuid, device->uuid, BTRFS_UUID_SIZE);
505
506         ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
507         BUG_ON(ret != sectorsize);
508
509         kfree(buf);
510         list_add(&device->dev_list, &root->fs_info->fs_devices->devices);
511         device->fs_devices = root->fs_info->fs_devices;
512         return 0;
513 }
514
515 int btrfs_prepare_device(int fd, char *file, int zero_end, u64 *block_count_ret)
516 {
517         u64 block_count;
518         u64 bytenr;
519         struct stat st;
520         int i, ret;
521
522         ret = fstat(fd, &st);
523         if (ret < 0) {
524                 fprintf(stderr, "unable to stat %s\n", file);
525                 exit(1);
526         }
527
528         block_count = device_size(fd, &st);
529         if (block_count == 0) {
530                 fprintf(stderr, "unable to find %s size\n", file);
531                 exit(1);
532         }
533         zero_end = 1;
534
535         if (block_count < 256 * 1024 * 1024) {
536                 fprintf(stderr, "device %s is too small "
537                         "(must be at least 256 MB)\n", file);
538                 exit(1);
539         }
540         ret = zero_dev_start(fd);
541         if (ret) {
542                 fprintf(stderr, "failed to zero device start %d\n", ret);
543                 exit(1);
544         }
545
546         for (i = 0 ; i < BTRFS_SUPER_MIRROR_MAX; i++) {
547                 bytenr = btrfs_sb_offset(i);
548                 if (bytenr >= block_count)
549                         break;
550                 zero_blocks(fd, bytenr, BTRFS_SUPER_INFO_SIZE);
551         }
552
553         if (zero_end) {
554                 ret = zero_dev_end(fd, block_count);
555                 if (ret) {
556                         fprintf(stderr, "failed to zero device end %d\n", ret);
557                         exit(1);
558                 }
559         }
560         *block_count_ret = block_count;
561         return 0;
562 }
563
564 int btrfs_make_root_dir(struct btrfs_trans_handle *trans,
565                         struct btrfs_root *root, u64 objectid)
566 {
567         int ret;
568         struct btrfs_inode_item inode_item;
569
570         memset(&inode_item, 0, sizeof(inode_item));
571         btrfs_set_stack_inode_generation(&inode_item, trans->transid);
572         btrfs_set_stack_inode_size(&inode_item, 0);
573         btrfs_set_stack_inode_nlink(&inode_item, 1);
574         btrfs_set_stack_inode_nbytes(&inode_item, root->leafsize);
575         btrfs_set_stack_inode_mode(&inode_item, S_IFDIR | 0555);
576
577         if (root->fs_info->tree_root == root)
578                 btrfs_set_super_root_dir(&root->fs_info->super_copy, objectid);
579
580         ret = btrfs_insert_inode(trans, root, objectid, &inode_item);
581         if (ret)
582                 goto error;
583
584         ret = btrfs_insert_inode_ref(trans, root, "..", 2, objectid, objectid, 0);
585         if (ret)
586                 goto error;
587
588         btrfs_set_root_dirid(&root->root_item, objectid);
589         ret = 0;
590 error:
591         return ret;
592 }
593
594 /* checks if a device is a loop device */
595 int is_loop_device (const char* device) {
596         struct stat statbuf;
597
598         if(stat(device, &statbuf) < 0)
599                 return -errno;
600
601         return (S_ISBLK(statbuf.st_mode) &&
602                 MAJOR(statbuf.st_rdev) == LOOP_MAJOR);
603 }
604
605
606 /* Takes a loop device path (e.g. /dev/loop0) and returns
607  * the associated file (e.g. /images/my_btrfs.img) */
608 int resolve_loop_device(const char* loop_dev, char* loop_file, int max_len)
609 {
610         int loop_fd;
611         int ret_ioctl;
612         struct loop_info loopinfo;
613
614         if ((loop_fd = open(loop_dev, O_RDONLY)) < 0)
615                 return -errno;
616
617         ret_ioctl = ioctl(loop_fd, LOOP_GET_STATUS, &loopinfo);
618         close(loop_fd);
619
620         if (ret_ioctl == 0)
621                 strncpy(loop_file, loopinfo.lo_name, max_len);
622         else
623                 return -errno;
624
625         return 0;
626 }
627
628 /* Checks whether a and b are identical or device
629  * files associated with the same block device
630  */
631 int is_same_blk_file(const char* a, const char* b)
632 {
633         struct stat st_buf_a, st_buf_b;
634         char real_a[PATH_MAX];
635         char real_b[PATH_MAX];
636
637         if(!realpath(a, real_a) ||
638            !realpath(b, real_b))
639         {
640                 return -errno;
641         }
642
643         /* Identical path? */
644         if(strcmp(real_a, real_b) == 0)
645                 return 1;
646
647         if(stat(a, &st_buf_a) < 0 ||
648            stat(b, &st_buf_b) < 0)
649         {
650                 return -errno;
651         }
652
653         /* Same blockdevice? */
654         if(S_ISBLK(st_buf_a.st_mode) &&
655            S_ISBLK(st_buf_b.st_mode) &&
656            st_buf_a.st_rdev == st_buf_b.st_rdev)
657         {
658                 return 1;
659         }
660
661         /* Hardlink? */
662         if (st_buf_a.st_dev == st_buf_b.st_dev &&
663             st_buf_a.st_ino == st_buf_b.st_ino)
664         {
665                 return 1;
666         }
667
668         return 0;
669 }
670
671 /* checks if a and b are identical or device
672  * files associated with the same block device or
673  * if one file is a loop device that uses the other
674  * file.
675  */
676 int is_same_loop_file(const char* a, const char* b)
677 {
678         char res_a[PATH_MAX];
679         char res_b[PATH_MAX];
680         const char* final_a;
681         const char* final_b;
682         int ret;
683
684         /* Resolve a if it is a loop device */
685         if((ret = is_loop_device(a)) < 0) {
686            return ret;
687         } else if(ret) {
688                 if((ret = resolve_loop_device(a, res_a, sizeof(res_a))) < 0)
689                         return ret;
690
691                 final_a = res_a;
692         } else {
693                 final_a = a;
694         }
695
696         /* Resolve b if it is a loop device */
697         if((ret = is_loop_device(b)) < 0) {
698            return ret;
699         } else if(ret) {
700                 if((ret = resolve_loop_device(b, res_b, sizeof(res_b))) < 0)
701                         return ret;
702
703                 final_b = res_b;
704         } else {
705                 final_b = b;
706         }
707
708         return is_same_blk_file(final_a, final_b);
709 }
710
711 /* Checks if a file exists and is a block or regular file*/
712 int is_existing_blk_or_reg_file(const char* filename)
713 {
714         struct stat st_buf;
715
716         if(stat(filename, &st_buf) < 0) {
717                 if(errno == ENOENT)
718                         return 0;
719                 else
720                         return -errno;
721         }
722
723         return (S_ISBLK(st_buf.st_mode) || S_ISREG(st_buf.st_mode));
724 }
725
726 /* Checks if a file is used (directly or indirectly via a loop device)
727  * by a device in fs_devices
728  */
729 int blk_file_in_dev_list(struct btrfs_fs_devices* fs_devices, const char* file)
730 {
731         int ret;
732         struct list_head *head;
733         struct list_head *cur;
734         struct btrfs_device *device;
735
736         head = &fs_devices->devices;
737         list_for_each(cur, head) {
738                 device = list_entry(cur, struct btrfs_device, dev_list);
739
740                 if((ret = is_same_loop_file(device->name, file)))
741                         return ret;
742         }
743
744         return 0;
745 }
746
747 /*
748  * returns 1 if the device was mounted, < 0 on error or 0 if everything
749  * is safe to continue.
750  */
751 int check_mounted(const char* file)
752 {
753         int ret;
754         int fd;
755         u64 total_devs = 1;
756         int is_btrfs;
757         struct btrfs_fs_devices* fs_devices_mnt = NULL;
758         FILE *f;
759         struct mntent *mnt;
760
761         fd = open(file, O_RDONLY);
762         if (fd < 0) {
763                 fprintf (stderr, "check_mounted(): Could not open %s\n", file);
764                 return -errno;
765         }
766
767         /* scan the initial device */
768         ret = btrfs_scan_one_device(fd, file, &fs_devices_mnt,
769                                     &total_devs, BTRFS_SUPER_INFO_OFFSET);
770         is_btrfs = (ret >= 0);
771         close(fd);
772
773         /* scan other devices */
774         if (is_btrfs && total_devs > 1) {
775                 if((ret = btrfs_scan_for_fsid(fs_devices_mnt, total_devs, 1)))
776                         return ret;
777         }
778
779         /* iterate over the list of currently mountes filesystems */
780         if ((f = setmntent ("/proc/mounts", "r")) == NULL)
781                 return -errno;
782
783         while ((mnt = getmntent (f)) != NULL) {
784                 if(is_btrfs) {
785                         if(strcmp(mnt->mnt_type, "btrfs") != 0)
786                                 continue;
787
788                         ret = blk_file_in_dev_list(fs_devices_mnt, mnt->mnt_fsname);
789                 } else {
790                         /* ignore entries in the mount table that are not
791                            associated with a file*/
792                         if((ret = is_existing_blk_or_reg_file(mnt->mnt_fsname)) < 0)
793                                 goto out_mntloop_err;
794                         else if(!ret)
795                                 continue;
796
797                         ret = is_same_loop_file(file, mnt->mnt_fsname);
798                 }
799
800                 if(ret < 0)
801                         goto out_mntloop_err;
802                 else if(ret)
803                         break;
804         }
805
806         /* Did we find an entry in mnt table? */
807         ret = (mnt != NULL);
808
809 out_mntloop_err:
810         endmntent (f);
811
812         return ret;
813 }
814
815 struct pending_dir {
816         struct list_head list;
817         char name[256];
818 };
819
820 void btrfs_register_one_device(char *fname)
821 {
822         struct btrfs_ioctl_vol_args args;
823         int fd;
824         int ret;
825         int e;
826
827         fd = open("/dev/btrfs-control", O_RDONLY);
828         if (fd < 0) {
829                 fprintf(stderr, "failed to open /dev/btrfs-control "
830                         "skipping device registration\n");
831                 return;
832         }
833         strncpy(args.name, fname, BTRFS_PATH_NAME_MAX);
834         ret = ioctl(fd, BTRFS_IOC_SCAN_DEV, &args);
835         e = errno;
836         if(ret<0){
837                 fprintf(stderr, "ERROR: unable to scan the device '%s' - %s\n",
838                         fname, strerror(e));
839         }
840         close(fd);
841 }
842
843 int btrfs_scan_one_dir(char *dirname, int run_ioctl)
844 {
845         DIR *dirp = NULL;
846         struct dirent *dirent;
847         struct pending_dir *pending;
848         struct stat st;
849         int ret;
850         int fd;
851         int dirname_len;
852         int pathlen;
853         char *fullpath;
854         struct list_head pending_list;
855         struct btrfs_fs_devices *tmp_devices;
856         u64 num_devices;
857
858         INIT_LIST_HEAD(&pending_list);
859
860         pending = malloc(sizeof(*pending));
861         if (!pending)
862                 return -ENOMEM;
863         strcpy(pending->name, dirname);
864
865 again:
866         dirname_len = strlen(pending->name);
867         pathlen = 1024;
868         fullpath = malloc(pathlen);
869         dirname = pending->name;
870
871         if (!fullpath) {
872                 ret = -ENOMEM;
873                 goto fail;
874         }
875         dirp = opendir(dirname);
876         if (!dirp) {
877                 fprintf(stderr, "Unable to open %s for scanning\n", dirname);
878                 return -ENOENT;
879         }
880         while(1) {
881                 dirent = readdir(dirp);
882                 if (!dirent)
883                         break;
884                 if (dirent->d_name[0] == '.')
885                         continue;
886                 if (dirname_len + strlen(dirent->d_name) + 2 > pathlen) {
887                         ret = -EFAULT;
888                         goto fail;
889                 }
890                 snprintf(fullpath, pathlen, "%s/%s", dirname, dirent->d_name);
891                 ret = lstat(fullpath, &st);
892                 if (ret < 0) {
893                         fprintf(stderr, "failed to stat %s\n", fullpath);
894                         continue;
895                 }
896                 if (S_ISLNK(st.st_mode))
897                         continue;
898                 if (S_ISDIR(st.st_mode)) {
899                         struct pending_dir *next = malloc(sizeof(*next));
900                         if (!next) {
901                                 ret = -ENOMEM;
902                                 goto fail;
903                         }
904                         strcpy(next->name, fullpath);
905                         list_add_tail(&next->list, &pending_list);
906                 }
907                 if (!S_ISBLK(st.st_mode)) {
908                         continue;
909                 }
910                 fd = open(fullpath, O_RDONLY);
911                 if (fd < 0) {
912                         fprintf(stderr, "failed to read %s: %s\n", fullpath,
913                                         strerror(errno));
914                         continue;
915                 }
916                 ret = btrfs_scan_one_device(fd, fullpath, &tmp_devices,
917                                             &num_devices,
918                                             BTRFS_SUPER_INFO_OFFSET);
919                 if (ret == 0 && run_ioctl > 0) {
920                         btrfs_register_one_device(fullpath);
921                 }
922                 close(fd);
923         }
924         if (!list_empty(&pending_list)) {
925                 free(pending);
926                 pending = list_entry(pending_list.next, struct pending_dir,
927                                      list);
928                 list_del(&pending->list);
929                 closedir(dirp);
930                 goto again;
931         }
932         ret = 0;
933 fail:
934         free(pending);
935         if (dirp)
936                 closedir(dirp);
937         return ret;
938 }
939
940 int btrfs_scan_for_fsid(struct btrfs_fs_devices *fs_devices, u64 total_devs,
941                         int run_ioctls)
942 {
943         return btrfs_scan_one_dir("/dev", run_ioctls);
944 }
945
946 int btrfs_device_already_in_root(struct btrfs_root *root, int fd,
947                                  int super_offset)
948 {
949         struct btrfs_super_block *disk_super;
950         char *buf;
951         int ret = 0;
952
953         buf = malloc(BTRFS_SUPER_INFO_SIZE);
954         if (!buf) {
955                 ret = -ENOMEM;
956                 goto out;
957         }
958         ret = pread(fd, buf, BTRFS_SUPER_INFO_SIZE, super_offset);
959         if (ret != BTRFS_SUPER_INFO_SIZE)
960                 goto brelse;
961
962         ret = 0;
963         disk_super = (struct btrfs_super_block *)buf;
964         if (strncmp((char *)(&disk_super->magic), BTRFS_MAGIC,
965             sizeof(disk_super->magic)))
966                 goto brelse;
967
968         if (!memcmp(disk_super->fsid, root->fs_info->super_copy.fsid,
969                     BTRFS_FSID_SIZE))
970                 ret = 1;
971 brelse:
972         free(buf);
973 out:
974         return ret;
975 }
976
977 static char *size_strs[] = { "", "KB", "MB", "GB", "TB",
978                             "PB", "EB", "ZB", "YB"};
979 char *pretty_sizes(u64 size)
980 {
981         int num_divs = 0;
982         int pretty_len = 16;
983         u64 last_size = size;
984         u64 fract_size = size;
985         float fraction;
986         char *pretty;
987
988         while(size > 0) {
989                 fract_size = last_size;
990                 last_size = size;
991                 size /= 1024;
992                 num_divs++;
993         }
994         if (num_divs == 0)
995                 num_divs = 1;
996         if (num_divs > ARRAY_SIZE(size_strs))
997                 return NULL;
998
999         fraction = (float)fract_size / 1024;
1000         pretty = malloc(pretty_len);
1001         snprintf(pretty, pretty_len, "%.2f%s", fraction, size_strs[num_divs-1]);
1002         return pretty;
1003 }
1004