btrfs-progs: Replace the overkill assert with normal error message.
[platform/upstream/btrfs-progs.git] / utils.c
1 /*
2  * Copyright (C) 2007 Oracle.  All rights reserved.
3  * Copyright (C) 2008 Morey Roof.  All rights reserved.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public
7  * License v2 as published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public
15  * License along with this program; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 021110-1307, USA.
18  */
19
20 #define _XOPEN_SOURCE 700
21 #define __USE_XOPEN2K8
22 #define __XOPEN2K8 /* due to an error in dirent.h, to get dirfd() */
23 #define _GNU_SOURCE     /* O_NOATIME */
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <sys/ioctl.h>
28 #include <sys/mount.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <uuid/uuid.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 <blkid/blkid.h>
41 #include "kerncompat.h"
42 #include "radix-tree.h"
43 #include "ctree.h"
44 #include "disk-io.h"
45 #include "transaction.h"
46 #include "crc32c.h"
47 #include "utils.h"
48 #include "volumes.h"
49 #include "ioctl.h"
50
51 #ifndef BLKDISCARD
52 #define BLKDISCARD      _IO(0x12,119)
53 #endif
54
55 /*
56  * Discard the given range in one go
57  */
58 static int discard_range(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 /*
68  * Discard blocks in the given range in 1G chunks, the process is interruptible
69  */
70 static int discard_blocks(int fd, u64 start, u64 len)
71 {
72         while (len > 0) {
73                 /* 1G granularity */
74                 u64 chunk_size = min_t(u64, len, 1*1024*1024*1024);
75                 int ret;
76
77                 ret = discard_range(fd, start, chunk_size);
78                 if (ret)
79                         return ret;
80                 len -= chunk_size;
81                 start += chunk_size;
82         }
83
84         return 0;
85 }
86
87 static u64 reference_root_table[] = {
88         [1] =   BTRFS_ROOT_TREE_OBJECTID,
89         [2] =   BTRFS_EXTENT_TREE_OBJECTID,
90         [3] =   BTRFS_CHUNK_TREE_OBJECTID,
91         [4] =   BTRFS_DEV_TREE_OBJECTID,
92         [5] =   BTRFS_FS_TREE_OBJECTID,
93         [6] =   BTRFS_CSUM_TREE_OBJECTID,
94 };
95
96 int make_btrfs(int fd, const char *device, const char *label,
97                u64 blocks[7], u64 num_bytes, u32 nodesize,
98                u32 leafsize, u32 sectorsize, u32 stripesize, u64 features)
99 {
100         struct btrfs_super_block super;
101         struct extent_buffer *buf;
102         struct btrfs_root_item root_item;
103         struct btrfs_disk_key disk_key;
104         struct btrfs_extent_item *extent_item;
105         struct btrfs_inode_item *inode_item;
106         struct btrfs_chunk *chunk;
107         struct btrfs_dev_item *dev_item;
108         struct btrfs_dev_extent *dev_extent;
109         u8 chunk_tree_uuid[BTRFS_UUID_SIZE];
110         u8 *ptr;
111         int i;
112         int ret;
113         u32 itemoff;
114         u32 nritems = 0;
115         u64 first_free;
116         u64 ref_root;
117         u32 array_size;
118         u32 item_size;
119         int skinny_metadata = !!(features &
120                                  BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA);
121
122         first_free = BTRFS_SUPER_INFO_OFFSET + sectorsize * 2 - 1;
123         first_free &= ~((u64)sectorsize - 1);
124
125         memset(&super, 0, sizeof(super));
126
127         num_bytes = (num_bytes / sectorsize) * sectorsize;
128         uuid_generate(super.fsid);
129         uuid_generate(super.dev_item.uuid);
130         uuid_generate(chunk_tree_uuid);
131
132         btrfs_set_super_bytenr(&super, blocks[0]);
133         btrfs_set_super_num_devices(&super, 1);
134         btrfs_set_super_magic(&super, BTRFS_MAGIC);
135         btrfs_set_super_generation(&super, 1);
136         btrfs_set_super_root(&super, blocks[1]);
137         btrfs_set_super_chunk_root(&super, blocks[3]);
138         btrfs_set_super_total_bytes(&super, num_bytes);
139         btrfs_set_super_bytes_used(&super, 6 * leafsize);
140         btrfs_set_super_sectorsize(&super, sectorsize);
141         btrfs_set_super_leafsize(&super, leafsize);
142         btrfs_set_super_nodesize(&super, nodesize);
143         btrfs_set_super_stripesize(&super, stripesize);
144         btrfs_set_super_csum_type(&super, BTRFS_CSUM_TYPE_CRC32);
145         btrfs_set_super_chunk_root_generation(&super, 1);
146         btrfs_set_super_cache_generation(&super, -1);
147         btrfs_set_super_incompat_flags(&super, features);
148         if (label)
149                 strncpy(super.label, label, BTRFS_LABEL_SIZE - 1);
150
151         buf = malloc(sizeof(*buf) + max(sectorsize, leafsize));
152
153         /* create the tree of root objects */
154         memset(buf->data, 0, leafsize);
155         buf->len = leafsize;
156         btrfs_set_header_bytenr(buf, blocks[1]);
157         btrfs_set_header_nritems(buf, 4);
158         btrfs_set_header_generation(buf, 1);
159         btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
160         btrfs_set_header_owner(buf, BTRFS_ROOT_TREE_OBJECTID);
161         write_extent_buffer(buf, super.fsid, btrfs_header_fsid(),
162                             BTRFS_FSID_SIZE);
163
164         write_extent_buffer(buf, chunk_tree_uuid,
165                             btrfs_header_chunk_tree_uuid(buf),
166                             BTRFS_UUID_SIZE);
167
168         /* create the items for the root tree */
169         memset(&root_item, 0, sizeof(root_item));
170         inode_item = &root_item.inode;
171         btrfs_set_stack_inode_generation(inode_item, 1);
172         btrfs_set_stack_inode_size(inode_item, 3);
173         btrfs_set_stack_inode_nlink(inode_item, 1);
174         btrfs_set_stack_inode_nbytes(inode_item, leafsize);
175         btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
176         btrfs_set_root_refs(&root_item, 1);
177         btrfs_set_root_used(&root_item, leafsize);
178         btrfs_set_root_generation(&root_item, 1);
179
180         memset(&disk_key, 0, sizeof(disk_key));
181         btrfs_set_disk_key_type(&disk_key, BTRFS_ROOT_ITEM_KEY);
182         btrfs_set_disk_key_offset(&disk_key, 0);
183         nritems = 0;
184
185         itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize) - sizeof(root_item);
186         btrfs_set_root_bytenr(&root_item, blocks[2]);
187         btrfs_set_disk_key_objectid(&disk_key, BTRFS_EXTENT_TREE_OBJECTID);
188         btrfs_set_item_key(buf, &disk_key, nritems);
189         btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
190         btrfs_set_item_size(buf, btrfs_item_nr(nritems),
191                             sizeof(root_item));
192         write_extent_buffer(buf, &root_item, btrfs_item_ptr_offset(buf,
193                             nritems), sizeof(root_item));
194         nritems++;
195
196         itemoff = itemoff - sizeof(root_item);
197         btrfs_set_root_bytenr(&root_item, blocks[4]);
198         btrfs_set_disk_key_objectid(&disk_key, BTRFS_DEV_TREE_OBJECTID);
199         btrfs_set_item_key(buf, &disk_key, nritems);
200         btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
201         btrfs_set_item_size(buf, btrfs_item_nr(nritems),
202                             sizeof(root_item));
203         write_extent_buffer(buf, &root_item,
204                             btrfs_item_ptr_offset(buf, nritems),
205                             sizeof(root_item));
206         nritems++;
207
208         itemoff = itemoff - sizeof(root_item);
209         btrfs_set_root_bytenr(&root_item, blocks[5]);
210         btrfs_set_disk_key_objectid(&disk_key, BTRFS_FS_TREE_OBJECTID);
211         btrfs_set_item_key(buf, &disk_key, nritems);
212         btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
213         btrfs_set_item_size(buf, btrfs_item_nr(nritems),
214                             sizeof(root_item));
215         write_extent_buffer(buf, &root_item,
216                             btrfs_item_ptr_offset(buf, nritems),
217                             sizeof(root_item));
218         nritems++;
219
220         itemoff = itemoff - sizeof(root_item);
221         btrfs_set_root_bytenr(&root_item, blocks[6]);
222         btrfs_set_disk_key_objectid(&disk_key, BTRFS_CSUM_TREE_OBJECTID);
223         btrfs_set_item_key(buf, &disk_key, nritems);
224         btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
225         btrfs_set_item_size(buf, btrfs_item_nr(nritems),
226                             sizeof(root_item));
227         write_extent_buffer(buf, &root_item,
228                             btrfs_item_ptr_offset(buf, nritems),
229                             sizeof(root_item));
230         nritems++;
231
232
233         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
234         ret = pwrite(fd, buf->data, leafsize, blocks[1]);
235         if (ret != leafsize) {
236                 ret = (ret < 0 ? -errno : -EIO);
237                 goto out;
238         }
239
240         /* create the items for the extent tree */
241         memset(buf->data+sizeof(struct btrfs_header), 0,
242                 leafsize-sizeof(struct btrfs_header));
243         nritems = 0;
244         itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize);
245         for (i = 1; i < 7; i++) {
246                 item_size = sizeof(struct btrfs_extent_item);
247                 if (!skinny_metadata)
248                         item_size += sizeof(struct btrfs_tree_block_info);
249
250                 BUG_ON(blocks[i] < first_free);
251                 BUG_ON(blocks[i] < blocks[i - 1]);
252
253                 /* create extent item */
254                 itemoff -= item_size;
255                 btrfs_set_disk_key_objectid(&disk_key, blocks[i]);
256                 if (skinny_metadata) {
257                         btrfs_set_disk_key_type(&disk_key,
258                                                 BTRFS_METADATA_ITEM_KEY);
259                         btrfs_set_disk_key_offset(&disk_key, 0);
260                 } else {
261                         btrfs_set_disk_key_type(&disk_key,
262                                                 BTRFS_EXTENT_ITEM_KEY);
263                         btrfs_set_disk_key_offset(&disk_key, leafsize);
264                 }
265                 btrfs_set_item_key(buf, &disk_key, nritems);
266                 btrfs_set_item_offset(buf, btrfs_item_nr(nritems),
267                                       itemoff);
268                 btrfs_set_item_size(buf, btrfs_item_nr(nritems),
269                                     item_size);
270                 extent_item = btrfs_item_ptr(buf, nritems,
271                                              struct btrfs_extent_item);
272                 btrfs_set_extent_refs(buf, extent_item, 1);
273                 btrfs_set_extent_generation(buf, extent_item, 1);
274                 btrfs_set_extent_flags(buf, extent_item,
275                                        BTRFS_EXTENT_FLAG_TREE_BLOCK);
276                 nritems++;
277
278                 /* create extent ref */
279                 ref_root = reference_root_table[i];
280                 btrfs_set_disk_key_objectid(&disk_key, blocks[i]);
281                 btrfs_set_disk_key_offset(&disk_key, ref_root);
282                 btrfs_set_disk_key_type(&disk_key, BTRFS_TREE_BLOCK_REF_KEY);
283                 btrfs_set_item_key(buf, &disk_key, nritems);
284                 btrfs_set_item_offset(buf, btrfs_item_nr(nritems),
285                                       itemoff);
286                 btrfs_set_item_size(buf, btrfs_item_nr(nritems), 0);
287                 nritems++;
288         }
289         btrfs_set_header_bytenr(buf, blocks[2]);
290         btrfs_set_header_owner(buf, BTRFS_EXTENT_TREE_OBJECTID);
291         btrfs_set_header_nritems(buf, nritems);
292         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
293         ret = pwrite(fd, buf->data, leafsize, blocks[2]);
294         if (ret != leafsize) {
295                 ret = (ret < 0 ? -errno : -EIO);
296                 goto out;
297         }
298
299         /* create the chunk tree */
300         memset(buf->data+sizeof(struct btrfs_header), 0,
301                 leafsize-sizeof(struct btrfs_header));
302         nritems = 0;
303         item_size = sizeof(*dev_item);
304         itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize) - item_size;
305
306         /* first device 1 (there is no device 0) */
307         btrfs_set_disk_key_objectid(&disk_key, BTRFS_DEV_ITEMS_OBJECTID);
308         btrfs_set_disk_key_offset(&disk_key, 1);
309         btrfs_set_disk_key_type(&disk_key, BTRFS_DEV_ITEM_KEY);
310         btrfs_set_item_key(buf, &disk_key, nritems);
311         btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
312         btrfs_set_item_size(buf, btrfs_item_nr(nritems), item_size);
313
314         dev_item = btrfs_item_ptr(buf, nritems, struct btrfs_dev_item);
315         btrfs_set_device_id(buf, dev_item, 1);
316         btrfs_set_device_generation(buf, dev_item, 0);
317         btrfs_set_device_total_bytes(buf, dev_item, num_bytes);
318         btrfs_set_device_bytes_used(buf, dev_item,
319                                     BTRFS_MKFS_SYSTEM_GROUP_SIZE);
320         btrfs_set_device_io_align(buf, dev_item, sectorsize);
321         btrfs_set_device_io_width(buf, dev_item, sectorsize);
322         btrfs_set_device_sector_size(buf, dev_item, sectorsize);
323         btrfs_set_device_type(buf, dev_item, 0);
324
325         write_extent_buffer(buf, super.dev_item.uuid,
326                             (unsigned long)btrfs_device_uuid(dev_item),
327                             BTRFS_UUID_SIZE);
328         write_extent_buffer(buf, super.fsid,
329                             (unsigned long)btrfs_device_fsid(dev_item),
330                             BTRFS_UUID_SIZE);
331         read_extent_buffer(buf, &super.dev_item, (unsigned long)dev_item,
332                            sizeof(*dev_item));
333
334         nritems++;
335         item_size = btrfs_chunk_item_size(1);
336         itemoff = itemoff - item_size;
337
338         /* then we have chunk 0 */
339         btrfs_set_disk_key_objectid(&disk_key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
340         btrfs_set_disk_key_offset(&disk_key, 0);
341         btrfs_set_disk_key_type(&disk_key, BTRFS_CHUNK_ITEM_KEY);
342         btrfs_set_item_key(buf, &disk_key, nritems);
343         btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
344         btrfs_set_item_size(buf, btrfs_item_nr(nritems), item_size);
345
346         chunk = btrfs_item_ptr(buf, nritems, struct btrfs_chunk);
347         btrfs_set_chunk_length(buf, chunk, BTRFS_MKFS_SYSTEM_GROUP_SIZE);
348         btrfs_set_chunk_owner(buf, chunk, BTRFS_EXTENT_TREE_OBJECTID);
349         btrfs_set_chunk_stripe_len(buf, chunk, 64 * 1024);
350         btrfs_set_chunk_type(buf, chunk, BTRFS_BLOCK_GROUP_SYSTEM);
351         btrfs_set_chunk_io_align(buf, chunk, sectorsize);
352         btrfs_set_chunk_io_width(buf, chunk, sectorsize);
353         btrfs_set_chunk_sector_size(buf, chunk, sectorsize);
354         btrfs_set_chunk_num_stripes(buf, chunk, 1);
355         btrfs_set_stripe_devid_nr(buf, chunk, 0, 1);
356         btrfs_set_stripe_offset_nr(buf, chunk, 0, 0);
357         nritems++;
358
359         write_extent_buffer(buf, super.dev_item.uuid,
360                             (unsigned long)btrfs_stripe_dev_uuid(&chunk->stripe),
361                             BTRFS_UUID_SIZE);
362
363         /* copy the key for the chunk to the system array */
364         ptr = super.sys_chunk_array;
365         array_size = sizeof(disk_key);
366
367         memcpy(ptr, &disk_key, sizeof(disk_key));
368         ptr += sizeof(disk_key);
369
370         /* copy the chunk to the system array */
371         read_extent_buffer(buf, ptr, (unsigned long)chunk, item_size);
372         array_size += item_size;
373         ptr += item_size;
374         btrfs_set_super_sys_array_size(&super, array_size);
375
376         btrfs_set_header_bytenr(buf, blocks[3]);
377         btrfs_set_header_owner(buf, BTRFS_CHUNK_TREE_OBJECTID);
378         btrfs_set_header_nritems(buf, nritems);
379         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
380         ret = pwrite(fd, buf->data, leafsize, blocks[3]);
381         if (ret != leafsize) {
382                 ret = (ret < 0 ? -errno : -EIO);
383                 goto out;
384         }
385
386         /* create the device tree */
387         memset(buf->data+sizeof(struct btrfs_header), 0,
388                 leafsize-sizeof(struct btrfs_header));
389         nritems = 0;
390         itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize) -
391                 sizeof(struct btrfs_dev_extent);
392
393         btrfs_set_disk_key_objectid(&disk_key, 1);
394         btrfs_set_disk_key_offset(&disk_key, 0);
395         btrfs_set_disk_key_type(&disk_key, BTRFS_DEV_EXTENT_KEY);
396         btrfs_set_item_key(buf, &disk_key, nritems);
397         btrfs_set_item_offset(buf, btrfs_item_nr(nritems), itemoff);
398         btrfs_set_item_size(buf, btrfs_item_nr(nritems),
399                             sizeof(struct btrfs_dev_extent));
400         dev_extent = btrfs_item_ptr(buf, nritems, struct btrfs_dev_extent);
401         btrfs_set_dev_extent_chunk_tree(buf, dev_extent,
402                                         BTRFS_CHUNK_TREE_OBJECTID);
403         btrfs_set_dev_extent_chunk_objectid(buf, dev_extent,
404                                         BTRFS_FIRST_CHUNK_TREE_OBJECTID);
405         btrfs_set_dev_extent_chunk_offset(buf, dev_extent, 0);
406
407         write_extent_buffer(buf, chunk_tree_uuid,
408                     (unsigned long)btrfs_dev_extent_chunk_tree_uuid(dev_extent),
409                     BTRFS_UUID_SIZE);
410
411         btrfs_set_dev_extent_length(buf, dev_extent,
412                                     BTRFS_MKFS_SYSTEM_GROUP_SIZE);
413         nritems++;
414
415         btrfs_set_header_bytenr(buf, blocks[4]);
416         btrfs_set_header_owner(buf, BTRFS_DEV_TREE_OBJECTID);
417         btrfs_set_header_nritems(buf, nritems);
418         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
419         ret = pwrite(fd, buf->data, leafsize, blocks[4]);
420         if (ret != leafsize) {
421                 ret = (ret < 0 ? -errno : -EIO);
422                 goto out;
423         }
424
425         /* create the FS root */
426         memset(buf->data+sizeof(struct btrfs_header), 0,
427                 leafsize-sizeof(struct btrfs_header));
428         btrfs_set_header_bytenr(buf, blocks[5]);
429         btrfs_set_header_owner(buf, BTRFS_FS_TREE_OBJECTID);
430         btrfs_set_header_nritems(buf, 0);
431         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
432         ret = pwrite(fd, buf->data, leafsize, blocks[5]);
433         if (ret != leafsize) {
434                 ret = (ret < 0 ? -errno : -EIO);
435                 goto out;
436         }
437         /* finally create the csum root */
438         memset(buf->data+sizeof(struct btrfs_header), 0,
439                 leafsize-sizeof(struct btrfs_header));
440         btrfs_set_header_bytenr(buf, blocks[6]);
441         btrfs_set_header_owner(buf, BTRFS_CSUM_TREE_OBJECTID);
442         btrfs_set_header_nritems(buf, 0);
443         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
444         ret = pwrite(fd, buf->data, leafsize, blocks[6]);
445         if (ret != leafsize) {
446                 ret = (ret < 0 ? -errno : -EIO);
447                 goto out;
448         }
449
450         /* and write out the super block */
451         BUG_ON(sizeof(super) > sectorsize);
452         memset(buf->data, 0, sectorsize);
453         memcpy(buf->data, &super, sizeof(super));
454         buf->len = sectorsize;
455         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
456         ret = pwrite(fd, buf->data, sectorsize, blocks[0]);
457         if (ret != sectorsize) {
458                 ret = (ret < 0 ? -errno : -EIO);
459                 goto out;
460         }
461
462         ret = 0;
463
464 out:
465         free(buf);
466         return ret;
467 }
468
469 u64 btrfs_device_size(int fd, struct stat *st)
470 {
471         u64 size;
472         if (S_ISREG(st->st_mode)) {
473                 return st->st_size;
474         }
475         if (!S_ISBLK(st->st_mode)) {
476                 return 0;
477         }
478         if (ioctl(fd, BLKGETSIZE64, &size) >= 0) {
479                 return size;
480         }
481         return 0;
482 }
483
484 static int zero_blocks(int fd, off_t start, size_t len)
485 {
486         char *buf = malloc(len);
487         int ret = 0;
488         ssize_t written;
489
490         if (!buf)
491                 return -ENOMEM;
492         memset(buf, 0, len);
493         written = pwrite(fd, buf, len, start);
494         if (written != len)
495                 ret = -EIO;
496         free(buf);
497         return ret;
498 }
499
500 static int zero_dev_start(int fd)
501 {
502         off_t start = 0;
503         size_t len = 2 * 1024 * 1024;
504
505 #ifdef __sparc__
506         /* don't overwrite the disk labels on sparc */
507         start = 1024;
508         len -= 1024;
509 #endif
510         return zero_blocks(fd, start, len);
511 }
512
513 static int zero_dev_end(int fd, u64 dev_size)
514 {
515         size_t len = 2 * 1024 * 1024;
516         off_t start = dev_size - len;
517
518         return zero_blocks(fd, start, len);
519 }
520
521 int btrfs_add_to_fsid(struct btrfs_trans_handle *trans,
522                       struct btrfs_root *root, int fd, char *path,
523                       u64 block_count, u32 io_width, u32 io_align,
524                       u32 sectorsize)
525 {
526         struct btrfs_super_block *disk_super;
527         struct btrfs_super_block *super = root->fs_info->super_copy;
528         struct btrfs_device *device;
529         struct btrfs_dev_item *dev_item;
530         char *buf;
531         u64 total_bytes;
532         u64 num_devs;
533         int ret;
534
535         device = kzalloc(sizeof(*device), GFP_NOFS);
536         if (!device)
537                 return -ENOMEM;
538         buf = kmalloc(sectorsize, GFP_NOFS);
539         if (!buf) {
540                 kfree(device);
541                 return -ENOMEM;
542         }
543         BUG_ON(sizeof(*disk_super) > sectorsize);
544         memset(buf, 0, sectorsize);
545
546         disk_super = (struct btrfs_super_block *)buf;
547         dev_item = &disk_super->dev_item;
548
549         uuid_generate(device->uuid);
550         device->devid = 0;
551         device->type = 0;
552         device->io_width = io_width;
553         device->io_align = io_align;
554         device->sector_size = sectorsize;
555         device->fd = fd;
556         device->writeable = 1;
557         device->total_bytes = block_count;
558         device->bytes_used = 0;
559         device->total_ios = 0;
560         device->dev_root = root->fs_info->dev_root;
561
562         ret = btrfs_add_device(trans, root, device);
563         BUG_ON(ret);
564
565         total_bytes = btrfs_super_total_bytes(super) + block_count;
566         btrfs_set_super_total_bytes(super, total_bytes);
567
568         num_devs = btrfs_super_num_devices(super) + 1;
569         btrfs_set_super_num_devices(super, num_devs);
570
571         memcpy(disk_super, super, sizeof(*disk_super));
572
573         printf("adding device %s id %llu\n", path,
574                (unsigned long long)device->devid);
575
576         btrfs_set_super_bytenr(disk_super, BTRFS_SUPER_INFO_OFFSET);
577         btrfs_set_stack_device_id(dev_item, device->devid);
578         btrfs_set_stack_device_type(dev_item, device->type);
579         btrfs_set_stack_device_io_align(dev_item, device->io_align);
580         btrfs_set_stack_device_io_width(dev_item, device->io_width);
581         btrfs_set_stack_device_sector_size(dev_item, device->sector_size);
582         btrfs_set_stack_device_total_bytes(dev_item, device->total_bytes);
583         btrfs_set_stack_device_bytes_used(dev_item, device->bytes_used);
584         memcpy(&dev_item->uuid, device->uuid, BTRFS_UUID_SIZE);
585
586         ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
587         BUG_ON(ret != sectorsize);
588
589         kfree(buf);
590         list_add(&device->dev_list, &root->fs_info->fs_devices->devices);
591         device->fs_devices = root->fs_info->fs_devices;
592         return 0;
593 }
594
595 int btrfs_prepare_device(int fd, char *file, int zero_end, u64 *block_count_ret,
596                            u64 max_block_count, int *mixed, int discard)
597 {
598         u64 block_count;
599         u64 bytenr;
600         struct stat st;
601         int i, ret;
602
603         ret = fstat(fd, &st);
604         if (ret < 0) {
605                 fprintf(stderr, "unable to stat %s\n", file);
606                 return 1;
607         }
608
609         block_count = btrfs_device_size(fd, &st);
610         if (block_count == 0) {
611                 fprintf(stderr, "unable to find %s size\n", file);
612                 return 1;
613         }
614         if (max_block_count)
615                 block_count = min(block_count, max_block_count);
616
617         if (block_count < 1024 * 1024 * 1024 && !(*mixed)) {
618                 printf("SMALL VOLUME: forcing mixed metadata/data groups\n");
619                 *mixed = 1;
620         }
621
622         if (discard) {
623                 /*
624                  * We intentionally ignore errors from the discard ioctl.  It
625                  * is not necessary for the mkfs functionality but just an
626                  * optimization.
627                  */
628                 if (discard_range(fd, 0, 0) == 0) {
629                         fprintf(stderr, "Performing full device TRIM (%s) ...\n",
630                                 pretty_size(block_count));
631                         discard_blocks(fd, 0, block_count);
632                 }
633         }
634
635         ret = zero_dev_start(fd);
636         if (ret)
637                 goto zero_dev_error;
638
639         for (i = 0 ; i < BTRFS_SUPER_MIRROR_MAX; i++) {
640                 bytenr = btrfs_sb_offset(i);
641                 if (bytenr >= block_count)
642                         break;
643                 ret = zero_blocks(fd, bytenr, BTRFS_SUPER_INFO_SIZE);
644                 if (ret)
645                         goto zero_dev_error;
646         }
647
648         if (zero_end) {
649                 ret = zero_dev_end(fd, block_count);
650                 if (ret)
651                         goto zero_dev_error;
652         }
653         *block_count_ret = block_count;
654
655 zero_dev_error:
656         if (ret < 0) {
657                 fprintf(stderr, "ERROR: failed to zero device '%s' - %s\n",
658                         file, strerror(-ret));
659                 return 1;
660         } else if (ret > 0) {
661                 fprintf(stderr, "ERROR: failed to zero device '%s' - %d\n",
662                         file, ret);
663                 return 1;
664         }
665         return 0;
666 }
667
668 int btrfs_make_root_dir(struct btrfs_trans_handle *trans,
669                         struct btrfs_root *root, u64 objectid)
670 {
671         int ret;
672         struct btrfs_inode_item inode_item;
673         time_t now = time(NULL);
674
675         memset(&inode_item, 0, sizeof(inode_item));
676         btrfs_set_stack_inode_generation(&inode_item, trans->transid);
677         btrfs_set_stack_inode_size(&inode_item, 0);
678         btrfs_set_stack_inode_nlink(&inode_item, 1);
679         btrfs_set_stack_inode_nbytes(&inode_item, root->leafsize);
680         btrfs_set_stack_inode_mode(&inode_item, S_IFDIR | 0755);
681         btrfs_set_stack_timespec_sec(&inode_item.atime, now);
682         btrfs_set_stack_timespec_nsec(&inode_item.atime, 0);
683         btrfs_set_stack_timespec_sec(&inode_item.ctime, now);
684         btrfs_set_stack_timespec_nsec(&inode_item.ctime, 0);
685         btrfs_set_stack_timespec_sec(&inode_item.mtime, now);
686         btrfs_set_stack_timespec_nsec(&inode_item.mtime, 0);
687         btrfs_set_stack_timespec_sec(&inode_item.otime, 0);
688         btrfs_set_stack_timespec_nsec(&inode_item.otime, 0);
689
690         if (root->fs_info->tree_root == root)
691                 btrfs_set_super_root_dir(root->fs_info->super_copy, objectid);
692
693         ret = btrfs_insert_inode(trans, root, objectid, &inode_item);
694         if (ret)
695                 goto error;
696
697         ret = btrfs_insert_inode_ref(trans, root, "..", 2, objectid, objectid, 0);
698         if (ret)
699                 goto error;
700
701         btrfs_set_root_dirid(&root->root_item, objectid);
702         ret = 0;
703 error:
704         return ret;
705 }
706
707 /*
708  * checks if a path is a block device node
709  * Returns negative errno on failure, otherwise
710  * returns 1 for blockdev, 0 for not-blockdev
711  */
712 int is_block_device(const char *path)
713 {
714         struct stat statbuf;
715
716         if (stat(path, &statbuf) < 0)
717                 return -errno;
718
719         return S_ISBLK(statbuf.st_mode);
720 }
721
722 /*
723  * check if given path is a mount point
724  * return 1 if yes. 0 if no. -1 for error
725  */
726 int is_mount_point(const char *path)
727 {
728         FILE *f;
729         struct mntent *mnt;
730         int ret = 0;
731
732         f = setmntent("/proc/self/mounts", "r");
733         if (f == NULL)
734                 return -1;
735
736         while ((mnt = getmntent(f)) != NULL) {
737                 if (strcmp(mnt->mnt_dir, path))
738                         continue;
739                 ret = 1;
740                 break;
741         }
742         endmntent(f);
743         return ret;
744 }
745
746 /*
747  * Find the mount point for a mounted device.
748  * On success, returns 0 with mountpoint in *mp.
749  * On failure, returns -errno (not mounted yields -EINVAL)
750  * Is noisy on failures, expects to be given a mounted device.
751  */
752 int get_btrfs_mount(const char *dev, char *mp, size_t mp_size)
753 {
754         int ret;
755         int fd = -1;
756
757         ret = is_block_device(dev);
758         if (ret <= 0) {
759                 if (!ret) {
760                         fprintf(stderr, "%s is not a block device\n", dev);
761                         ret = -EINVAL;
762                 } else {
763                         fprintf(stderr, "Could not check %s: %s\n",
764                                 dev, strerror(-ret));
765                 }
766                 goto out;
767         }
768
769         fd = open(dev, O_RDONLY);
770         if (fd < 0) {
771                 ret = -errno;
772                 fprintf(stderr, "Could not open %s: %s\n", dev, strerror(errno));
773                 goto out;
774         }
775
776         ret = check_mounted_where(fd, dev, mp, mp_size, NULL);
777         if (!ret) {
778                 ret = -EINVAL;
779         } else { /* mounted, all good */
780                 ret = 0;
781         }
782 out:
783         if (fd != -1)
784                 close(fd);
785         return ret;
786 }
787
788 /*
789  * Given a pathname, return a filehandle to:
790  *      the original pathname or,
791  *      if the pathname is a mounted btrfs device, to its mountpoint.
792  *
793  * On error, return -1, errno should be set.
794  */
795 int open_path_or_dev_mnt(const char *path, DIR **dirstream)
796 {
797         char mp[BTRFS_PATH_NAME_MAX + 1];
798         int fdmnt;
799
800         if (is_block_device(path)) {
801                 int ret;
802
803                 ret = get_btrfs_mount(path, mp, sizeof(mp));
804                 if (ret < 0) {
805                         /* not a mounted btrfs dev */
806                         errno = EINVAL;
807                         return -1;
808                 }
809                 fdmnt = open_file_or_dir(mp, dirstream);
810         } else {
811                 fdmnt = open_file_or_dir(path, dirstream);
812         }
813
814         return fdmnt;
815 }
816
817 /* checks if a device is a loop device */
818 static int is_loop_device (const char* device) {
819         struct stat statbuf;
820
821         if(stat(device, &statbuf) < 0)
822                 return -errno;
823
824         return (S_ISBLK(statbuf.st_mode) &&
825                 MAJOR(statbuf.st_rdev) == LOOP_MAJOR);
826 }
827
828
829 /* Takes a loop device path (e.g. /dev/loop0) and returns
830  * the associated file (e.g. /images/my_btrfs.img) */
831 static int resolve_loop_device(const char* loop_dev, char* loop_file,
832                 int max_len)
833 {
834         int ret;
835         FILE *f;
836         char fmt[20];
837         char p[PATH_MAX];
838         char real_loop_dev[PATH_MAX];
839
840         if (!realpath(loop_dev, real_loop_dev))
841                 return -errno;
842         snprintf(p, PATH_MAX, "/sys/block/%s/loop/backing_file", strrchr(real_loop_dev, '/'));
843         if (!(f = fopen(p, "r")))
844                 return -errno;
845
846         snprintf(fmt, 20, "%%%i[^\n]", max_len-1);
847         ret = fscanf(f, fmt, loop_file);
848         fclose(f);
849         if (ret == EOF)
850                 return -errno;
851
852         return 0;
853 }
854
855 /* Checks whether a and b are identical or device
856  * files associated with the same block device
857  */
858 static int is_same_blk_file(const char* a, const char* b)
859 {
860         struct stat st_buf_a, st_buf_b;
861         char real_a[PATH_MAX];
862         char real_b[PATH_MAX];
863
864         if(!realpath(a, real_a))
865                 strcpy(real_a, a);
866
867         if (!realpath(b, real_b))
868                 strcpy(real_b, b);
869
870         /* Identical path? */
871         if(strcmp(real_a, real_b) == 0)
872                 return 1;
873
874         if(stat(a, &st_buf_a) < 0 ||
875            stat(b, &st_buf_b) < 0)
876         {
877                 if (errno == ENOENT)
878                         return 0;
879                 return -errno;
880         }
881
882         /* Same blockdevice? */
883         if(S_ISBLK(st_buf_a.st_mode) &&
884            S_ISBLK(st_buf_b.st_mode) &&
885            st_buf_a.st_rdev == st_buf_b.st_rdev)
886         {
887                 return 1;
888         }
889
890         /* Hardlink? */
891         if (st_buf_a.st_dev == st_buf_b.st_dev &&
892             st_buf_a.st_ino == st_buf_b.st_ino)
893         {
894                 return 1;
895         }
896
897         return 0;
898 }
899
900 /* checks if a and b are identical or device
901  * files associated with the same block device or
902  * if one file is a loop device that uses the other
903  * file.
904  */
905 static int is_same_loop_file(const char* a, const char* b)
906 {
907         char res_a[PATH_MAX];
908         char res_b[PATH_MAX];
909         const char* final_a = NULL;
910         const char* final_b = NULL;
911         int ret;
912
913         /* Resolve a if it is a loop device */
914         if((ret = is_loop_device(a)) < 0) {
915                 if (ret == -ENOENT)
916                         return 0;
917                 return ret;
918         } else if (ret) {
919                 ret = resolve_loop_device(a, res_a, sizeof(res_a));
920                 if (ret < 0) {
921                         if (errno != EPERM)
922                                 return ret;
923                 } else {
924                         final_a = res_a;
925                 }
926         } else {
927                 final_a = a;
928         }
929
930         /* Resolve b if it is a loop device */
931         if ((ret = is_loop_device(b)) < 0) {
932                 if (ret == -ENOENT)
933                         return 0;
934                 return ret;
935         } else if (ret) {
936                 ret = resolve_loop_device(b, res_b, sizeof(res_b));
937                 if (ret < 0) {
938                         if (errno != EPERM)
939                                 return ret;
940                 } else {
941                         final_b = res_b;
942                 }
943         } else {
944                 final_b = b;
945         }
946
947         return is_same_blk_file(final_a, final_b);
948 }
949
950 /* Checks if a file exists and is a block or regular file*/
951 static int is_existing_blk_or_reg_file(const char* filename)
952 {
953         struct stat st_buf;
954
955         if(stat(filename, &st_buf) < 0) {
956                 if(errno == ENOENT)
957                         return 0;
958                 else
959                         return -errno;
960         }
961
962         return (S_ISBLK(st_buf.st_mode) || S_ISREG(st_buf.st_mode));
963 }
964
965 /* Checks if a file is used (directly or indirectly via a loop device)
966  * by a device in fs_devices
967  */
968 static int blk_file_in_dev_list(struct btrfs_fs_devices* fs_devices,
969                 const char* file)
970 {
971         int ret;
972         struct list_head *head;
973         struct list_head *cur;
974         struct btrfs_device *device;
975
976         head = &fs_devices->devices;
977         list_for_each(cur, head) {
978                 device = list_entry(cur, struct btrfs_device, dev_list);
979
980                 if((ret = is_same_loop_file(device->name, file)))
981                         return ret;
982         }
983
984         return 0;
985 }
986
987 /*
988  * returns 1 if the device was mounted, < 0 on error or 0 if everything
989  * is safe to continue.
990  */
991 int check_mounted(const char* file)
992 {
993         int fd;
994         int ret;
995
996         fd = open(file, O_RDONLY);
997         if (fd < 0) {
998                 fprintf (stderr, "check_mounted(): Could not open %s\n", file);
999                 return -errno;
1000         }
1001
1002         ret =  check_mounted_where(fd, file, NULL, 0, NULL);
1003         close(fd);
1004
1005         return ret;
1006 }
1007
1008 int check_mounted_where(int fd, const char *file, char *where, int size,
1009                         struct btrfs_fs_devices **fs_dev_ret)
1010 {
1011         int ret;
1012         u64 total_devs = 1;
1013         int is_btrfs;
1014         struct btrfs_fs_devices *fs_devices_mnt = NULL;
1015         FILE *f;
1016         struct mntent *mnt;
1017
1018         /* scan the initial device */
1019         ret = btrfs_scan_one_device(fd, file, &fs_devices_mnt,
1020                                     &total_devs, BTRFS_SUPER_INFO_OFFSET);
1021         is_btrfs = (ret >= 0);
1022
1023         /* scan other devices */
1024         if (is_btrfs && total_devs > 1) {
1025                 if ((ret = btrfs_scan_for_fsid(!BTRFS_UPDATE_KERNEL)))
1026                         return ret;
1027         }
1028
1029         /* iterate over the list of currently mountes filesystems */
1030         if ((f = setmntent ("/proc/self/mounts", "r")) == NULL)
1031                 return -errno;
1032
1033         while ((mnt = getmntent (f)) != NULL) {
1034                 if(is_btrfs) {
1035                         if(strcmp(mnt->mnt_type, "btrfs") != 0)
1036                                 continue;
1037
1038                         ret = blk_file_in_dev_list(fs_devices_mnt, mnt->mnt_fsname);
1039                 } else {
1040                         /* ignore entries in the mount table that are not
1041                            associated with a file*/
1042                         if((ret = is_existing_blk_or_reg_file(mnt->mnt_fsname)) < 0)
1043                                 goto out_mntloop_err;
1044                         else if(!ret)
1045                                 continue;
1046
1047                         ret = is_same_loop_file(file, mnt->mnt_fsname);
1048                 }
1049
1050                 if(ret < 0)
1051                         goto out_mntloop_err;
1052                 else if(ret)
1053                         break;
1054         }
1055
1056         /* Did we find an entry in mnt table? */
1057         if (mnt && size && where) {
1058                 strncpy(where, mnt->mnt_dir, size);
1059                 where[size-1] = 0;
1060         }
1061         if (fs_dev_ret)
1062                 *fs_dev_ret = fs_devices_mnt;
1063
1064         ret = (mnt != NULL);
1065
1066 out_mntloop_err:
1067         endmntent (f);
1068
1069         return ret;
1070 }
1071
1072 struct pending_dir {
1073         struct list_head list;
1074         char name[PATH_MAX];
1075 };
1076
1077 void btrfs_register_one_device(char *fname)
1078 {
1079         struct btrfs_ioctl_vol_args args;
1080         int fd;
1081         int ret;
1082         int e;
1083
1084         fd = open("/dev/btrfs-control", O_RDONLY);
1085         if (fd < 0) {
1086                 fprintf(stderr, "failed to open /dev/btrfs-control "
1087                         "skipping device registration: %s\n",
1088                         strerror(errno));
1089                 return;
1090         }
1091         strncpy(args.name, fname, BTRFS_PATH_NAME_MAX);
1092         args.name[BTRFS_PATH_NAME_MAX-1] = 0;
1093         ret = ioctl(fd, BTRFS_IOC_SCAN_DEV, &args);
1094         e = errno;
1095         if(ret<0){
1096                 fprintf(stderr, "ERROR: device scan failed '%s' - %s\n",
1097                         fname, strerror(e));
1098         }
1099         close(fd);
1100 }
1101
1102 int btrfs_scan_one_dir(char *dirname, int run_ioctl)
1103 {
1104         DIR *dirp = NULL;
1105         struct dirent *dirent;
1106         struct pending_dir *pending;
1107         struct stat st;
1108         int ret;
1109         int fd;
1110         int dirname_len;
1111         char *fullpath;
1112         struct list_head pending_list;
1113         struct btrfs_fs_devices *tmp_devices;
1114         u64 num_devices;
1115
1116         INIT_LIST_HEAD(&pending_list);
1117
1118         pending = malloc(sizeof(*pending));
1119         if (!pending)
1120                 return -ENOMEM;
1121         strcpy(pending->name, dirname);
1122
1123 again:
1124         dirname_len = strlen(pending->name);
1125         fullpath = malloc(PATH_MAX);
1126         dirname = pending->name;
1127
1128         if (!fullpath) {
1129                 ret = -ENOMEM;
1130                 goto fail;
1131         }
1132         dirp = opendir(dirname);
1133         if (!dirp) {
1134                 fprintf(stderr, "Unable to open %s for scanning\n", dirname);
1135                 ret = -errno;
1136                 goto fail;
1137         }
1138         while(1) {
1139                 dirent = readdir(dirp);
1140                 if (!dirent)
1141                         break;
1142                 if (dirent->d_name[0] == '.')
1143                         continue;
1144                 if (dirname_len + strlen(dirent->d_name) + 2 > PATH_MAX) {
1145                         ret = -EFAULT;
1146                         goto fail;
1147                 }
1148                 snprintf(fullpath, PATH_MAX, "%s/%s", dirname, dirent->d_name);
1149                 ret = lstat(fullpath, &st);
1150                 if (ret < 0) {
1151                         fprintf(stderr, "failed to stat %s\n", fullpath);
1152                         continue;
1153                 }
1154                 if (S_ISLNK(st.st_mode))
1155                         continue;
1156                 if (S_ISDIR(st.st_mode)) {
1157                         struct pending_dir *next = malloc(sizeof(*next));
1158                         if (!next) {
1159                                 ret = -ENOMEM;
1160                                 goto fail;
1161                         }
1162                         strcpy(next->name, fullpath);
1163                         list_add_tail(&next->list, &pending_list);
1164                 }
1165                 if (!S_ISBLK(st.st_mode)) {
1166                         continue;
1167                 }
1168                 fd = open(fullpath, O_RDONLY);
1169                 if (fd < 0) {
1170                         /* ignore the following errors:
1171                                 ENXIO (device don't exists) 
1172                                 ENOMEDIUM (No medium found -> 
1173                                         like a cd tray empty)
1174                         */
1175                         if(errno != ENXIO && errno != ENOMEDIUM) 
1176                                 fprintf(stderr, "failed to read %s: %s\n", 
1177                                         fullpath, strerror(errno));
1178                         continue;
1179                 }
1180                 ret = btrfs_scan_one_device(fd, fullpath, &tmp_devices,
1181                                             &num_devices,
1182                                             BTRFS_SUPER_INFO_OFFSET);
1183                 if (ret == 0 && run_ioctl > 0) {
1184                         btrfs_register_one_device(fullpath);
1185                 }
1186                 close(fd);
1187         }
1188         if (!list_empty(&pending_list)) {
1189                 free(pending);
1190                 pending = list_entry(pending_list.next, struct pending_dir,
1191                                      list);
1192                 free(fullpath);
1193                 list_del(&pending->list);
1194                 closedir(dirp);
1195                 dirp = NULL;
1196                 goto again;
1197         }
1198         ret = 0;
1199 fail:
1200         free(pending);
1201         free(fullpath);
1202         while (!list_empty(&pending_list)) {
1203                 pending = list_entry(pending_list.next, struct pending_dir,
1204                                      list);
1205                 list_del(&pending->list);
1206                 free(pending);
1207         }
1208         if (dirp)
1209                 closedir(dirp);
1210         return ret;
1211 }
1212
1213 int btrfs_scan_for_fsid(int run_ioctls)
1214 {
1215         int ret;
1216
1217         ret = scan_for_btrfs(BTRFS_SCAN_PROC, run_ioctls);
1218         if (ret)
1219                 ret = scan_for_btrfs(BTRFS_SCAN_DEV, run_ioctls);
1220         return ret;
1221 }
1222
1223 int btrfs_device_already_in_root(struct btrfs_root *root, int fd,
1224                                  int super_offset)
1225 {
1226         struct btrfs_super_block *disk_super;
1227         char *buf;
1228         int ret = 0;
1229
1230         buf = malloc(BTRFS_SUPER_INFO_SIZE);
1231         if (!buf) {
1232                 ret = -ENOMEM;
1233                 goto out;
1234         }
1235         ret = pread(fd, buf, BTRFS_SUPER_INFO_SIZE, super_offset);
1236         if (ret != BTRFS_SUPER_INFO_SIZE)
1237                 goto brelse;
1238
1239         ret = 0;
1240         disk_super = (struct btrfs_super_block *)buf;
1241         if (btrfs_super_magic(disk_super) != BTRFS_MAGIC)
1242                 goto brelse;
1243
1244         if (!memcmp(disk_super->fsid, root->fs_info->super_copy->fsid,
1245                     BTRFS_FSID_SIZE))
1246                 ret = 1;
1247 brelse:
1248         free(buf);
1249 out:
1250         return ret;
1251 }
1252
1253 static char *size_strs[] = { "", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"};
1254 int pretty_size_snprintf(u64 size, char *str, size_t str_bytes)
1255 {
1256         int num_divs = 0;
1257         float fraction;
1258
1259         if (str_bytes == 0)
1260                 return 0;
1261
1262         if( size < 1024 ){
1263                 fraction = size;
1264                 num_divs = 0;
1265         } else {
1266                 u64 last_size = size;
1267                 num_divs = 0;
1268                 while(size >= 1024){
1269                         last_size = size;
1270                         size /= 1024;
1271                         num_divs ++;
1272                 }
1273
1274                 if (num_divs >= ARRAY_SIZE(size_strs)) {
1275                         str[0] = '\0';
1276                         return -1;
1277                 }
1278                 fraction = (float)last_size / 1024;
1279         }
1280         return snprintf(str, str_bytes, "%.2f%s", fraction,
1281                         size_strs[num_divs]);
1282 }
1283
1284 /*
1285  * __strncpy__null - strncpy with null termination
1286  * @dest:       the target array
1287  * @src:        the source string
1288  * @n:          maximum bytes to copy (size of *dest)
1289  *
1290  * Like strncpy, but ensures destination is null-terminated.
1291  *
1292  * Copies the string pointed to by src, including the terminating null
1293  * byte ('\0'), to the buffer pointed to by dest, up to a maximum
1294  * of n bytes.  Then ensure that dest is null-terminated.
1295  */
1296 char *__strncpy__null(char *dest, const char *src, size_t n)
1297 {
1298         strncpy(dest, src, n);
1299         if (n > 0)
1300                 dest[n - 1] = '\0';
1301         return dest;
1302 }
1303
1304 /*
1305  * Checks to make sure that the label matches our requirements.
1306  * Returns:
1307        0    if everything is safe and usable
1308       -1    if the label is too long
1309  */
1310 static int check_label(const char *input)
1311 {
1312        int len = strlen(input);
1313
1314        if (len > BTRFS_LABEL_SIZE - 1) {
1315                 fprintf(stderr, "ERROR: Label %s is too long (max %d)\n",
1316                         input, BTRFS_LABEL_SIZE - 1);
1317                return -1;
1318        }
1319
1320        return 0;
1321 }
1322
1323 static int set_label_unmounted(const char *dev, const char *label)
1324 {
1325         struct btrfs_trans_handle *trans;
1326         struct btrfs_root *root;
1327         int ret;
1328
1329         ret = check_mounted(dev);
1330         if (ret < 0) {
1331                fprintf(stderr, "FATAL: error checking %s mount status\n", dev);
1332                return -1;
1333         }
1334         if (ret > 0) {
1335                 fprintf(stderr, "ERROR: dev %s is mounted, use mount point\n",
1336                         dev);
1337                 return -1;
1338         }
1339
1340         /* Open the super_block at the default location
1341          * and as read-write.
1342          */
1343         root = open_ctree(dev, 0, OPEN_CTREE_WRITES);
1344         if (!root) /* errors are printed by open_ctree() */
1345                 return -1;
1346
1347         trans = btrfs_start_transaction(root, 1);
1348         snprintf(root->fs_info->super_copy->label, BTRFS_LABEL_SIZE, "%s",
1349                  label);
1350         btrfs_commit_transaction(trans, root);
1351
1352         /* Now we close it since we are done. */
1353         close_ctree(root);
1354         return 0;
1355 }
1356
1357 static int set_label_mounted(const char *mount_path, const char *label)
1358 {
1359         int fd;
1360
1361         fd = open(mount_path, O_RDONLY | O_NOATIME);
1362         if (fd < 0) {
1363                 fprintf(stderr, "ERROR: unable to access '%s'\n", mount_path);
1364                 return -1;
1365         }
1366
1367         if (ioctl(fd, BTRFS_IOC_SET_FSLABEL, label) < 0) {
1368                 fprintf(stderr, "ERROR: unable to set label %s\n",
1369                         strerror(errno));
1370                 close(fd);
1371                 return -1;
1372         }
1373
1374         close(fd);
1375         return 0;
1376 }
1377
1378 static int get_label_unmounted(const char *dev, char *label)
1379 {
1380         struct btrfs_root *root;
1381         int ret;
1382
1383         ret = check_mounted(dev);
1384         if (ret < 0) {
1385                fprintf(stderr, "FATAL: error checking %s mount status\n", dev);
1386                return -1;
1387         }
1388         if (ret > 0) {
1389                 fprintf(stderr, "ERROR: dev %s is mounted, use mount point\n",
1390                         dev);
1391                 return -1;
1392         }
1393
1394         /* Open the super_block at the default location
1395          * and as read-only.
1396          */
1397         root = open_ctree(dev, 0, 0);
1398         if(!root)
1399                 return -1;
1400
1401         memcpy(label, root->fs_info->super_copy->label, BTRFS_LABEL_SIZE);
1402
1403         /* Now we close it since we are done. */
1404         close_ctree(root);
1405         return 0;
1406 }
1407
1408 /*
1409  * If a partition is mounted, try to get the filesystem label via its
1410  * mounted path rather than device.  Return the corresponding error
1411  * the user specified the device path.
1412  */
1413 int get_label_mounted(const char *mount_path, char *labelp)
1414 {
1415         char label[BTRFS_LABEL_SIZE];
1416         int fd;
1417
1418         fd = open(mount_path, O_RDONLY | O_NOATIME);
1419         if (fd < 0) {
1420                 fprintf(stderr, "ERROR: unable to access '%s'\n", mount_path);
1421                 return -1;
1422         }
1423
1424         memset(label, '\0', sizeof(label));
1425         if (ioctl(fd, BTRFS_IOC_GET_FSLABEL, label) < 0) {
1426                 fprintf(stderr, "ERROR: unable get label %s\n", strerror(errno));
1427                 close(fd);
1428                 return -1;
1429         }
1430
1431         strncpy(labelp, label, sizeof(label));
1432         close(fd);
1433         return 0;
1434 }
1435
1436 int get_label(const char *btrfs_dev, char *label)
1437 {
1438         int ret;
1439
1440         if (is_existing_blk_or_reg_file(btrfs_dev))
1441                 ret = get_label_unmounted(btrfs_dev, label);
1442         else
1443                 ret = get_label_mounted(btrfs_dev, label);
1444
1445         return ret;
1446 }
1447
1448 int set_label(const char *btrfs_dev, const char *label)
1449 {
1450         if (check_label(label))
1451                 return -1;
1452
1453         return is_existing_blk_or_reg_file(btrfs_dev) ?
1454                 set_label_unmounted(btrfs_dev, label) :
1455                 set_label_mounted(btrfs_dev, label);
1456 }
1457
1458 int btrfs_scan_block_devices(int run_ioctl)
1459 {
1460
1461         struct stat st;
1462         int ret;
1463         int fd;
1464         struct btrfs_fs_devices *tmp_devices;
1465         u64 num_devices;
1466         FILE *proc_partitions;
1467         int i;
1468         char buf[1024];
1469         char fullpath[110];
1470         int scans = 0;
1471         int special;
1472
1473 scan_again:
1474         proc_partitions = fopen("/proc/partitions","r");
1475         if (!proc_partitions) {
1476                 fprintf(stderr, "Unable to open '/proc/partitions' for scanning\n");
1477                 return -ENOENT;
1478         }
1479         /* skip the header */
1480         for (i = 0; i < 2; i++)
1481                 if (!fgets(buf, 1023, proc_partitions)) {
1482                         fprintf(stderr,
1483                                 "Unable to read '/proc/partitions' for scanning\n");
1484                         fclose(proc_partitions);
1485                         return -ENOENT;
1486                 }
1487
1488         strcpy(fullpath,"/dev/");
1489         while(fgets(buf, 1023, proc_partitions)) {
1490                 i = sscanf(buf," %*d %*d %*d %99s", fullpath+5);
1491
1492                 /*
1493                  * multipath and MD devices may register as a btrfs filesystem
1494                  * both through the original block device and through
1495                  * the special (/dev/mapper or /dev/mdX) entry.
1496                  * This scans the special entries last
1497                  */
1498                 special = strncmp(fullpath, "/dev/dm-", strlen("/dev/dm-")) == 0;
1499                 if (!special)
1500                         special = strncmp(fullpath, "/dev/md", strlen("/dev/md")) == 0;
1501
1502                 if (scans == 0 && special)
1503                         continue;
1504                 if (scans > 0 && !special)
1505                         continue;
1506
1507                 ret = lstat(fullpath, &st);
1508                 if (ret < 0) {
1509                         fprintf(stderr, "failed to stat %s\n", fullpath);
1510                         continue;
1511                 }
1512                 if (!S_ISBLK(st.st_mode)) {
1513                         continue;
1514                 }
1515
1516                 fd = open(fullpath, O_RDONLY);
1517                 if (fd < 0) {
1518                         if (errno != ENOMEDIUM)
1519                                 fprintf(stderr, "failed to open %s: %s\n",
1520                                         fullpath, strerror(errno));
1521                         continue;
1522                 }
1523                 ret = btrfs_scan_one_device(fd, fullpath, &tmp_devices,
1524                                             &num_devices,
1525                                             BTRFS_SUPER_INFO_OFFSET);
1526                 if (ret == 0 && run_ioctl > 0) {
1527                         btrfs_register_one_device(fullpath);
1528                 }
1529                 close(fd);
1530         }
1531
1532         fclose(proc_partitions);
1533
1534         if (scans == 0) {
1535                 scans++;
1536                 goto scan_again;
1537         }
1538         return 0;
1539 }
1540
1541 u64 parse_size(char *s)
1542 {
1543         int i;
1544         char c;
1545         u64 mult = 1;
1546
1547         for (i = 0; s && s[i] && isdigit(s[i]); i++) ;
1548         if (!i) {
1549                 fprintf(stderr, "ERROR: size value is empty\n");
1550                 exit(50);
1551         }
1552
1553         if (s[i]) {
1554                 c = tolower(s[i]);
1555                 switch (c) {
1556                 case 'e':
1557                         mult *= 1024;
1558                         /* fallthrough */
1559                 case 'p':
1560                         mult *= 1024;
1561                         /* fallthrough */
1562                 case 't':
1563                         mult *= 1024;
1564                         /* fallthrough */
1565                 case 'g':
1566                         mult *= 1024;
1567                         /* fallthrough */
1568                 case 'm':
1569                         mult *= 1024;
1570                         /* fallthrough */
1571                 case 'k':
1572                         mult *= 1024;
1573                         /* fallthrough */
1574                 case 'b':
1575                         break;
1576                 default:
1577                         fprintf(stderr, "ERROR: Unknown size descriptor "
1578                                 "'%c'\n", c);
1579                         exit(1);
1580                 }
1581         }
1582         if (s[i] && s[i+1]) {
1583                 fprintf(stderr, "ERROR: Illegal suffix contains "
1584                         "character '%c' in wrong position\n",
1585                         s[i+1]);
1586                 exit(51);
1587         }
1588         return strtoull(s, NULL, 10) * mult;
1589 }
1590
1591 int open_file_or_dir3(const char *fname, DIR **dirstream, int open_flags)
1592 {
1593         int ret;
1594         struct stat st;
1595         int fd;
1596
1597         ret = stat(fname, &st);
1598         if (ret < 0) {
1599                 return -1;
1600         }
1601         if (S_ISDIR(st.st_mode)) {
1602                 *dirstream = opendir(fname);
1603                 if (!*dirstream)
1604                         return -1;
1605                 fd = dirfd(*dirstream);
1606         } else if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
1607                 fd = open(fname, open_flags);
1608         } else {
1609                 /*
1610                  * we set this on purpose, in case the caller output
1611                  * strerror(errno) as success
1612                  */
1613                 errno = EINVAL;
1614                 return -1;
1615         }
1616         if (fd < 0) {
1617                 fd = -1;
1618                 if (*dirstream)
1619                         closedir(*dirstream);
1620         }
1621         return fd;
1622 }
1623
1624 int open_file_or_dir(const char *fname, DIR **dirstream)
1625 {
1626         return open_file_or_dir3(fname, dirstream, O_RDWR);
1627 }
1628
1629 void close_file_or_dir(int fd, DIR *dirstream)
1630 {
1631         if (dirstream)
1632                 closedir(dirstream);
1633         else if (fd >= 0)
1634                 close(fd);
1635 }
1636
1637 int get_device_info(int fd, u64 devid,
1638                 struct btrfs_ioctl_dev_info_args *di_args)
1639 {
1640         int ret;
1641
1642         di_args->devid = devid;
1643         memset(&di_args->uuid, '\0', sizeof(di_args->uuid));
1644
1645         ret = ioctl(fd, BTRFS_IOC_DEV_INFO, di_args);
1646         return ret ? -errno : 0;
1647 }
1648
1649 /*
1650  * For a given path, fill in the ioctl fs_ and info_ args.
1651  * If the path is a btrfs mountpoint, fill info for all devices.
1652  * If the path is a btrfs device, fill in only that device.
1653  *
1654  * The path provided must be either on a mounted btrfs fs,
1655  * or be a mounted btrfs device.
1656  *
1657  * Returns 0 on success, or a negative errno.
1658  */
1659 int get_fs_info(char *path, struct btrfs_ioctl_fs_info_args *fi_args,
1660                 struct btrfs_ioctl_dev_info_args **di_ret)
1661 {
1662         int fd = -1;
1663         int ret = 0;
1664         int ndevs = 0;
1665         int i = 0;
1666         struct btrfs_fs_devices *fs_devices_mnt = NULL;
1667         struct btrfs_ioctl_dev_info_args *di_args;
1668         char mp[BTRFS_PATH_NAME_MAX + 1];
1669         DIR *dirstream = NULL;
1670
1671         memset(fi_args, 0, sizeof(*fi_args));
1672
1673         if (is_block_device(path)) {
1674                 struct btrfs_super_block *disk_super;
1675                 char buf[BTRFS_SUPER_INFO_SIZE];
1676                 u64 devid;
1677
1678                 /* Ensure it's mounted, then set path to the mountpoint */
1679                 fd = open(path, O_RDONLY);
1680                 if (fd < 0) {
1681                         ret = -errno;
1682                         fprintf(stderr, "Couldn't open %s: %s\n",
1683                                 path, strerror(errno));
1684                         goto out;
1685                 }
1686                 ret = check_mounted_where(fd, path, mp, sizeof(mp),
1687                                           &fs_devices_mnt);
1688                 if (!ret) {
1689                         ret = -EINVAL;
1690                         goto out;
1691                 }
1692                 if (ret < 0)
1693                         goto out;
1694                 path = mp;
1695                 /* Only fill in this one device */
1696                 fi_args->num_devices = 1;
1697
1698                 disk_super = (struct btrfs_super_block *)buf;
1699                 ret = btrfs_read_dev_super(fd, disk_super, BTRFS_SUPER_INFO_OFFSET);
1700                 if (ret < 0) {
1701                         ret = -EIO;
1702                         goto out;
1703                 }
1704                 devid = btrfs_stack_device_id(&disk_super->dev_item);
1705
1706                 fi_args->max_id = devid;
1707                 i = devid;
1708
1709                 memcpy(fi_args->fsid, fs_devices_mnt->fsid, BTRFS_FSID_SIZE);
1710                 close(fd);
1711         }
1712
1713         /* at this point path must not be for a block device */
1714         fd = open_file_or_dir(path, &dirstream);
1715         if (fd < 0) {
1716                 ret = -errno;
1717                 goto out;
1718         }
1719
1720         /* fill in fi_args if not just a single device */
1721         if (fi_args->num_devices != 1) {
1722                 ret = ioctl(fd, BTRFS_IOC_FS_INFO, fi_args);
1723                 if (ret < 0) {
1724                         ret = -errno;
1725                         goto out;
1726                 }
1727         }
1728
1729         if (!fi_args->num_devices)
1730                 goto out;
1731
1732         di_args = *di_ret = malloc(fi_args->num_devices * sizeof(*di_args));
1733         if (!di_args) {
1734                 ret = -errno;
1735                 goto out;
1736         }
1737
1738         for (; i <= fi_args->max_id; ++i) {
1739                 BUG_ON(ndevs >= fi_args->num_devices);
1740                 ret = get_device_info(fd, i, &di_args[ndevs]);
1741                 if (ret == -ENODEV)
1742                         continue;
1743                 if (ret)
1744                         goto out;
1745                 ndevs++;
1746         }
1747
1748         /*
1749         * only when the only dev we wanted to find is not there then
1750         * let any error be returned
1751         */
1752         if (fi_args->num_devices != 1) {
1753                 BUG_ON(ndevs == 0);
1754                 ret = 0;
1755         }
1756
1757 out:
1758         close_file_or_dir(fd, dirstream);
1759         return ret;
1760 }
1761
1762 #define isoctal(c)      (((c) & ~7) == '0')
1763
1764 static inline void translate(char *f, char *t)
1765 {
1766         while (*f != '\0') {
1767                 if (*f == '\\' &&
1768                     isoctal(f[1]) && isoctal(f[2]) && isoctal(f[3])) {
1769                         *t++ = 64*(f[1] & 7) + 8*(f[2] & 7) + (f[3] & 7);
1770                         f += 4;
1771                 } else
1772                         *t++ = *f++;
1773         }
1774         *t = '\0';
1775         return;
1776 }
1777
1778 /*
1779  * Checks if the swap device.
1780  * Returns 1 if swap device, < 0 on error or 0 if not swap device.
1781  */
1782 static int is_swap_device(const char *file)
1783 {
1784         FILE    *f;
1785         struct stat     st_buf;
1786         dev_t   dev;
1787         ino_t   ino = 0;
1788         char    tmp[PATH_MAX];
1789         char    buf[PATH_MAX];
1790         char    *cp;
1791         int     ret = 0;
1792
1793         if (stat(file, &st_buf) < 0)
1794                 return -errno;
1795         if (S_ISBLK(st_buf.st_mode))
1796                 dev = st_buf.st_rdev;
1797         else if (S_ISREG(st_buf.st_mode)) {
1798                 dev = st_buf.st_dev;
1799                 ino = st_buf.st_ino;
1800         } else
1801                 return 0;
1802
1803         if ((f = fopen("/proc/swaps", "r")) == NULL)
1804                 return 0;
1805
1806         /* skip the first line */
1807         if (fgets(tmp, sizeof(tmp), f) == NULL)
1808                 goto out;
1809
1810         while (fgets(tmp, sizeof(tmp), f) != NULL) {
1811                 if ((cp = strchr(tmp, ' ')) != NULL)
1812                         *cp = '\0';
1813                 if ((cp = strchr(tmp, '\t')) != NULL)
1814                         *cp = '\0';
1815                 translate(tmp, buf);
1816                 if (stat(buf, &st_buf) != 0)
1817                         continue;
1818                 if (S_ISBLK(st_buf.st_mode)) {
1819                         if (dev == st_buf.st_rdev) {
1820                                 ret = 1;
1821                                 break;
1822                         }
1823                 } else if (S_ISREG(st_buf.st_mode)) {
1824                         if (dev == st_buf.st_dev && ino == st_buf.st_ino) {
1825                                 ret = 1;
1826                                 break;
1827                         }
1828                 }
1829         }
1830
1831 out:
1832         fclose(f);
1833
1834         return ret;
1835 }
1836
1837 /*
1838  * Check for existing filesystem or partition table on device.
1839  * Returns:
1840  *       1 for existing fs or partition
1841  *       0 for nothing found
1842  *      -1 for internal error
1843  */
1844 static int
1845 check_overwrite(
1846         char            *device)
1847 {
1848         const char      *type;
1849         blkid_probe     pr = NULL;
1850         int             ret;
1851         blkid_loff_t    size;
1852
1853         if (!device || !*device)
1854                 return 0;
1855
1856         ret = -1; /* will reset on success of all setup calls */
1857
1858         pr = blkid_new_probe_from_filename(device);
1859         if (!pr)
1860                 goto out;
1861
1862         size = blkid_probe_get_size(pr);
1863         if (size < 0)
1864                 goto out;
1865
1866         /* nothing to overwrite on a 0-length device */
1867         if (size == 0) {
1868                 ret = 0;
1869                 goto out;
1870         }
1871
1872         ret = blkid_probe_enable_partitions(pr, 1);
1873         if (ret < 0)
1874                 goto out;
1875
1876         ret = blkid_do_fullprobe(pr);
1877         if (ret < 0)
1878                 goto out;
1879
1880         /*
1881          * Blkid returns 1 for nothing found and 0 when it finds a signature,
1882          * but we want the exact opposite, so reverse the return value here.
1883          *
1884          * In addition print some useful diagnostics about what actually is
1885          * on the device.
1886          */
1887         if (ret) {
1888                 ret = 0;
1889                 goto out;
1890         }
1891
1892         if (!blkid_probe_lookup_value(pr, "TYPE", &type, NULL)) {
1893                 fprintf(stderr,
1894                         "%s appears to contain an existing "
1895                         "filesystem (%s).\n", device, type);
1896         } else if (!blkid_probe_lookup_value(pr, "PTTYPE", &type, NULL)) {
1897                 fprintf(stderr,
1898                         "%s appears to contain a partition "
1899                         "table (%s).\n", device, type);
1900         } else {
1901                 fprintf(stderr,
1902                         "%s appears to contain something weird "
1903                         "according to blkid\n", device);
1904         }
1905         ret = 1;
1906
1907 out:
1908         if (pr)
1909                 blkid_free_probe(pr);
1910         if (ret == -1)
1911                 fprintf(stderr,
1912                         "probe of %s failed, cannot detect "
1913                           "existing filesystem.\n", device);
1914         return ret;
1915 }
1916
1917 int test_num_disk_vs_raid(u64 metadata_profile, u64 data_profile,
1918         u64 dev_cnt, int mixed, char *estr)
1919 {
1920         size_t sz = 100;
1921         u64 allowed = 0;
1922
1923         switch (dev_cnt) {
1924         default:
1925         case 4:
1926                 allowed |= BTRFS_BLOCK_GROUP_RAID10;
1927         case 3:
1928                 allowed |= BTRFS_BLOCK_GROUP_RAID6;
1929         case 2:
1930                 allowed |= BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
1931                         BTRFS_BLOCK_GROUP_RAID5;
1932                 break;
1933         case 1:
1934                 allowed |= BTRFS_BLOCK_GROUP_DUP;
1935         }
1936
1937         if (metadata_profile & ~allowed) {
1938                 snprintf(estr, sz, "unable to create FS with metadata "
1939                         "profile %llu (have %llu devices)\n",
1940                         metadata_profile, dev_cnt);
1941                 return 1;
1942         }
1943         if (data_profile & ~allowed) {
1944                 snprintf(estr, sz, "unable to create FS with data "
1945                         "profile %llu (have %llu devices)\n",
1946                         metadata_profile, dev_cnt);
1947                 return 1;
1948         }
1949
1950         if (!mixed && (data_profile & BTRFS_BLOCK_GROUP_DUP)) {
1951                 snprintf(estr, sz,
1952                         "dup for data is allowed only in mixed mode");
1953                 return 1;
1954         }
1955         return 0;
1956 }
1957
1958 /* Check if disk is suitable for btrfs
1959  * returns:
1960  *  1: something is wrong, estr provides the error
1961  *  0: all is fine
1962  */
1963 int test_dev_for_mkfs(char *file, int force_overwrite, char *estr)
1964 {
1965         int ret, fd;
1966         size_t sz = 100;
1967         struct stat st;
1968
1969         ret = is_swap_device(file);
1970         if (ret < 0) {
1971                 snprintf(estr, sz, "error checking %s status: %s\n", file,
1972                         strerror(-ret));
1973                 return 1;
1974         }
1975         if (ret == 1) {
1976                 snprintf(estr, sz, "%s is a swap device\n", file);
1977                 return 1;
1978         }
1979         if (!force_overwrite) {
1980                 if (check_overwrite(file)) {
1981                         snprintf(estr, sz, "Use the -f option to force overwrite.\n");
1982                         return 1;
1983                 }
1984         }
1985         ret = check_mounted(file);
1986         if (ret < 0) {
1987                 snprintf(estr, sz, "error checking %s mount status\n",
1988                         file);
1989                 return 1;
1990         }
1991         if (ret == 1) {
1992                 snprintf(estr, sz, "%s is mounted\n", file);
1993                 return 1;
1994         }
1995         /* check if the device is busy */
1996         fd = open(file, O_RDWR|O_EXCL);
1997         if (fd < 0) {
1998                 snprintf(estr, sz, "unable to open %s: %s\n", file,
1999                         strerror(errno));
2000                 return 1;
2001         }
2002         if (fstat(fd, &st)) {
2003                 snprintf(estr, sz, "unable to stat %s: %s\n", file,
2004                         strerror(errno));
2005                 close(fd);
2006                 return 1;
2007         }
2008         if (!S_ISBLK(st.st_mode)) {
2009                 fprintf(stderr, "'%s' is not a block device\n", file);
2010                 close(fd);
2011                 return 1;
2012         }
2013         close(fd);
2014         return 0;
2015 }
2016
2017 int btrfs_scan_lblkid(int update_kernel)
2018 {
2019         int fd = -1;
2020         int ret;
2021         u64 num_devices;
2022         struct btrfs_fs_devices *tmp_devices;
2023         blkid_dev_iterate iter = NULL;
2024         blkid_dev dev = NULL;
2025         blkid_cache cache = NULL;
2026         char path[PATH_MAX];
2027
2028         if (blkid_get_cache(&cache, 0) < 0) {
2029                 printf("ERROR: lblkid cache get failed\n");
2030                 return 1;
2031         }
2032         blkid_probe_all(cache);
2033         iter = blkid_dev_iterate_begin(cache);
2034         blkid_dev_set_search(iter, "TYPE", "btrfs");
2035         while (blkid_dev_next(iter, &dev) == 0) {
2036                 dev = blkid_verify(cache, dev);
2037                 if (!dev)
2038                         continue;
2039                 /* if we are here its definitely a btrfs disk*/
2040                 strncpy(path, blkid_dev_devname(dev), PATH_MAX);
2041
2042                 fd = open(path, O_RDONLY);
2043                 if (fd < 0) {
2044                         printf("ERROR: could not open %s\n", path);
2045                         continue;
2046                 }
2047                 ret = btrfs_scan_one_device(fd, path, &tmp_devices,
2048                                 &num_devices, BTRFS_SUPER_INFO_OFFSET);
2049                 if (ret) {
2050                         printf("ERROR: could not scan %s\n", path);
2051                         close (fd);
2052                         continue;
2053                 }
2054
2055                 close(fd);
2056                 if (update_kernel)
2057                         btrfs_register_one_device(path);
2058         }
2059         blkid_dev_iterate_end(iter);
2060         blkid_put_cache(cache);
2061         return 0;
2062 }
2063
2064 /*
2065  * scans devs for the btrfs
2066 */
2067 int scan_for_btrfs(int where, int update_kernel)
2068 {
2069         int ret = 0;
2070
2071         switch (where) {
2072         case BTRFS_SCAN_PROC:
2073                 ret = btrfs_scan_block_devices(update_kernel);
2074                 break;
2075         case BTRFS_SCAN_DEV:
2076                 ret = btrfs_scan_one_dir("/dev", update_kernel);
2077                 break;
2078         case BTRFS_SCAN_LBLKID:
2079                 ret = btrfs_scan_lblkid(update_kernel);
2080                 break;
2081         }
2082         return ret;
2083 }
2084
2085 int is_vol_small(char *file)
2086 {
2087         int fd = -1;
2088         int e;
2089         struct stat st;
2090         u64 size;
2091
2092         fd = open(file, O_RDONLY);
2093         if (fd < 0)
2094                 return -errno;
2095         if (fstat(fd, &st) < 0) {
2096                 e = -errno;
2097                 close(fd);
2098                 return e;
2099         }
2100         size = btrfs_device_size(fd, &st);
2101         if (size == 0) {
2102                 close(fd);
2103                 return -1;
2104         }
2105         if (size < 1024 * 1024 * 1024) {
2106                 close(fd);
2107                 return 1;
2108         } else {
2109                 close(fd);
2110                 return 0;
2111         }
2112 }
2113
2114 /*
2115  * This reads a line from the stdin and only returns non-zero if the
2116  * first whitespace delimited token is a case insensitive match with yes
2117  * or y.
2118  */
2119 int ask_user(char *question)
2120 {
2121         char buf[30] = {0,};
2122         char *saveptr = NULL;
2123         char *answer;
2124
2125         printf("%s [y/N]: ", question);
2126
2127         return fgets(buf, sizeof(buf) - 1, stdin) &&
2128                (answer = strtok_r(buf, " \t\n\r", &saveptr)) &&
2129                (!strcasecmp(answer, "yes") || !strcasecmp(answer, "y"));
2130 }
2131
2132 /*
2133  * For a given:
2134  * - file or directory return the containing tree root id
2135  * - subvolume return it's own tree id
2136  * - BTRFS_EMPTY_SUBVOL_DIR_OBJECTID (directory with ino == 2) the result is
2137  *   undefined and function returns -1
2138  */
2139 int lookup_ino_rootid(int fd, u64 *rootid)
2140 {
2141         struct btrfs_ioctl_ino_lookup_args args;
2142         int ret;
2143         int e;
2144
2145         memset(&args, 0, sizeof(args));
2146         args.treeid = 0;
2147         args.objectid = BTRFS_FIRST_FREE_OBJECTID;
2148
2149         ret = ioctl(fd, BTRFS_IOC_INO_LOOKUP, &args);
2150         e = errno;
2151         if (ret) {
2152                 fprintf(stderr, "ERROR: Failed to lookup root id - %s\n",
2153                         strerror(e));
2154                 return ret;
2155         }
2156
2157         *rootid = args.treeid;
2158
2159         return 0;
2160 }
2161
2162 int find_mount_root(const char *path, char **mount_root)
2163 {
2164         FILE *mnttab;
2165         int fd;
2166         struct mntent *ent;
2167         int len;
2168         int ret;
2169         int longest_matchlen = 0;
2170         char *longest_match = NULL;
2171
2172         fd = open(path, O_RDONLY | O_NOATIME);
2173         if (fd < 0)
2174                 return -errno;
2175         close(fd);
2176
2177         mnttab = setmntent("/proc/self/mounts", "r");
2178         if (!mnttab)
2179                 return -errno;
2180
2181         while ((ent = getmntent(mnttab))) {
2182                 len = strlen(ent->mnt_dir);
2183                 if (strncmp(ent->mnt_dir, path, len) == 0) {
2184                         /* match found */
2185                         if (longest_matchlen < len) {
2186                                 free(longest_match);
2187                                 longest_matchlen = len;
2188                                 longest_match = strdup(ent->mnt_dir);
2189                         }
2190                 }
2191         }
2192         endmntent(mnttab);
2193
2194         if (!longest_match) {
2195                 fprintf(stderr,
2196                         "ERROR: Failed to find mount root for path %s.\n",
2197                         path);
2198                 return -ENOENT;
2199         }
2200
2201         ret = 0;
2202         *mount_root = realpath(longest_match, NULL);
2203         if (!*mount_root)
2204                 ret = -errno;
2205
2206         free(longest_match);
2207         return ret;
2208 }