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