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