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