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