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