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