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