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