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