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