Btrfs-progs: allow compression property gets for read-only subvolumes
[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         zero_end = 1;
617
618         if (block_count < 1024 * 1024 * 1024 && !(*mixed)) {
619                 printf("SMALL VOLUME: forcing mixed metadata/data groups\n");
620                 *mixed = 1;
621         }
622
623         if (discard) {
624                 /*
625                  * We intentionally ignore errors from the discard ioctl.  It
626                  * is not necessary for the mkfs functionality but just an
627                  * optimization.
628                  */
629                 if (discard_range(fd, 0, 0) == 0) {
630                         fprintf(stderr, "Performing full device TRIM (%s) ...\n",
631                                 pretty_size(block_count));
632                         discard_blocks(fd, 0, block_count);
633                 }
634         }
635
636         ret = zero_dev_start(fd);
637         if (ret)
638                 goto zero_dev_error;
639
640         for (i = 0 ; i < BTRFS_SUPER_MIRROR_MAX; i++) {
641                 bytenr = btrfs_sb_offset(i);
642                 if (bytenr >= block_count)
643                         break;
644                 ret = zero_blocks(fd, bytenr, BTRFS_SUPER_INFO_SIZE);
645                 if (ret)
646                         goto zero_dev_error;
647         }
648
649         if (zero_end) {
650                 ret = zero_dev_end(fd, block_count);
651                 if (ret)
652                         goto zero_dev_error;
653         }
654         *block_count_ret = block_count;
655
656 zero_dev_error:
657         if (ret < 0) {
658                 fprintf(stderr, "ERROR: failed to zero device '%s' - %s\n",
659                         file, strerror(-ret));
660                 return 1;
661         } else if (ret > 0) {
662                 fprintf(stderr, "ERROR: failed to zero device '%s' - %d\n",
663                         file, ret);
664                 return 1;
665         }
666         return 0;
667 }
668
669 int btrfs_make_root_dir(struct btrfs_trans_handle *trans,
670                         struct btrfs_root *root, u64 objectid)
671 {
672         int ret;
673         struct btrfs_inode_item inode_item;
674         time_t now = time(NULL);
675
676         memset(&inode_item, 0, sizeof(inode_item));
677         btrfs_set_stack_inode_generation(&inode_item, trans->transid);
678         btrfs_set_stack_inode_size(&inode_item, 0);
679         btrfs_set_stack_inode_nlink(&inode_item, 1);
680         btrfs_set_stack_inode_nbytes(&inode_item, root->leafsize);
681         btrfs_set_stack_inode_mode(&inode_item, S_IFDIR | 0755);
682         btrfs_set_stack_timespec_sec(&inode_item.atime, now);
683         btrfs_set_stack_timespec_nsec(&inode_item.atime, 0);
684         btrfs_set_stack_timespec_sec(&inode_item.ctime, now);
685         btrfs_set_stack_timespec_nsec(&inode_item.ctime, 0);
686         btrfs_set_stack_timespec_sec(&inode_item.mtime, now);
687         btrfs_set_stack_timespec_nsec(&inode_item.mtime, 0);
688         btrfs_set_stack_timespec_sec(&inode_item.otime, 0);
689         btrfs_set_stack_timespec_nsec(&inode_item.otime, 0);
690
691         if (root->fs_info->tree_root == root)
692                 btrfs_set_super_root_dir(root->fs_info->super_copy, objectid);
693
694         ret = btrfs_insert_inode(trans, root, objectid, &inode_item);
695         if (ret)
696                 goto error;
697
698         ret = btrfs_insert_inode_ref(trans, root, "..", 2, objectid, objectid, 0);
699         if (ret)
700                 goto error;
701
702         btrfs_set_root_dirid(&root->root_item, objectid);
703         ret = 0;
704 error:
705         return ret;
706 }
707
708 /*
709  * checks if a path is a block device node
710  * Returns negative errno on failure, otherwise
711  * returns 1 for blockdev, 0 for not-blockdev
712  */
713 int is_block_device(const char *path)
714 {
715         struct stat statbuf;
716
717         if (stat(path, &statbuf) < 0)
718                 return -errno;
719
720         return S_ISBLK(statbuf.st_mode);
721 }
722
723 /*
724  * check if given path is a mount point
725  * return 1 if yes. 0 if no. -1 for error
726  */
727 int is_mount_point(const char *path)
728 {
729         FILE *f;
730         struct mntent *mnt;
731         int ret = 0;
732
733         f = setmntent("/proc/self/mounts", "r");
734         if (f == NULL)
735                 return -1;
736
737         while ((mnt = getmntent(f)) != NULL) {
738                 if (strcmp(mnt->mnt_dir, path))
739                         continue;
740                 ret = 1;
741                 break;
742         }
743         endmntent(f);
744         return ret;
745 }
746
747 /*
748  * Find the mount point for a mounted device.
749  * On success, returns 0 with mountpoint in *mp.
750  * On failure, returns -errno (not mounted yields -EINVAL)
751  * Is noisy on failures, expects to be given a mounted device.
752  */
753 int get_btrfs_mount(const char *dev, char *mp, size_t mp_size)
754 {
755         int ret;
756         int fd = -1;
757
758         ret = is_block_device(dev);
759         if (ret <= 0) {
760                 if (!ret) {
761                         fprintf(stderr, "%s is not a block device\n", dev);
762                         ret = -EINVAL;
763                 } else {
764                         fprintf(stderr, "Could not check %s: %s\n",
765                                 dev, strerror(-ret));
766                 }
767                 goto out;
768         }
769
770         fd = open(dev, O_RDONLY);
771         if (fd < 0) {
772                 ret = -errno;
773                 fprintf(stderr, "Could not open %s: %s\n", dev, strerror(errno));
774                 goto out;
775         }
776
777         ret = check_mounted_where(fd, dev, mp, mp_size, NULL);
778         if (!ret) {
779                 ret = -EINVAL;
780         } else { /* mounted, all good */
781                 ret = 0;
782         }
783 out:
784         if (fd != -1)
785                 close(fd);
786         return ret;
787 }
788
789 /*
790  * Given a pathname, return a filehandle to:
791  *      the original pathname or,
792  *      if the pathname is a mounted btrfs device, to its mountpoint.
793  *
794  * On error, return -1, errno should be set.
795  */
796 int open_path_or_dev_mnt(const char *path, DIR **dirstream)
797 {
798         char mp[BTRFS_PATH_NAME_MAX + 1];
799         int fdmnt;
800
801         if (is_block_device(path)) {
802                 int ret;
803
804                 ret = get_btrfs_mount(path, mp, sizeof(mp));
805                 if (ret < 0) {
806                         /* not a mounted btrfs dev */
807                         errno = EINVAL;
808                         return -1;
809                 }
810                 fdmnt = open_file_or_dir(mp, dirstream);
811         } else {
812                 fdmnt = open_file_or_dir(path, dirstream);
813         }
814
815         return fdmnt;
816 }
817
818 /* checks if a device is a loop device */
819 static int is_loop_device (const char* device) {
820         struct stat statbuf;
821
822         if(stat(device, &statbuf) < 0)
823                 return -errno;
824
825         return (S_ISBLK(statbuf.st_mode) &&
826                 MAJOR(statbuf.st_rdev) == LOOP_MAJOR);
827 }
828
829
830 /* Takes a loop device path (e.g. /dev/loop0) and returns
831  * the associated file (e.g. /images/my_btrfs.img) */
832 static int resolve_loop_device(const char* loop_dev, char* loop_file,
833                 int max_len)
834 {
835         int ret;
836         FILE *f;
837         char fmt[20];
838         char p[PATH_MAX];
839         char real_loop_dev[PATH_MAX];
840
841         if (!realpath(loop_dev, real_loop_dev))
842                 return -errno;
843         snprintf(p, PATH_MAX, "/sys/block/%s/loop/backing_file", strrchr(real_loop_dev, '/'));
844         if (!(f = fopen(p, "r")))
845                 return -errno;
846
847         snprintf(fmt, 20, "%%%i[^\n]", max_len-1);
848         ret = fscanf(f, fmt, loop_file);
849         fclose(f);
850         if (ret == EOF)
851                 return -errno;
852
853         return 0;
854 }
855
856 /* Checks whether a and b are identical or device
857  * files associated with the same block device
858  */
859 static int is_same_blk_file(const char* a, const char* b)
860 {
861         struct stat st_buf_a, st_buf_b;
862         char real_a[PATH_MAX];
863         char real_b[PATH_MAX];
864
865         if(!realpath(a, real_a))
866                 strcpy(real_a, a);
867
868         if (!realpath(b, real_b))
869                 strcpy(real_b, b);
870
871         /* Identical path? */
872         if(strcmp(real_a, real_b) == 0)
873                 return 1;
874
875         if(stat(a, &st_buf_a) < 0 ||
876            stat(b, &st_buf_b) < 0)
877         {
878                 if (errno == ENOENT)
879                         return 0;
880                 return -errno;
881         }
882
883         /* Same blockdevice? */
884         if(S_ISBLK(st_buf_a.st_mode) &&
885            S_ISBLK(st_buf_b.st_mode) &&
886            st_buf_a.st_rdev == st_buf_b.st_rdev)
887         {
888                 return 1;
889         }
890
891         /* Hardlink? */
892         if (st_buf_a.st_dev == st_buf_b.st_dev &&
893             st_buf_a.st_ino == st_buf_b.st_ino)
894         {
895                 return 1;
896         }
897
898         return 0;
899 }
900
901 /* checks if a and b are identical or device
902  * files associated with the same block device or
903  * if one file is a loop device that uses the other
904  * file.
905  */
906 static int is_same_loop_file(const char* a, const char* b)
907 {
908         char res_a[PATH_MAX];
909         char res_b[PATH_MAX];
910         const char* final_a = NULL;
911         const char* final_b = NULL;
912         int ret;
913
914         /* Resolve a if it is a loop device */
915         if((ret = is_loop_device(a)) < 0) {
916                 if (ret == -ENOENT)
917                         return 0;
918                 return ret;
919         } else if (ret) {
920                 ret = resolve_loop_device(a, res_a, sizeof(res_a));
921                 if (ret < 0) {
922                         if (errno != EPERM)
923                                 return ret;
924                 } else {
925                         final_a = res_a;
926                 }
927         } else {
928                 final_a = a;
929         }
930
931         /* Resolve b if it is a loop device */
932         if ((ret = is_loop_device(b)) < 0) {
933                 if (ret == -ENOENT)
934                         return 0;
935                 return ret;
936         } else if (ret) {
937                 ret = resolve_loop_device(b, res_b, sizeof(res_b));
938                 if (ret < 0) {
939                         if (errno != EPERM)
940                                 return ret;
941                 } else {
942                         final_b = res_b;
943                 }
944         } else {
945                 final_b = b;
946         }
947
948         return is_same_blk_file(final_a, final_b);
949 }
950
951 /* Checks if a file exists and is a block or regular file*/
952 static int is_existing_blk_or_reg_file(const char* filename)
953 {
954         struct stat st_buf;
955
956         if(stat(filename, &st_buf) < 0) {
957                 if(errno == ENOENT)
958                         return 0;
959                 else
960                         return -errno;
961         }
962
963         return (S_ISBLK(st_buf.st_mode) || S_ISREG(st_buf.st_mode));
964 }
965
966 /* Checks if a file is used (directly or indirectly via a loop device)
967  * by a device in fs_devices
968  */
969 static int blk_file_in_dev_list(struct btrfs_fs_devices* fs_devices,
970                 const char* file)
971 {
972         int ret;
973         struct list_head *head;
974         struct list_head *cur;
975         struct btrfs_device *device;
976
977         head = &fs_devices->devices;
978         list_for_each(cur, head) {
979                 device = list_entry(cur, struct btrfs_device, dev_list);
980
981                 if((ret = is_same_loop_file(device->name, file)))
982                         return ret;
983         }
984
985         return 0;
986 }
987
988 /*
989  * returns 1 if the device was mounted, < 0 on error or 0 if everything
990  * is safe to continue.
991  */
992 int check_mounted(const char* file)
993 {
994         int fd;
995         int ret;
996
997         fd = open(file, O_RDONLY);
998         if (fd < 0) {
999                 fprintf (stderr, "check_mounted(): Could not open %s\n", file);
1000                 return -errno;
1001         }
1002
1003         ret =  check_mounted_where(fd, file, NULL, 0, NULL);
1004         close(fd);
1005
1006         return ret;
1007 }
1008
1009 int check_mounted_where(int fd, const char *file, char *where, int size,
1010                         struct btrfs_fs_devices **fs_dev_ret)
1011 {
1012         int ret;
1013         u64 total_devs = 1;
1014         int is_btrfs;
1015         struct btrfs_fs_devices *fs_devices_mnt = NULL;
1016         FILE *f;
1017         struct mntent *mnt;
1018
1019         /* scan the initial device */
1020         ret = btrfs_scan_one_device(fd, file, &fs_devices_mnt,
1021                                     &total_devs, BTRFS_SUPER_INFO_OFFSET);
1022         is_btrfs = (ret >= 0);
1023
1024         /* scan other devices */
1025         if (is_btrfs && total_devs > 1) {
1026                 if ((ret = btrfs_scan_for_fsid(!BTRFS_UPDATE_KERNEL)))
1027                         return ret;
1028         }
1029
1030         /* iterate over the list of currently mountes filesystems */
1031         if ((f = setmntent ("/proc/self/mounts", "r")) == NULL)
1032                 return -errno;
1033
1034         while ((mnt = getmntent (f)) != NULL) {
1035                 if(is_btrfs) {
1036                         if(strcmp(mnt->mnt_type, "btrfs") != 0)
1037                                 continue;
1038
1039                         ret = blk_file_in_dev_list(fs_devices_mnt, mnt->mnt_fsname);
1040                 } else {
1041                         /* ignore entries in the mount table that are not
1042                            associated with a file*/
1043                         if((ret = is_existing_blk_or_reg_file(mnt->mnt_fsname)) < 0)
1044                                 goto out_mntloop_err;
1045                         else if(!ret)
1046                                 continue;
1047
1048                         ret = is_same_loop_file(file, mnt->mnt_fsname);
1049                 }
1050
1051                 if(ret < 0)
1052                         goto out_mntloop_err;
1053                 else if(ret)
1054                         break;
1055         }
1056
1057         /* Did we find an entry in mnt table? */
1058         if (mnt && size && where) {
1059                 strncpy(where, mnt->mnt_dir, size);
1060                 where[size-1] = 0;
1061         }
1062         if (fs_dev_ret)
1063                 *fs_dev_ret = fs_devices_mnt;
1064
1065         ret = (mnt != NULL);
1066
1067 out_mntloop_err:
1068         endmntent (f);
1069
1070         return ret;
1071 }
1072
1073 struct pending_dir {
1074         struct list_head list;
1075         char name[PATH_MAX];
1076 };
1077
1078 void btrfs_register_one_device(char *fname)
1079 {
1080         struct btrfs_ioctl_vol_args args;
1081         int fd;
1082         int ret;
1083         int e;
1084
1085         fd = open("/dev/btrfs-control", O_RDONLY);
1086         if (fd < 0) {
1087                 fprintf(stderr, "failed to open /dev/btrfs-control "
1088                         "skipping device registration: %s\n",
1089                         strerror(errno));
1090                 return;
1091         }
1092         strncpy(args.name, fname, BTRFS_PATH_NAME_MAX);
1093         args.name[BTRFS_PATH_NAME_MAX-1] = 0;
1094         ret = ioctl(fd, BTRFS_IOC_SCAN_DEV, &args);
1095         e = errno;
1096         if(ret<0){
1097                 fprintf(stderr, "ERROR: device scan failed '%s' - %s\n",
1098                         fname, strerror(e));
1099         }
1100         close(fd);
1101 }
1102
1103 int btrfs_scan_one_dir(char *dirname, int run_ioctl)
1104 {
1105         DIR *dirp = NULL;
1106         struct dirent *dirent;
1107         struct pending_dir *pending;
1108         struct stat st;
1109         int ret;
1110         int fd;
1111         int dirname_len;
1112         char *fullpath;
1113         struct list_head pending_list;
1114         struct btrfs_fs_devices *tmp_devices;
1115         u64 num_devices;
1116
1117         INIT_LIST_HEAD(&pending_list);
1118
1119         pending = malloc(sizeof(*pending));
1120         if (!pending)
1121                 return -ENOMEM;
1122         strcpy(pending->name, dirname);
1123
1124 again:
1125         dirname_len = strlen(pending->name);
1126         fullpath = malloc(PATH_MAX);
1127         dirname = pending->name;
1128
1129         if (!fullpath) {
1130                 ret = -ENOMEM;
1131                 goto fail;
1132         }
1133         dirp = opendir(dirname);
1134         if (!dirp) {
1135                 fprintf(stderr, "Unable to open %s for scanning\n", dirname);
1136                 ret = -errno;
1137                 goto fail;
1138         }
1139         while(1) {
1140                 dirent = readdir(dirp);
1141                 if (!dirent)
1142                         break;
1143                 if (dirent->d_name[0] == '.')
1144                         continue;
1145                 if (dirname_len + strlen(dirent->d_name) + 2 > PATH_MAX) {
1146                         ret = -EFAULT;
1147                         goto fail;
1148                 }
1149                 snprintf(fullpath, PATH_MAX, "%s/%s", dirname, dirent->d_name);
1150                 ret = lstat(fullpath, &st);
1151                 if (ret < 0) {
1152                         fprintf(stderr, "failed to stat %s\n", fullpath);
1153                         continue;
1154                 }
1155                 if (S_ISLNK(st.st_mode))
1156                         continue;
1157                 if (S_ISDIR(st.st_mode)) {
1158                         struct pending_dir *next = malloc(sizeof(*next));
1159                         if (!next) {
1160                                 ret = -ENOMEM;
1161                                 goto fail;
1162                         }
1163                         strcpy(next->name, fullpath);
1164                         list_add_tail(&next->list, &pending_list);
1165                 }
1166                 if (!S_ISBLK(st.st_mode)) {
1167                         continue;
1168                 }
1169                 fd = open(fullpath, O_RDONLY);
1170                 if (fd < 0) {
1171                         /* ignore the following errors:
1172                                 ENXIO (device don't exists) 
1173                                 ENOMEDIUM (No medium found -> 
1174                                         like a cd tray empty)
1175                         */
1176                         if(errno != ENXIO && errno != ENOMEDIUM) 
1177                                 fprintf(stderr, "failed to read %s: %s\n", 
1178                                         fullpath, strerror(errno));
1179                         continue;
1180                 }
1181                 ret = btrfs_scan_one_device(fd, fullpath, &tmp_devices,
1182                                             &num_devices,
1183                                             BTRFS_SUPER_INFO_OFFSET);
1184                 if (ret == 0 && run_ioctl > 0) {
1185                         btrfs_register_one_device(fullpath);
1186                 }
1187                 close(fd);
1188         }
1189         if (!list_empty(&pending_list)) {
1190                 free(pending);
1191                 pending = list_entry(pending_list.next, struct pending_dir,
1192                                      list);
1193                 free(fullpath);
1194                 list_del(&pending->list);
1195                 closedir(dirp);
1196                 dirp = NULL;
1197                 goto again;
1198         }
1199         ret = 0;
1200 fail:
1201         free(pending);
1202         free(fullpath);
1203         while (!list_empty(&pending_list)) {
1204                 pending = list_entry(pending_list.next, struct pending_dir,
1205                                      list);
1206                 list_del(&pending->list);
1207                 free(pending);
1208         }
1209         if (dirp)
1210                 closedir(dirp);
1211         return ret;
1212 }
1213
1214 int btrfs_scan_for_fsid(int run_ioctls)
1215 {
1216         int ret;
1217
1218         ret = scan_for_btrfs(BTRFS_SCAN_PROC, run_ioctls);
1219         if (ret)
1220                 ret = scan_for_btrfs(BTRFS_SCAN_DEV, run_ioctls);
1221         return ret;
1222 }
1223
1224 int btrfs_device_already_in_root(struct btrfs_root *root, int fd,
1225                                  int super_offset)
1226 {
1227         struct btrfs_super_block *disk_super;
1228         char *buf;
1229         int ret = 0;
1230
1231         buf = malloc(BTRFS_SUPER_INFO_SIZE);
1232         if (!buf) {
1233                 ret = -ENOMEM;
1234                 goto out;
1235         }
1236         ret = pread(fd, buf, BTRFS_SUPER_INFO_SIZE, super_offset);
1237         if (ret != BTRFS_SUPER_INFO_SIZE)
1238                 goto brelse;
1239
1240         ret = 0;
1241         disk_super = (struct btrfs_super_block *)buf;
1242         if (btrfs_super_magic(disk_super) != BTRFS_MAGIC)
1243                 goto brelse;
1244
1245         if (!memcmp(disk_super->fsid, root->fs_info->super_copy->fsid,
1246                     BTRFS_FSID_SIZE))
1247                 ret = 1;
1248 brelse:
1249         free(buf);
1250 out:
1251         return ret;
1252 }
1253
1254 static char *size_strs[] = { "", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"};
1255 int pretty_size_snprintf(u64 size, char *str, size_t str_bytes)
1256 {
1257         int num_divs = 0;
1258         float fraction;
1259
1260         if (str_bytes == 0)
1261                 return 0;
1262
1263         if( size < 1024 ){
1264                 fraction = size;
1265                 num_divs = 0;
1266         } else {
1267                 u64 last_size = size;
1268                 num_divs = 0;
1269                 while(size >= 1024){
1270                         last_size = size;
1271                         size /= 1024;
1272                         num_divs ++;
1273                 }
1274
1275                 if (num_divs >= ARRAY_SIZE(size_strs)) {
1276                         str[0] = '\0';
1277                         return -1;
1278                 }
1279                 fraction = (float)last_size / 1024;
1280         }
1281         return snprintf(str, str_bytes, "%.2f%s", fraction,
1282                         size_strs[num_divs]);
1283 }
1284
1285 /*
1286  * __strncpy__null - strncpy with null termination
1287  * @dest:       the target array
1288  * @src:        the source string
1289  * @n:          maximum bytes to copy (size of *dest)
1290  *
1291  * Like strncpy, but ensures destination is null-terminated.
1292  *
1293  * Copies the string pointed to by src, including the terminating null
1294  * byte ('\0'), to the buffer pointed to by dest, up to a maximum
1295  * of n bytes.  Then ensure that dest is null-terminated.
1296  */
1297 char *__strncpy__null(char *dest, const char *src, size_t n)
1298 {
1299         strncpy(dest, src, n);
1300         if (n > 0)
1301                 dest[n - 1] = '\0';
1302         return dest;
1303 }
1304
1305 /*
1306  * Checks to make sure that the label matches our requirements.
1307  * Returns:
1308        0    if everything is safe and usable
1309       -1    if the label is too long
1310  */
1311 static int check_label(const char *input)
1312 {
1313        int len = strlen(input);
1314
1315        if (len > BTRFS_LABEL_SIZE - 1) {
1316                 fprintf(stderr, "ERROR: Label %s is too long (max %d)\n",
1317                         input, BTRFS_LABEL_SIZE - 1);
1318                return -1;
1319        }
1320
1321        return 0;
1322 }
1323
1324 static int set_label_unmounted(const char *dev, const char *label)
1325 {
1326         struct btrfs_trans_handle *trans;
1327         struct btrfs_root *root;
1328         int ret;
1329
1330         ret = check_mounted(dev);
1331         if (ret < 0) {
1332                fprintf(stderr, "FATAL: error checking %s mount status\n", dev);
1333                return -1;
1334         }
1335         if (ret > 0) {
1336                 fprintf(stderr, "ERROR: dev %s is mounted, use mount point\n",
1337                         dev);
1338                 return -1;
1339         }
1340
1341         /* Open the super_block at the default location
1342          * and as read-write.
1343          */
1344         root = open_ctree(dev, 0, OPEN_CTREE_WRITES);
1345         if (!root) /* errors are printed by open_ctree() */
1346                 return -1;
1347
1348         trans = btrfs_start_transaction(root, 1);
1349         snprintf(root->fs_info->super_copy->label, BTRFS_LABEL_SIZE, "%s",
1350                  label);
1351         btrfs_commit_transaction(trans, root);
1352
1353         /* Now we close it since we are done. */
1354         close_ctree(root);
1355         return 0;
1356 }
1357
1358 static int set_label_mounted(const char *mount_path, const char *label)
1359 {
1360         int fd;
1361
1362         fd = open(mount_path, O_RDONLY | O_NOATIME);
1363         if (fd < 0) {
1364                 fprintf(stderr, "ERROR: unable to access '%s'\n", mount_path);
1365                 return -1;
1366         }
1367
1368         if (ioctl(fd, BTRFS_IOC_SET_FSLABEL, label) < 0) {
1369                 fprintf(stderr, "ERROR: unable to set label %s\n",
1370                         strerror(errno));
1371                 close(fd);
1372                 return -1;
1373         }
1374
1375         close(fd);
1376         return 0;
1377 }
1378
1379 static int get_label_unmounted(const char *dev, char *label)
1380 {
1381         struct btrfs_root *root;
1382         int ret;
1383
1384         ret = check_mounted(dev);
1385         if (ret < 0) {
1386                fprintf(stderr, "FATAL: error checking %s mount status\n", dev);
1387                return -1;
1388         }
1389         if (ret > 0) {
1390                 fprintf(stderr, "ERROR: dev %s is mounted, use mount point\n",
1391                         dev);
1392                 return -1;
1393         }
1394
1395         /* Open the super_block at the default location
1396          * and as read-only.
1397          */
1398         root = open_ctree(dev, 0, 0);
1399         if(!root)
1400                 return -1;
1401
1402         memcpy(label, root->fs_info->super_copy->label, BTRFS_LABEL_SIZE);
1403
1404         /* Now we close it since we are done. */
1405         close_ctree(root);
1406         return 0;
1407 }
1408
1409 /*
1410  * If a partition is mounted, try to get the filesystem label via its
1411  * mounted path rather than device.  Return the corresponding error
1412  * the user specified the device path.
1413  */
1414 int get_label_mounted(const char *mount_path, char *labelp)
1415 {
1416         char label[BTRFS_LABEL_SIZE];
1417         int fd;
1418
1419         fd = open(mount_path, O_RDONLY | O_NOATIME);
1420         if (fd < 0) {
1421                 fprintf(stderr, "ERROR: unable to access '%s'\n", mount_path);
1422                 return -1;
1423         }
1424
1425         memset(label, '\0', sizeof(label));
1426         if (ioctl(fd, BTRFS_IOC_GET_FSLABEL, label) < 0) {
1427                 fprintf(stderr, "ERROR: unable get label %s\n", strerror(errno));
1428                 close(fd);
1429                 return -1;
1430         }
1431
1432         strncpy(labelp, label, sizeof(label));
1433         close(fd);
1434         return 0;
1435 }
1436
1437 int get_label(const char *btrfs_dev, char *label)
1438 {
1439         int ret;
1440
1441         if (is_existing_blk_or_reg_file(btrfs_dev))
1442                 ret = get_label_unmounted(btrfs_dev, label);
1443         else
1444                 ret = get_label_mounted(btrfs_dev, label);
1445
1446         return ret;
1447 }
1448
1449 int set_label(const char *btrfs_dev, const char *label)
1450 {
1451         if (check_label(label))
1452                 return -1;
1453
1454         return is_existing_blk_or_reg_file(btrfs_dev) ?
1455                 set_label_unmounted(btrfs_dev, label) :
1456                 set_label_mounted(btrfs_dev, label);
1457 }
1458
1459 int btrfs_scan_block_devices(int run_ioctl)
1460 {
1461
1462         struct stat st;
1463         int ret;
1464         int fd;
1465         struct btrfs_fs_devices *tmp_devices;
1466         u64 num_devices;
1467         FILE *proc_partitions;
1468         int i;
1469         char buf[1024];
1470         char fullpath[110];
1471         int scans = 0;
1472         int special;
1473
1474 scan_again:
1475         proc_partitions = fopen("/proc/partitions","r");
1476         if (!proc_partitions) {
1477                 fprintf(stderr, "Unable to open '/proc/partitions' for scanning\n");
1478                 return -ENOENT;
1479         }
1480         /* skip the header */
1481         for (i = 0; i < 2; i++)
1482                 if (!fgets(buf, 1023, proc_partitions)) {
1483                         fprintf(stderr,
1484                                 "Unable to read '/proc/partitions' for scanning\n");
1485                         fclose(proc_partitions);
1486                         return -ENOENT;
1487                 }
1488
1489         strcpy(fullpath,"/dev/");
1490         while(fgets(buf, 1023, proc_partitions)) {
1491                 i = sscanf(buf," %*d %*d %*d %99s", fullpath+5);
1492
1493                 /*
1494                  * multipath and MD devices may register as a btrfs filesystem
1495                  * both through the original block device and through
1496                  * the special (/dev/mapper or /dev/mdX) entry.
1497                  * This scans the special entries last
1498                  */
1499                 special = strncmp(fullpath, "/dev/dm-", strlen("/dev/dm-")) == 0;
1500                 if (!special)
1501                         special = strncmp(fullpath, "/dev/md", strlen("/dev/md")) == 0;
1502
1503                 if (scans == 0 && special)
1504                         continue;
1505                 if (scans > 0 && !special)
1506                         continue;
1507
1508                 ret = lstat(fullpath, &st);
1509                 if (ret < 0) {
1510                         fprintf(stderr, "failed to stat %s\n", fullpath);
1511                         continue;
1512                 }
1513                 if (!S_ISBLK(st.st_mode)) {
1514                         continue;
1515                 }
1516
1517                 fd = open(fullpath, O_RDONLY);
1518                 if (fd < 0) {
1519                         if (errno != ENOMEDIUM)
1520                                 fprintf(stderr, "failed to open %s: %s\n",
1521                                         fullpath, strerror(errno));
1522                         continue;
1523                 }
1524                 ret = btrfs_scan_one_device(fd, fullpath, &tmp_devices,
1525                                             &num_devices,
1526                                             BTRFS_SUPER_INFO_OFFSET);
1527                 if (ret == 0 && run_ioctl > 0) {
1528                         btrfs_register_one_device(fullpath);
1529                 }
1530                 close(fd);
1531         }
1532
1533         fclose(proc_partitions);
1534
1535         if (scans == 0) {
1536                 scans++;
1537                 goto scan_again;
1538         }
1539         return 0;
1540 }
1541
1542 /*
1543  * This function should be only used when parsing
1544  * command arg, it won't return error to it's
1545  * caller and rather exit directly just like usage().
1546  */
1547 u64 arg_strtou64(const char *str)
1548 {
1549         u64 value;
1550         char *ptr_parse_end = NULL;
1551
1552         value = strtoull(str, &ptr_parse_end, 0);
1553         if (ptr_parse_end && *ptr_parse_end != '\0') {
1554                 fprintf(stderr, "ERROR: %s is not a valid numeric value.\n",
1555                         str);
1556                 exit(1);
1557         }
1558         /*
1559          * if we pass a negative number to strtoull,
1560          * it will return an unexpected number to us,
1561          * so let's do the check ourselves.
1562          */
1563         if (str[0] == '-') {
1564                 fprintf(stderr, "ERROR: %s: negative value is invalid.\n",
1565                         str);
1566                 exit(1);
1567         }
1568         if (value == ULLONG_MAX) {
1569                 fprintf(stderr, "ERROR: %s is too large.\n", str);
1570                 exit(1);
1571         }
1572         return value;
1573 }
1574
1575 u64 parse_size(char *s)
1576 {
1577         int i;
1578         char c;
1579         u64 mult = 1;
1580
1581         for (i = 0; s && s[i] && isdigit(s[i]); i++) ;
1582         if (!i) {
1583                 fprintf(stderr, "ERROR: size value is empty\n");
1584                 exit(50);
1585         }
1586
1587         if (s[i]) {
1588                 c = tolower(s[i]);
1589                 switch (c) {
1590                 case 'e':
1591                         mult *= 1024;
1592                         /* fallthrough */
1593                 case 'p':
1594                         mult *= 1024;
1595                         /* fallthrough */
1596                 case 't':
1597                         mult *= 1024;
1598                         /* fallthrough */
1599                 case 'g':
1600                         mult *= 1024;
1601                         /* fallthrough */
1602                 case 'm':
1603                         mult *= 1024;
1604                         /* fallthrough */
1605                 case 'k':
1606                         mult *= 1024;
1607                         /* fallthrough */
1608                 case 'b':
1609                         break;
1610                 default:
1611                         fprintf(stderr, "ERROR: Unknown size descriptor "
1612                                 "'%c'\n", c);
1613                         exit(1);
1614                 }
1615         }
1616         if (s[i] && s[i+1]) {
1617                 fprintf(stderr, "ERROR: Illegal suffix contains "
1618                         "character '%c' in wrong position\n",
1619                         s[i+1]);
1620                 exit(51);
1621         }
1622         return strtoull(s, NULL, 10) * mult;
1623 }
1624
1625 int open_file_or_dir3(const char *fname, DIR **dirstream, int open_flags)
1626 {
1627         int ret;
1628         struct stat st;
1629         int fd;
1630
1631         ret = stat(fname, &st);
1632         if (ret < 0) {
1633                 return -1;
1634         }
1635         if (S_ISDIR(st.st_mode)) {
1636                 *dirstream = opendir(fname);
1637                 if (!*dirstream)
1638                         return -1;
1639                 fd = dirfd(*dirstream);
1640         } else if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
1641                 fd = open(fname, open_flags);
1642         } else {
1643                 /*
1644                  * we set this on purpose, in case the caller output
1645                  * strerror(errno) as success
1646                  */
1647                 errno = EINVAL;
1648                 return -1;
1649         }
1650         if (fd < 0) {
1651                 fd = -1;
1652                 if (*dirstream)
1653                         closedir(*dirstream);
1654         }
1655         return fd;
1656 }
1657
1658 int open_file_or_dir(const char *fname, DIR **dirstream)
1659 {
1660         return open_file_or_dir3(fname, dirstream, O_RDWR);
1661 }
1662
1663 void close_file_or_dir(int fd, DIR *dirstream)
1664 {
1665         if (dirstream)
1666                 closedir(dirstream);
1667         else if (fd >= 0)
1668                 close(fd);
1669 }
1670
1671 int get_device_info(int fd, u64 devid,
1672                 struct btrfs_ioctl_dev_info_args *di_args)
1673 {
1674         int ret;
1675
1676         di_args->devid = devid;
1677         memset(&di_args->uuid, '\0', sizeof(di_args->uuid));
1678
1679         ret = ioctl(fd, BTRFS_IOC_DEV_INFO, di_args);
1680         return ret ? -errno : 0;
1681 }
1682
1683 /*
1684  * For a given path, fill in the ioctl fs_ and info_ args.
1685  * If the path is a btrfs mountpoint, fill info for all devices.
1686  * If the path is a btrfs device, fill in only that device.
1687  *
1688  * The path provided must be either on a mounted btrfs fs,
1689  * or be a mounted btrfs device.
1690  *
1691  * Returns 0 on success, or a negative errno.
1692  */
1693 int get_fs_info(char *path, struct btrfs_ioctl_fs_info_args *fi_args,
1694                 struct btrfs_ioctl_dev_info_args **di_ret)
1695 {
1696         int fd = -1;
1697         int ret = 0;
1698         int ndevs = 0;
1699         int i = 0;
1700         struct btrfs_fs_devices *fs_devices_mnt = NULL;
1701         struct btrfs_ioctl_dev_info_args *di_args;
1702         char mp[BTRFS_PATH_NAME_MAX + 1];
1703         DIR *dirstream = NULL;
1704
1705         memset(fi_args, 0, sizeof(*fi_args));
1706
1707         if (is_block_device(path)) {
1708                 struct btrfs_super_block *disk_super;
1709                 char buf[BTRFS_SUPER_INFO_SIZE];
1710                 u64 devid;
1711
1712                 /* Ensure it's mounted, then set path to the mountpoint */
1713                 fd = open(path, O_RDONLY);
1714                 if (fd < 0) {
1715                         ret = -errno;
1716                         fprintf(stderr, "Couldn't open %s: %s\n",
1717                                 path, strerror(errno));
1718                         goto out;
1719                 }
1720                 ret = check_mounted_where(fd, path, mp, sizeof(mp),
1721                                           &fs_devices_mnt);
1722                 if (!ret) {
1723                         ret = -EINVAL;
1724                         goto out;
1725                 }
1726                 if (ret < 0)
1727                         goto out;
1728                 path = mp;
1729                 /* Only fill in this one device */
1730                 fi_args->num_devices = 1;
1731
1732                 disk_super = (struct btrfs_super_block *)buf;
1733                 ret = btrfs_read_dev_super(fd, disk_super, BTRFS_SUPER_INFO_OFFSET);
1734                 if (ret < 0) {
1735                         ret = -EIO;
1736                         goto out;
1737                 }
1738                 devid = btrfs_stack_device_id(&disk_super->dev_item);
1739
1740                 fi_args->max_id = devid;
1741                 i = devid;
1742
1743                 memcpy(fi_args->fsid, fs_devices_mnt->fsid, BTRFS_FSID_SIZE);
1744                 close(fd);
1745         }
1746
1747         /* at this point path must not be for a block device */
1748         fd = open_file_or_dir(path, &dirstream);
1749         if (fd < 0) {
1750                 ret = -errno;
1751                 goto out;
1752         }
1753
1754         /* fill in fi_args if not just a single device */
1755         if (fi_args->num_devices != 1) {
1756                 ret = ioctl(fd, BTRFS_IOC_FS_INFO, fi_args);
1757                 if (ret < 0) {
1758                         ret = -errno;
1759                         goto out;
1760                 }
1761         }
1762
1763         if (!fi_args->num_devices)
1764                 goto out;
1765
1766         di_args = *di_ret = malloc(fi_args->num_devices * sizeof(*di_args));
1767         if (!di_args) {
1768                 ret = -errno;
1769                 goto out;
1770         }
1771
1772         for (; i <= fi_args->max_id; ++i) {
1773                 BUG_ON(ndevs >= fi_args->num_devices);
1774                 ret = get_device_info(fd, i, &di_args[ndevs]);
1775                 if (ret == -ENODEV)
1776                         continue;
1777                 if (ret)
1778                         goto out;
1779                 ndevs++;
1780         }
1781
1782         /*
1783         * only when the only dev we wanted to find is not there then
1784         * let any error be returned
1785         */
1786         if (fi_args->num_devices != 1) {
1787                 BUG_ON(ndevs == 0);
1788                 ret = 0;
1789         }
1790
1791 out:
1792         close_file_or_dir(fd, dirstream);
1793         return ret;
1794 }
1795
1796 #define isoctal(c)      (((c) & ~7) == '0')
1797
1798 static inline void translate(char *f, char *t)
1799 {
1800         while (*f != '\0') {
1801                 if (*f == '\\' &&
1802                     isoctal(f[1]) && isoctal(f[2]) && isoctal(f[3])) {
1803                         *t++ = 64*(f[1] & 7) + 8*(f[2] & 7) + (f[3] & 7);
1804                         f += 4;
1805                 } else
1806                         *t++ = *f++;
1807         }
1808         *t = '\0';
1809         return;
1810 }
1811
1812 /*
1813  * Checks if the swap device.
1814  * Returns 1 if swap device, < 0 on error or 0 if not swap device.
1815  */
1816 static int is_swap_device(const char *file)
1817 {
1818         FILE    *f;
1819         struct stat     st_buf;
1820         dev_t   dev;
1821         ino_t   ino = 0;
1822         char    tmp[PATH_MAX];
1823         char    buf[PATH_MAX];
1824         char    *cp;
1825         int     ret = 0;
1826
1827         if (stat(file, &st_buf) < 0)
1828                 return -errno;
1829         if (S_ISBLK(st_buf.st_mode))
1830                 dev = st_buf.st_rdev;
1831         else if (S_ISREG(st_buf.st_mode)) {
1832                 dev = st_buf.st_dev;
1833                 ino = st_buf.st_ino;
1834         } else
1835                 return 0;
1836
1837         if ((f = fopen("/proc/swaps", "r")) == NULL)
1838                 return 0;
1839
1840         /* skip the first line */
1841         if (fgets(tmp, sizeof(tmp), f) == NULL)
1842                 goto out;
1843
1844         while (fgets(tmp, sizeof(tmp), f) != NULL) {
1845                 if ((cp = strchr(tmp, ' ')) != NULL)
1846                         *cp = '\0';
1847                 if ((cp = strchr(tmp, '\t')) != NULL)
1848                         *cp = '\0';
1849                 translate(tmp, buf);
1850                 if (stat(buf, &st_buf) != 0)
1851                         continue;
1852                 if (S_ISBLK(st_buf.st_mode)) {
1853                         if (dev == st_buf.st_rdev) {
1854                                 ret = 1;
1855                                 break;
1856                         }
1857                 } else if (S_ISREG(st_buf.st_mode)) {
1858                         if (dev == st_buf.st_dev && ino == st_buf.st_ino) {
1859                                 ret = 1;
1860                                 break;
1861                         }
1862                 }
1863         }
1864
1865 out:
1866         fclose(f);
1867
1868         return ret;
1869 }
1870
1871 /*
1872  * Check for existing filesystem or partition table on device.
1873  * Returns:
1874  *       1 for existing fs or partition
1875  *       0 for nothing found
1876  *      -1 for internal error
1877  */
1878 static int
1879 check_overwrite(
1880         char            *device)
1881 {
1882         const char      *type;
1883         blkid_probe     pr = NULL;
1884         int             ret;
1885         blkid_loff_t    size;
1886
1887         if (!device || !*device)
1888                 return 0;
1889
1890         ret = -1; /* will reset on success of all setup calls */
1891
1892         pr = blkid_new_probe_from_filename(device);
1893         if (!pr)
1894                 goto out;
1895
1896         size = blkid_probe_get_size(pr);
1897         if (size < 0)
1898                 goto out;
1899
1900         /* nothing to overwrite on a 0-length device */
1901         if (size == 0) {
1902                 ret = 0;
1903                 goto out;
1904         }
1905
1906         ret = blkid_probe_enable_partitions(pr, 1);
1907         if (ret < 0)
1908                 goto out;
1909
1910         ret = blkid_do_fullprobe(pr);
1911         if (ret < 0)
1912                 goto out;
1913
1914         /*
1915          * Blkid returns 1 for nothing found and 0 when it finds a signature,
1916          * but we want the exact opposite, so reverse the return value here.
1917          *
1918          * In addition print some useful diagnostics about what actually is
1919          * on the device.
1920          */
1921         if (ret) {
1922                 ret = 0;
1923                 goto out;
1924         }
1925
1926         if (!blkid_probe_lookup_value(pr, "TYPE", &type, NULL)) {
1927                 fprintf(stderr,
1928                         "%s appears to contain an existing "
1929                         "filesystem (%s).\n", device, type);
1930         } else if (!blkid_probe_lookup_value(pr, "PTTYPE", &type, NULL)) {
1931                 fprintf(stderr,
1932                         "%s appears to contain a partition "
1933                         "table (%s).\n", device, type);
1934         } else {
1935                 fprintf(stderr,
1936                         "%s appears to contain something weird "
1937                         "according to blkid\n", device);
1938         }
1939         ret = 1;
1940
1941 out:
1942         if (pr)
1943                 blkid_free_probe(pr);
1944         if (ret == -1)
1945                 fprintf(stderr,
1946                         "probe of %s failed, cannot detect "
1947                           "existing filesystem.\n", device);
1948         return ret;
1949 }
1950
1951 int test_num_disk_vs_raid(u64 metadata_profile, u64 data_profile,
1952         u64 dev_cnt, int mixed, char *estr)
1953 {
1954         size_t sz = 100;
1955         u64 allowed = 0;
1956
1957         switch (dev_cnt) {
1958         default:
1959         case 4:
1960                 allowed |= BTRFS_BLOCK_GROUP_RAID10;
1961         case 3:
1962                 allowed |= BTRFS_BLOCK_GROUP_RAID6;
1963         case 2:
1964                 allowed |= BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
1965                         BTRFS_BLOCK_GROUP_RAID5;
1966                 break;
1967         case 1:
1968                 allowed |= BTRFS_BLOCK_GROUP_DUP;
1969         }
1970
1971         if (metadata_profile & ~allowed) {
1972                 snprintf(estr, sz, "unable to create FS with metadata "
1973                         "profile %llu (have %llu devices)\n",
1974                         metadata_profile, dev_cnt);
1975                 return 1;
1976         }
1977         if (data_profile & ~allowed) {
1978                 snprintf(estr, sz, "unable to create FS with data "
1979                         "profile %llu (have %llu devices)\n",
1980                         metadata_profile, dev_cnt);
1981                 return 1;
1982         }
1983
1984         if (!mixed && (data_profile & BTRFS_BLOCK_GROUP_DUP)) {
1985                 snprintf(estr, sz,
1986                         "dup for data is allowed only in mixed mode");
1987                 return 1;
1988         }
1989         return 0;
1990 }
1991
1992 /* Check if disk is suitable for btrfs
1993  * returns:
1994  *  1: something is wrong, estr provides the error
1995  *  0: all is fine
1996  */
1997 int test_dev_for_mkfs(char *file, int force_overwrite, char *estr)
1998 {
1999         int ret, fd;
2000         size_t sz = 100;
2001         struct stat st;
2002
2003         ret = is_swap_device(file);
2004         if (ret < 0) {
2005                 snprintf(estr, sz, "error checking %s status: %s\n", file,
2006                         strerror(-ret));
2007                 return 1;
2008         }
2009         if (ret == 1) {
2010                 snprintf(estr, sz, "%s is a swap device\n", file);
2011                 return 1;
2012         }
2013         if (!force_overwrite) {
2014                 if (check_overwrite(file)) {
2015                         snprintf(estr, sz, "Use the -f option to force overwrite.\n");
2016                         return 1;
2017                 }
2018         }
2019         ret = check_mounted(file);
2020         if (ret < 0) {
2021                 snprintf(estr, sz, "error checking %s mount status\n",
2022                         file);
2023                 return 1;
2024         }
2025         if (ret == 1) {
2026                 snprintf(estr, sz, "%s is mounted\n", file);
2027                 return 1;
2028         }
2029         /* check if the device is busy */
2030         fd = open(file, O_RDWR|O_EXCL);
2031         if (fd < 0) {
2032                 snprintf(estr, sz, "unable to open %s: %s\n", file,
2033                         strerror(errno));
2034                 return 1;
2035         }
2036         if (fstat(fd, &st)) {
2037                 snprintf(estr, sz, "unable to stat %s: %s\n", file,
2038                         strerror(errno));
2039                 close(fd);
2040                 return 1;
2041         }
2042         if (!S_ISBLK(st.st_mode)) {
2043                 fprintf(stderr, "'%s' is not a block device\n", file);
2044                 close(fd);
2045                 return 1;
2046         }
2047         close(fd);
2048         return 0;
2049 }
2050
2051 int btrfs_scan_lblkid(int update_kernel)
2052 {
2053         int fd = -1;
2054         int ret;
2055         u64 num_devices;
2056         struct btrfs_fs_devices *tmp_devices;
2057         blkid_dev_iterate iter = NULL;
2058         blkid_dev dev = NULL;
2059         blkid_cache cache = NULL;
2060         char path[PATH_MAX];
2061
2062         if (blkid_get_cache(&cache, 0) < 0) {
2063                 printf("ERROR: lblkid cache get failed\n");
2064                 return 1;
2065         }
2066         blkid_probe_all(cache);
2067         iter = blkid_dev_iterate_begin(cache);
2068         blkid_dev_set_search(iter, "TYPE", "btrfs");
2069         while (blkid_dev_next(iter, &dev) == 0) {
2070                 dev = blkid_verify(cache, dev);
2071                 if (!dev)
2072                         continue;
2073                 /* if we are here its definitely a btrfs disk*/
2074                 strncpy(path, blkid_dev_devname(dev), PATH_MAX);
2075
2076                 fd = open(path, O_RDONLY);
2077                 if (fd < 0) {
2078                         printf("ERROR: could not open %s\n", path);
2079                         continue;
2080                 }
2081                 ret = btrfs_scan_one_device(fd, path, &tmp_devices,
2082                                 &num_devices, BTRFS_SUPER_INFO_OFFSET);
2083                 if (ret) {
2084                         printf("ERROR: could not scan %s\n", path);
2085                         close (fd);
2086                         continue;
2087                 }
2088
2089                 close(fd);
2090                 if (update_kernel)
2091                         btrfs_register_one_device(path);
2092         }
2093         blkid_dev_iterate_end(iter);
2094         blkid_put_cache(cache);
2095         return 0;
2096 }
2097
2098 /*
2099  * scans devs for the btrfs
2100 */
2101 int scan_for_btrfs(int where, int update_kernel)
2102 {
2103         int ret = 0;
2104
2105         switch (where) {
2106         case BTRFS_SCAN_PROC:
2107                 ret = btrfs_scan_block_devices(update_kernel);
2108                 break;
2109         case BTRFS_SCAN_DEV:
2110                 ret = btrfs_scan_one_dir("/dev", update_kernel);
2111                 break;
2112         case BTRFS_SCAN_LBLKID:
2113                 ret = btrfs_scan_lblkid(update_kernel);
2114                 break;
2115         }
2116         return ret;
2117 }
2118
2119 int is_vol_small(char *file)
2120 {
2121         int fd = -1;
2122         int e;
2123         struct stat st;
2124         u64 size;
2125
2126         fd = open(file, O_RDONLY);
2127         if (fd < 0)
2128                 return -errno;
2129         if (fstat(fd, &st) < 0) {
2130                 e = -errno;
2131                 close(fd);
2132                 return e;
2133         }
2134         size = btrfs_device_size(fd, &st);
2135         if (size == 0) {
2136                 close(fd);
2137                 return -1;
2138         }
2139         if (size < 1024 * 1024 * 1024) {
2140                 close(fd);
2141                 return 1;
2142         } else {
2143                 close(fd);
2144                 return 0;
2145         }
2146 }
2147
2148 /*
2149  * This reads a line from the stdin and only returns non-zero if the
2150  * first whitespace delimited token is a case insensitive match with yes
2151  * or y.
2152  */
2153 int ask_user(char *question)
2154 {
2155         char buf[30] = {0,};
2156         char *saveptr = NULL;
2157         char *answer;
2158
2159         printf("%s [y/N]: ", question);
2160
2161         return fgets(buf, sizeof(buf) - 1, stdin) &&
2162                (answer = strtok_r(buf, " \t\n\r", &saveptr)) &&
2163                (!strcasecmp(answer, "yes") || !strcasecmp(answer, "y"));
2164 }
2165
2166 /*
2167  * For a given:
2168  * - file or directory return the containing tree root id
2169  * - subvolume return it's own tree id
2170  * - BTRFS_EMPTY_SUBVOL_DIR_OBJECTID (directory with ino == 2) the result is
2171  *   undefined and function returns -1
2172  */
2173 int lookup_ino_rootid(int fd, u64 *rootid)
2174 {
2175         struct btrfs_ioctl_ino_lookup_args args;
2176         int ret;
2177         int e;
2178
2179         memset(&args, 0, sizeof(args));
2180         args.treeid = 0;
2181         args.objectid = BTRFS_FIRST_FREE_OBJECTID;
2182
2183         ret = ioctl(fd, BTRFS_IOC_INO_LOOKUP, &args);
2184         e = errno;
2185         if (ret) {
2186                 fprintf(stderr, "ERROR: Failed to lookup root id - %s\n",
2187                         strerror(e));
2188                 return ret;
2189         }
2190
2191         *rootid = args.treeid;
2192
2193         return 0;
2194 }
2195
2196 int find_mount_root(const char *path, char **mount_root)
2197 {
2198         FILE *mnttab;
2199         int fd;
2200         struct mntent *ent;
2201         int len;
2202         int ret;
2203         int longest_matchlen = 0;
2204         char *longest_match = NULL;
2205
2206         fd = open(path, O_RDONLY | O_NOATIME);
2207         if (fd < 0)
2208                 return -errno;
2209         close(fd);
2210
2211         mnttab = setmntent("/proc/self/mounts", "r");
2212         if (!mnttab)
2213                 return -errno;
2214
2215         while ((ent = getmntent(mnttab))) {
2216                 len = strlen(ent->mnt_dir);
2217                 if (strncmp(ent->mnt_dir, path, len) == 0) {
2218                         /* match found */
2219                         if (longest_matchlen < len) {
2220                                 free(longest_match);
2221                                 longest_matchlen = len;
2222                                 longest_match = strdup(ent->mnt_dir);
2223                         }
2224                 }
2225         }
2226         endmntent(mnttab);
2227
2228         if (!longest_match) {
2229                 fprintf(stderr,
2230                         "ERROR: Failed to find mount root for path %s.\n",
2231                         path);
2232                 return -ENOENT;
2233         }
2234
2235         ret = 0;
2236         *mount_root = realpath(longest_match, NULL);
2237         if (!*mount_root)
2238                 ret = -errno;
2239
2240         free(longest_match);
2241         return ret;
2242 }