btrfs-progs: print fs features filtered by a mask
[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_process_fs_features(u64 flags)
597 {
598         int i;
599
600         for (i = 0; i < ARRAY_SIZE(mkfs_features); i++) {
601                 if (flags & mkfs_features[i].flag) {
602                         printf("Turning ON incompat feature '%s': %s\n",
603                                 mkfs_features[i].name,
604                                 mkfs_features[i].desc);
605                 }
606         }
607 }
608
609 void btrfs_list_all_fs_features(u64 mask_disallowed)
610 {
611         int i;
612
613         fprintf(stderr, "Filesystem features available:\n");
614         for (i = 0; i < ARRAY_SIZE(mkfs_features) - 1; i++) {
615                 char *is_default = "";
616
617                 if (mkfs_features[i].flag & mask_disallowed)
618                         continue;
619                 if (mkfs_features[i].flag & BTRFS_MKFS_DEFAULT_FEATURES)
620                         is_default = ", default";
621                 fprintf(stderr, "%-20s- %s (0x%llx%s)\n",
622                                 mkfs_features[i].name,
623                                 mkfs_features[i].desc,
624                                 mkfs_features[i].flag,
625                                 is_default);
626         }
627 }
628
629 /*
630  * Return NULL if all features were parsed fine, otherwise return the name of
631  * the first unparsed.
632  */
633 char* btrfs_parse_fs_features(char *namelist, u64 *flags)
634 {
635         char *this_char;
636         char *save_ptr = NULL; /* Satisfy static checkers */
637
638         for (this_char = strtok_r(namelist, ",", &save_ptr);
639              this_char != NULL;
640              this_char = strtok_r(NULL, ",", &save_ptr)) {
641                 if (parse_one_fs_feature(this_char, flags))
642                         return this_char;
643         }
644
645         return NULL;
646 }
647
648 u64 btrfs_device_size(int fd, struct stat *st)
649 {
650         u64 size;
651         if (S_ISREG(st->st_mode)) {
652                 return st->st_size;
653         }
654         if (!S_ISBLK(st->st_mode)) {
655                 return 0;
656         }
657         if (ioctl(fd, BLKGETSIZE64, &size) >= 0) {
658                 return size;
659         }
660         return 0;
661 }
662
663 static int zero_blocks(int fd, off_t start, size_t len)
664 {
665         char *buf = malloc(len);
666         int ret = 0;
667         ssize_t written;
668
669         if (!buf)
670                 return -ENOMEM;
671         memset(buf, 0, len);
672         written = pwrite(fd, buf, len, start);
673         if (written != len)
674                 ret = -EIO;
675         free(buf);
676         return ret;
677 }
678
679 #define ZERO_DEV_BYTES (2 * 1024 * 1024)
680
681 /* don't write outside the device by clamping the region to the device size */
682 static int zero_dev_clamped(int fd, off_t start, ssize_t len, u64 dev_size)
683 {
684         off_t end = max(start, start + len);
685
686 #ifdef __sparc__
687         /* and don't overwrite the disk labels on sparc */
688         start = max(start, 1024);
689         end = max(end, 1024);
690 #endif
691
692         start = min_t(u64, start, dev_size);
693         end = min_t(u64, end, dev_size);
694
695         return zero_blocks(fd, start, end - start);
696 }
697
698 int btrfs_add_to_fsid(struct btrfs_trans_handle *trans,
699                       struct btrfs_root *root, int fd, char *path,
700                       u64 block_count, u32 io_width, u32 io_align,
701                       u32 sectorsize)
702 {
703         struct btrfs_super_block *disk_super;
704         struct btrfs_super_block *super = root->fs_info->super_copy;
705         struct btrfs_device *device;
706         struct btrfs_dev_item *dev_item;
707         char *buf;
708         u64 total_bytes;
709         u64 num_devs;
710         int ret;
711
712         device = kzalloc(sizeof(*device), GFP_NOFS);
713         if (!device)
714                 return -ENOMEM;
715         buf = kmalloc(sectorsize, GFP_NOFS);
716         if (!buf) {
717                 kfree(device);
718                 return -ENOMEM;
719         }
720         BUG_ON(sizeof(*disk_super) > sectorsize);
721         memset(buf, 0, sectorsize);
722
723         disk_super = (struct btrfs_super_block *)buf;
724         dev_item = &disk_super->dev_item;
725
726         uuid_generate(device->uuid);
727         device->devid = 0;
728         device->type = 0;
729         device->io_width = io_width;
730         device->io_align = io_align;
731         device->sector_size = sectorsize;
732         device->fd = fd;
733         device->writeable = 1;
734         device->total_bytes = block_count;
735         device->bytes_used = 0;
736         device->total_ios = 0;
737         device->dev_root = root->fs_info->dev_root;
738
739         ret = btrfs_add_device(trans, root, device);
740         BUG_ON(ret);
741
742         total_bytes = btrfs_super_total_bytes(super) + block_count;
743         btrfs_set_super_total_bytes(super, total_bytes);
744
745         num_devs = btrfs_super_num_devices(super) + 1;
746         btrfs_set_super_num_devices(super, num_devs);
747
748         memcpy(disk_super, super, sizeof(*disk_super));
749
750         printf("adding device %s id %llu\n", path,
751                (unsigned long long)device->devid);
752
753         btrfs_set_super_bytenr(disk_super, BTRFS_SUPER_INFO_OFFSET);
754         btrfs_set_stack_device_id(dev_item, device->devid);
755         btrfs_set_stack_device_type(dev_item, device->type);
756         btrfs_set_stack_device_io_align(dev_item, device->io_align);
757         btrfs_set_stack_device_io_width(dev_item, device->io_width);
758         btrfs_set_stack_device_sector_size(dev_item, device->sector_size);
759         btrfs_set_stack_device_total_bytes(dev_item, device->total_bytes);
760         btrfs_set_stack_device_bytes_used(dev_item, device->bytes_used);
761         memcpy(&dev_item->uuid, device->uuid, BTRFS_UUID_SIZE);
762
763         ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
764         BUG_ON(ret != sectorsize);
765
766         kfree(buf);
767         list_add(&device->dev_list, &root->fs_info->fs_devices->devices);
768         device->fs_devices = root->fs_info->fs_devices;
769         return 0;
770 }
771
772 static void btrfs_wipe_existing_sb(int fd)
773 {
774         const char *off = NULL;
775         size_t len = 0;
776         loff_t offset;
777         char buf[BUFSIZ];
778         int rc = 0;
779         blkid_probe pr = NULL;
780
781         pr = blkid_new_probe();
782         if (!pr)
783                 return;
784
785         if (blkid_probe_set_device(pr, fd, 0, 0))
786                 goto out;
787
788         rc = blkid_probe_lookup_value(pr, "SBMAGIC_OFFSET", &off, NULL);
789         if (!rc)
790                 rc = blkid_probe_lookup_value(pr, "SBMAGIC", NULL, &len);
791
792         if (rc || len == 0 || off == NULL)
793                 goto out;
794
795         offset = strtoll(off, NULL, 10);
796         if (len > sizeof(buf))
797                 len = sizeof(buf);
798
799         memset(buf, 0, len);
800         rc = pwrite(fd, buf, len, offset);
801         fsync(fd);
802
803 out:
804         blkid_free_probe(pr);
805         return;
806 }
807
808 int btrfs_prepare_device(int fd, char *file, int zero_end, u64 *block_count_ret,
809                            u64 max_block_count, int *mixed, int discard)
810 {
811         u64 block_count;
812         struct stat st;
813         int i, ret;
814
815         ret = fstat(fd, &st);
816         if (ret < 0) {
817                 fprintf(stderr, "unable to stat %s\n", file);
818                 return 1;
819         }
820
821         block_count = btrfs_device_size(fd, &st);
822         if (block_count == 0) {
823                 fprintf(stderr, "unable to find %s size\n", file);
824                 return 1;
825         }
826         if (max_block_count)
827                 block_count = min(block_count, max_block_count);
828
829         if (block_count < BTRFS_MKFS_SMALL_VOLUME_SIZE && !(*mixed))
830                 *mixed = 1;
831
832         if (discard) {
833                 /*
834                  * We intentionally ignore errors from the discard ioctl.  It
835                  * is not necessary for the mkfs functionality but just an
836                  * optimization.
837                  */
838                 if (discard_range(fd, 0, 0) == 0) {
839                         printf("Performing full device TRIM (%s) ...\n",
840                                 pretty_size(block_count));
841                         discard_blocks(fd, 0, block_count);
842                 }
843         }
844
845         ret = zero_dev_clamped(fd, 0, ZERO_DEV_BYTES, block_count);
846         for (i = 0 ; !ret && i < BTRFS_SUPER_MIRROR_MAX; i++)
847                 ret = zero_dev_clamped(fd, btrfs_sb_offset(i),
848                                        BTRFS_SUPER_INFO_SIZE, block_count);
849         if (!ret && zero_end)
850                 ret = zero_dev_clamped(fd, block_count - ZERO_DEV_BYTES,
851                                        ZERO_DEV_BYTES, block_count);
852
853         if (ret < 0) {
854                 fprintf(stderr, "ERROR: failed to zero device '%s' - %s\n",
855                         file, strerror(-ret));
856                 return 1;
857         }
858
859         btrfs_wipe_existing_sb(fd);
860
861         *block_count_ret = block_count;
862         return 0;
863 }
864
865 int btrfs_make_root_dir(struct btrfs_trans_handle *trans,
866                         struct btrfs_root *root, u64 objectid)
867 {
868         int ret;
869         struct btrfs_inode_item inode_item;
870         time_t now = time(NULL);
871
872         memset(&inode_item, 0, sizeof(inode_item));
873         btrfs_set_stack_inode_generation(&inode_item, trans->transid);
874         btrfs_set_stack_inode_size(&inode_item, 0);
875         btrfs_set_stack_inode_nlink(&inode_item, 1);
876         btrfs_set_stack_inode_nbytes(&inode_item, root->nodesize);
877         btrfs_set_stack_inode_mode(&inode_item, S_IFDIR | 0755);
878         btrfs_set_stack_timespec_sec(&inode_item.atime, now);
879         btrfs_set_stack_timespec_nsec(&inode_item.atime, 0);
880         btrfs_set_stack_timespec_sec(&inode_item.ctime, now);
881         btrfs_set_stack_timespec_nsec(&inode_item.ctime, 0);
882         btrfs_set_stack_timespec_sec(&inode_item.mtime, now);
883         btrfs_set_stack_timespec_nsec(&inode_item.mtime, 0);
884         btrfs_set_stack_timespec_sec(&inode_item.otime, 0);
885         btrfs_set_stack_timespec_nsec(&inode_item.otime, 0);
886
887         if (root->fs_info->tree_root == root)
888                 btrfs_set_super_root_dir(root->fs_info->super_copy, objectid);
889
890         ret = btrfs_insert_inode(trans, root, objectid, &inode_item);
891         if (ret)
892                 goto error;
893
894         ret = btrfs_insert_inode_ref(trans, root, "..", 2, objectid, objectid, 0);
895         if (ret)
896                 goto error;
897
898         btrfs_set_root_dirid(&root->root_item, objectid);
899         ret = 0;
900 error:
901         return ret;
902 }
903
904 /*
905  * checks if a path is a block device node
906  * Returns negative errno on failure, otherwise
907  * returns 1 for blockdev, 0 for not-blockdev
908  */
909 int is_block_device(const char *path)
910 {
911         struct stat statbuf;
912
913         if (stat(path, &statbuf) < 0)
914                 return -errno;
915
916         return S_ISBLK(statbuf.st_mode);
917 }
918
919 /*
920  * check if given path is a mount point
921  * return 1 if yes. 0 if no. -1 for error
922  */
923 int is_mount_point(const char *path)
924 {
925         FILE *f;
926         struct mntent *mnt;
927         int ret = 0;
928
929         f = setmntent("/proc/self/mounts", "r");
930         if (f == NULL)
931                 return -1;
932
933         while ((mnt = getmntent(f)) != NULL) {
934                 if (strcmp(mnt->mnt_dir, path))
935                         continue;
936                 ret = 1;
937                 break;
938         }
939         endmntent(f);
940         return ret;
941 }
942
943 static int is_reg_file(const char *path)
944 {
945         struct stat statbuf;
946
947         if (stat(path, &statbuf) < 0)
948                 return -errno;
949         return S_ISREG(statbuf.st_mode);
950 }
951
952 /*
953  * This function checks if the given input parameter is
954  * an uuid or a path
955  * return <0 : some error in the given input
956  * return BTRFS_ARG_UNKNOWN:    unknown input
957  * return BTRFS_ARG_UUID:       given input is uuid
958  * return BTRFS_ARG_MNTPOINT:   given input is path
959  * return BTRFS_ARG_REG:        given input is regular file
960  */
961 int check_arg_type(const char *input)
962 {
963         uuid_t uuid;
964         char path[PATH_MAX];
965
966         if (!input)
967                 return -EINVAL;
968
969         if (realpath(input, path)) {
970                 if (is_block_device(path) == 1)
971                         return BTRFS_ARG_BLKDEV;
972
973                 if (is_mount_point(path) == 1)
974                         return BTRFS_ARG_MNTPOINT;
975
976                 if (is_reg_file(path))
977                         return BTRFS_ARG_REG;
978
979                 return BTRFS_ARG_UNKNOWN;
980         }
981
982         if (strlen(input) == (BTRFS_UUID_UNPARSED_SIZE - 1) &&
983                 !uuid_parse(input, uuid))
984                 return BTRFS_ARG_UUID;
985
986         return BTRFS_ARG_UNKNOWN;
987 }
988
989 /*
990  * Find the mount point for a mounted device.
991  * On success, returns 0 with mountpoint in *mp.
992  * On failure, returns -errno (not mounted yields -EINVAL)
993  * Is noisy on failures, expects to be given a mounted device.
994  */
995 int get_btrfs_mount(const char *dev, char *mp, size_t mp_size)
996 {
997         int ret;
998         int fd = -1;
999
1000         ret = is_block_device(dev);
1001         if (ret <= 0) {
1002                 if (!ret) {
1003                         fprintf(stderr, "%s is not a block device\n", dev);
1004                         ret = -EINVAL;
1005                 } else {
1006                         fprintf(stderr, "Could not check %s: %s\n",
1007                                 dev, strerror(-ret));
1008                 }
1009                 goto out;
1010         }
1011
1012         fd = open(dev, O_RDONLY);
1013         if (fd < 0) {
1014                 ret = -errno;
1015                 fprintf(stderr, "Could not open %s: %s\n", dev, strerror(errno));
1016                 goto out;
1017         }
1018
1019         ret = check_mounted_where(fd, dev, mp, mp_size, NULL);
1020         if (!ret) {
1021                 ret = -EINVAL;
1022         } else { /* mounted, all good */
1023                 ret = 0;
1024         }
1025 out:
1026         if (fd != -1)
1027                 close(fd);
1028         return ret;
1029 }
1030
1031 /*
1032  * Given a pathname, return a filehandle to:
1033  *      the original pathname or,
1034  *      if the pathname is a mounted btrfs device, to its mountpoint.
1035  *
1036  * On error, return -1, errno should be set.
1037  */
1038 int open_path_or_dev_mnt(const char *path, DIR **dirstream)
1039 {
1040         char mp[BTRFS_PATH_NAME_MAX + 1];
1041         int fdmnt;
1042
1043         if (is_block_device(path)) {
1044                 int ret;
1045
1046                 ret = get_btrfs_mount(path, mp, sizeof(mp));
1047                 if (ret < 0) {
1048                         /* not a mounted btrfs dev */
1049                         errno = EINVAL;
1050                         return -1;
1051                 }
1052                 fdmnt = open_file_or_dir(mp, dirstream);
1053         } else {
1054                 fdmnt = open_file_or_dir(path, dirstream);
1055         }
1056
1057         return fdmnt;
1058 }
1059
1060 /* checks if a device is a loop device */
1061 static int is_loop_device (const char* device) {
1062         struct stat statbuf;
1063
1064         if(stat(device, &statbuf) < 0)
1065                 return -errno;
1066
1067         return (S_ISBLK(statbuf.st_mode) &&
1068                 MAJOR(statbuf.st_rdev) == LOOP_MAJOR);
1069 }
1070
1071
1072 /* Takes a loop device path (e.g. /dev/loop0) and returns
1073  * the associated file (e.g. /images/my_btrfs.img) */
1074 static int resolve_loop_device(const char* loop_dev, char* loop_file,
1075                 int max_len)
1076 {
1077         int ret;
1078         FILE *f;
1079         char fmt[20];
1080         char p[PATH_MAX];
1081         char real_loop_dev[PATH_MAX];
1082
1083         if (!realpath(loop_dev, real_loop_dev))
1084                 return -errno;
1085         snprintf(p, PATH_MAX, "/sys/block/%s/loop/backing_file", strrchr(real_loop_dev, '/'));
1086         if (!(f = fopen(p, "r")))
1087                 return -errno;
1088
1089         snprintf(fmt, 20, "%%%i[^\n]", max_len-1);
1090         ret = fscanf(f, fmt, loop_file);
1091         fclose(f);
1092         if (ret == EOF)
1093                 return -errno;
1094
1095         return 0;
1096 }
1097
1098 /*
1099  * Checks whether a and b are identical or device
1100  * files associated with the same block device
1101  */
1102 static int is_same_blk_file(const char* a, const char* b)
1103 {
1104         struct stat st_buf_a, st_buf_b;
1105         char real_a[PATH_MAX];
1106         char real_b[PATH_MAX];
1107
1108         if (!realpath(a, real_a))
1109                 strncpy_null(real_a, a);
1110
1111         if (!realpath(b, real_b))
1112                 strncpy_null(real_b, b);
1113
1114         /* Identical path? */
1115         if (strcmp(real_a, real_b) == 0)
1116                 return 1;
1117
1118         if (stat(a, &st_buf_a) < 0 || stat(b, &st_buf_b) < 0) {
1119                 if (errno == ENOENT)
1120                         return 0;
1121                 return -errno;
1122         }
1123
1124         /* Same blockdevice? */
1125         if (S_ISBLK(st_buf_a.st_mode) && S_ISBLK(st_buf_b.st_mode) &&
1126             st_buf_a.st_rdev == st_buf_b.st_rdev) {
1127                 return 1;
1128         }
1129
1130         /* Hardlink? */
1131         if (st_buf_a.st_dev == st_buf_b.st_dev &&
1132             st_buf_a.st_ino == st_buf_b.st_ino) {
1133                 return 1;
1134         }
1135
1136         return 0;
1137 }
1138
1139 /* checks if a and b are identical or device
1140  * files associated with the same block device or
1141  * if one file is a loop device that uses the other
1142  * file.
1143  */
1144 static int is_same_loop_file(const char* a, const char* b)
1145 {
1146         char res_a[PATH_MAX];
1147         char res_b[PATH_MAX];
1148         const char* final_a = NULL;
1149         const char* final_b = NULL;
1150         int ret;
1151
1152         /* Resolve a if it is a loop device */
1153         if((ret = is_loop_device(a)) < 0) {
1154                 if (ret == -ENOENT)
1155                         return 0;
1156                 return ret;
1157         } else if (ret) {
1158                 ret = resolve_loop_device(a, res_a, sizeof(res_a));
1159                 if (ret < 0) {
1160                         if (errno != EPERM)
1161                                 return ret;
1162                 } else {
1163                         final_a = res_a;
1164                 }
1165         } else {
1166                 final_a = a;
1167         }
1168
1169         /* Resolve b if it is a loop device */
1170         if ((ret = is_loop_device(b)) < 0) {
1171                 if (ret == -ENOENT)
1172                         return 0;
1173                 return ret;
1174         } else if (ret) {
1175                 ret = resolve_loop_device(b, res_b, sizeof(res_b));
1176                 if (ret < 0) {
1177                         if (errno != EPERM)
1178                                 return ret;
1179                 } else {
1180                         final_b = res_b;
1181                 }
1182         } else {
1183                 final_b = b;
1184         }
1185
1186         return is_same_blk_file(final_a, final_b);
1187 }
1188
1189 /* Checks if a file exists and is a block or regular file*/
1190 static int is_existing_blk_or_reg_file(const char* filename)
1191 {
1192         struct stat st_buf;
1193
1194         if(stat(filename, &st_buf) < 0) {
1195                 if(errno == ENOENT)
1196                         return 0;
1197                 else
1198                         return -errno;
1199         }
1200
1201         return (S_ISBLK(st_buf.st_mode) || S_ISREG(st_buf.st_mode));
1202 }
1203
1204 /* Checks if a file is used (directly or indirectly via a loop device)
1205  * by a device in fs_devices
1206  */
1207 static int blk_file_in_dev_list(struct btrfs_fs_devices* fs_devices,
1208                 const char* file)
1209 {
1210         int ret;
1211         struct list_head *head;
1212         struct list_head *cur;
1213         struct btrfs_device *device;
1214
1215         head = &fs_devices->devices;
1216         list_for_each(cur, head) {
1217                 device = list_entry(cur, struct btrfs_device, dev_list);
1218
1219                 if((ret = is_same_loop_file(device->name, file)))
1220                         return ret;
1221         }
1222
1223         return 0;
1224 }
1225
1226 /*
1227  * Resolve a pathname to a device mapper node to /dev/mapper/<name>
1228  * Returns NULL on invalid input or malloc failure; Other failures
1229  * will be handled by the caller using the input pathame.
1230  */
1231 char *canonicalize_dm_name(const char *ptname)
1232 {
1233         FILE    *f;
1234         size_t  sz;
1235         char    path[PATH_MAX], name[PATH_MAX], *res = NULL;
1236
1237         if (!ptname || !*ptname)
1238                 return NULL;
1239
1240         snprintf(path, sizeof(path), "/sys/block/%s/dm/name", ptname);
1241         if (!(f = fopen(path, "r")))
1242                 return NULL;
1243
1244         /* read <name>\n from sysfs */
1245         if (fgets(name, sizeof(name), f) && (sz = strlen(name)) > 1) {
1246                 name[sz - 1] = '\0';
1247                 snprintf(path, sizeof(path), "/dev/mapper/%s", name);
1248
1249                 if (access(path, F_OK) == 0)
1250                         res = strdup(path);
1251         }
1252         fclose(f);
1253         return res;
1254 }
1255
1256 /*
1257  * Resolve a pathname to a canonical device node, e.g. /dev/sda1 or
1258  * to a device mapper pathname.
1259  * Returns NULL on invalid input or malloc failure; Other failures
1260  * will be handled by the caller using the input pathame.
1261  */
1262 char *canonicalize_path(const char *path)
1263 {
1264         char *canonical, *p;
1265
1266         if (!path || !*path)
1267                 return NULL;
1268
1269         canonical = realpath(path, NULL);
1270         if (!canonical)
1271                 return strdup(path);
1272         p = strrchr(canonical, '/');
1273         if (p && strncmp(p, "/dm-", 4) == 0 && isdigit(*(p + 4))) {
1274                 char *dm = canonicalize_dm_name(p + 1);
1275
1276                 if (dm) {
1277                         free(canonical);
1278                         return dm;
1279                 }
1280         }
1281         return canonical;
1282 }
1283
1284 /*
1285  * returns 1 if the device was mounted, < 0 on error or 0 if everything
1286  * is safe to continue.
1287  */
1288 int check_mounted(const char* file)
1289 {
1290         int fd;
1291         int ret;
1292
1293         fd = open(file, O_RDONLY);
1294         if (fd < 0) {
1295                 fprintf (stderr, "check_mounted(): Could not open %s\n", file);
1296                 return -errno;
1297         }
1298
1299         ret =  check_mounted_where(fd, file, NULL, 0, NULL);
1300         close(fd);
1301
1302         return ret;
1303 }
1304
1305 int check_mounted_where(int fd, const char *file, char *where, int size,
1306                         struct btrfs_fs_devices **fs_dev_ret)
1307 {
1308         int ret;
1309         u64 total_devs = 1;
1310         int is_btrfs;
1311         struct btrfs_fs_devices *fs_devices_mnt = NULL;
1312         FILE *f;
1313         struct mntent *mnt;
1314
1315         /* scan the initial device */
1316         ret = btrfs_scan_one_device(fd, file, &fs_devices_mnt,
1317                                     &total_devs, BTRFS_SUPER_INFO_OFFSET, 0);
1318         is_btrfs = (ret >= 0);
1319
1320         /* scan other devices */
1321         if (is_btrfs && total_devs > 1) {
1322                 ret = btrfs_scan_lblkid();
1323                 if (ret)
1324                         return ret;
1325         }
1326
1327         /* iterate over the list of currently mountes filesystems */
1328         if ((f = setmntent ("/proc/self/mounts", "r")) == NULL)
1329                 return -errno;
1330
1331         while ((mnt = getmntent (f)) != NULL) {
1332                 if(is_btrfs) {
1333                         if(strcmp(mnt->mnt_type, "btrfs") != 0)
1334                                 continue;
1335
1336                         ret = blk_file_in_dev_list(fs_devices_mnt, mnt->mnt_fsname);
1337                 } else {
1338                         /* ignore entries in the mount table that are not
1339                            associated with a file*/
1340                         if((ret = is_existing_blk_or_reg_file(mnt->mnt_fsname)) < 0)
1341                                 goto out_mntloop_err;
1342                         else if(!ret)
1343                                 continue;
1344
1345                         ret = is_same_loop_file(file, mnt->mnt_fsname);
1346                 }
1347
1348                 if(ret < 0)
1349                         goto out_mntloop_err;
1350                 else if(ret)
1351                         break;
1352         }
1353
1354         /* Did we find an entry in mnt table? */
1355         if (mnt && size && where) {
1356                 strncpy(where, mnt->mnt_dir, size);
1357                 where[size-1] = 0;
1358         }
1359         if (fs_dev_ret)
1360                 *fs_dev_ret = fs_devices_mnt;
1361
1362         ret = (mnt != NULL);
1363
1364 out_mntloop_err:
1365         endmntent (f);
1366
1367         return ret;
1368 }
1369
1370 struct pending_dir {
1371         struct list_head list;
1372         char name[PATH_MAX];
1373 };
1374
1375 int btrfs_register_one_device(const char *fname)
1376 {
1377         struct btrfs_ioctl_vol_args args;
1378         int fd;
1379         int ret;
1380         int e;
1381
1382         fd = open("/dev/btrfs-control", O_RDWR);
1383         if (fd < 0) {
1384                 fprintf(stderr, "failed to open /dev/btrfs-control "
1385                         "skipping device registration: %s\n",
1386                         strerror(errno));
1387                 return -errno;
1388         }
1389         strncpy(args.name, fname, BTRFS_PATH_NAME_MAX);
1390         args.name[BTRFS_PATH_NAME_MAX-1] = 0;
1391         ret = ioctl(fd, BTRFS_IOC_SCAN_DEV, &args);
1392         e = errno;
1393         if (ret < 0) {
1394                 fprintf(stderr, "ERROR: device scan failed '%s' - %s\n",
1395                         fname, strerror(e));
1396                 ret = -e;
1397         }
1398         close(fd);
1399         return ret;
1400 }
1401
1402 /*
1403  * Register all devices in the fs_uuid list created in the user
1404  * space. Ensure btrfs_scan_lblkid() is called before this func.
1405  */
1406 int btrfs_register_all_devices(void)
1407 {
1408         int err;
1409         struct btrfs_fs_devices *fs_devices;
1410         struct btrfs_device *device;
1411         struct list_head *all_uuids;
1412
1413         all_uuids = btrfs_scanned_uuids();
1414
1415         list_for_each_entry(fs_devices, all_uuids, list) {
1416                 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1417                         if (strlen(device->name) != 0) {
1418                                 err = btrfs_register_one_device(device->name);
1419                                 if (err < 0)
1420                                         return err;
1421                                 if (err > 0)
1422                                         return -err;
1423                         }
1424                 }
1425         }
1426         return 0;
1427 }
1428
1429 int btrfs_device_already_in_root(struct btrfs_root *root, int fd,
1430                                  int super_offset)
1431 {
1432         struct btrfs_super_block *disk_super;
1433         char *buf;
1434         int ret = 0;
1435
1436         buf = malloc(BTRFS_SUPER_INFO_SIZE);
1437         if (!buf) {
1438                 ret = -ENOMEM;
1439                 goto out;
1440         }
1441         ret = pread(fd, buf, BTRFS_SUPER_INFO_SIZE, super_offset);
1442         if (ret != BTRFS_SUPER_INFO_SIZE)
1443                 goto brelse;
1444
1445         ret = 0;
1446         disk_super = (struct btrfs_super_block *)buf;
1447         if (btrfs_super_magic(disk_super) != BTRFS_MAGIC)
1448                 goto brelse;
1449
1450         if (!memcmp(disk_super->fsid, root->fs_info->super_copy->fsid,
1451                     BTRFS_FSID_SIZE))
1452                 ret = 1;
1453 brelse:
1454         free(buf);
1455 out:
1456         return ret;
1457 }
1458
1459 static const char* unit_suffix_binary[] =
1460         { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"};
1461 static const char* unit_suffix_decimal[] =
1462         { "B", "kB", "MB", "GB", "TB", "PB", "EB"};
1463
1464 int pretty_size_snprintf(u64 size, char *str, size_t str_size, unsigned unit_mode)
1465 {
1466         int num_divs;
1467         float fraction;
1468         u64 base = 0;
1469         int mult = 0;
1470         const char** suffix = NULL;
1471         u64 last_size;
1472
1473         if (str_size == 0)
1474                 return 0;
1475
1476         if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_RAW) {
1477                 snprintf(str, str_size, "%llu", size);
1478                 return 0;
1479         }
1480
1481         if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_BINARY) {
1482                 base = 1024;
1483                 mult = 1024;
1484                 suffix = unit_suffix_binary;
1485         } else if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_DECIMAL) {
1486                 base = 1000;
1487                 mult = 1000;
1488                 suffix = unit_suffix_decimal;
1489         }
1490
1491         /* Unknown mode */
1492         if (!base) {
1493                 fprintf(stderr, "INTERNAL ERROR: unknown unit base, mode %d\n",
1494                                 unit_mode);
1495                 assert(0);
1496                 return -1;
1497         }
1498
1499         num_divs = 0;
1500         last_size = size;
1501         switch (unit_mode & UNITS_MODE_MASK) {
1502         case UNITS_TBYTES: base *= mult; num_divs++;
1503         case UNITS_GBYTES: base *= mult; num_divs++;
1504         case UNITS_MBYTES: base *= mult; num_divs++;
1505         case UNITS_KBYTES: num_divs++;
1506                            break;
1507         case UNITS_BYTES:
1508                            base = 1;
1509                            num_divs = 0;
1510                            break;
1511         default:
1512                 while (size >= mult) {
1513                         last_size = size;
1514                         size /= mult;
1515                         num_divs++;
1516                 }
1517         }
1518
1519         if (num_divs >= ARRAY_SIZE(unit_suffix_binary)) {
1520                 str[0] = '\0';
1521                 printf("INTERNAL ERROR: unsupported unit suffix, index %d\n",
1522                                 num_divs);
1523                 assert(0);
1524                 return -1;
1525         }
1526         fraction = (float)last_size / base;
1527
1528         return snprintf(str, str_size, "%.2f%s", fraction, suffix[num_divs]);
1529 }
1530
1531 /*
1532  * __strncpy__null - strncpy with null termination
1533  * @dest:       the target array
1534  * @src:        the source string
1535  * @n:          maximum bytes to copy (size of *dest)
1536  *
1537  * Like strncpy, but ensures destination is null-terminated.
1538  *
1539  * Copies the string pointed to by src, including the terminating null
1540  * byte ('\0'), to the buffer pointed to by dest, up to a maximum
1541  * of n bytes.  Then ensure that dest is null-terminated.
1542  */
1543 char *__strncpy__null(char *dest, const char *src, size_t n)
1544 {
1545         strncpy(dest, src, n);
1546         if (n > 0)
1547                 dest[n - 1] = '\0';
1548         return dest;
1549 }
1550
1551 /*
1552  * Checks to make sure that the label matches our requirements.
1553  * Returns:
1554        0    if everything is safe and usable
1555       -1    if the label is too long
1556  */
1557 static int check_label(const char *input)
1558 {
1559        int len = strlen(input);
1560
1561        if (len > BTRFS_LABEL_SIZE - 1) {
1562                 fprintf(stderr, "ERROR: Label %s is too long (max %d)\n",
1563                         input, BTRFS_LABEL_SIZE - 1);
1564                return -1;
1565        }
1566
1567        return 0;
1568 }
1569
1570 static int set_label_unmounted(const char *dev, const char *label)
1571 {
1572         struct btrfs_trans_handle *trans;
1573         struct btrfs_root *root;
1574         int ret;
1575
1576         ret = check_mounted(dev);
1577         if (ret < 0) {
1578                fprintf(stderr, "FATAL: error checking %s mount status\n", dev);
1579                return -1;
1580         }
1581         if (ret > 0) {
1582                 fprintf(stderr, "ERROR: dev %s is mounted, use mount point\n",
1583                         dev);
1584                 return -1;
1585         }
1586
1587         /* Open the super_block at the default location
1588          * and as read-write.
1589          */
1590         root = open_ctree(dev, 0, OPEN_CTREE_WRITES);
1591         if (!root) /* errors are printed by open_ctree() */
1592                 return -1;
1593
1594         trans = btrfs_start_transaction(root, 1);
1595         snprintf(root->fs_info->super_copy->label, BTRFS_LABEL_SIZE, "%s",
1596                  label);
1597         btrfs_commit_transaction(trans, root);
1598
1599         /* Now we close it since we are done. */
1600         close_ctree(root);
1601         return 0;
1602 }
1603
1604 static int set_label_mounted(const char *mount_path, const char *label)
1605 {
1606         int fd;
1607
1608         fd = open(mount_path, O_RDONLY | O_NOATIME);
1609         if (fd < 0) {
1610                 fprintf(stderr, "ERROR: unable to access '%s'\n", mount_path);
1611                 return -1;
1612         }
1613
1614         if (ioctl(fd, BTRFS_IOC_SET_FSLABEL, label) < 0) {
1615                 fprintf(stderr, "ERROR: unable to set label %s\n",
1616                         strerror(errno));
1617                 close(fd);
1618                 return -1;
1619         }
1620
1621         close(fd);
1622         return 0;
1623 }
1624
1625 static int get_label_unmounted(const char *dev, char *label)
1626 {
1627         struct btrfs_root *root;
1628         int ret;
1629
1630         ret = check_mounted(dev);
1631         if (ret < 0) {
1632                fprintf(stderr, "FATAL: error checking %s mount status\n", dev);
1633                return -1;
1634         }
1635         if (ret > 0) {
1636                 fprintf(stderr, "ERROR: dev %s is mounted, use mount point\n",
1637                         dev);
1638                 return -1;
1639         }
1640
1641         /* Open the super_block at the default location
1642          * and as read-only.
1643          */
1644         root = open_ctree(dev, 0, 0);
1645         if(!root)
1646                 return -1;
1647
1648         memcpy(label, root->fs_info->super_copy->label, BTRFS_LABEL_SIZE);
1649
1650         /* Now we close it since we are done. */
1651         close_ctree(root);
1652         return 0;
1653 }
1654
1655 /*
1656  * If a partition is mounted, try to get the filesystem label via its
1657  * mounted path rather than device.  Return the corresponding error
1658  * the user specified the device path.
1659  */
1660 int get_label_mounted(const char *mount_path, char *labelp)
1661 {
1662         char label[BTRFS_LABEL_SIZE];
1663         int fd;
1664
1665         fd = open(mount_path, O_RDONLY | O_NOATIME);
1666         if (fd < 0) {
1667                 fprintf(stderr, "ERROR: unable to access '%s'\n", mount_path);
1668                 return -1;
1669         }
1670
1671         memset(label, '\0', sizeof(label));
1672         if (ioctl(fd, BTRFS_IOC_GET_FSLABEL, label) < 0) {
1673                 fprintf(stderr, "ERROR: unable get label %s\n", strerror(errno));
1674                 close(fd);
1675                 return -1;
1676         }
1677
1678         strncpy(labelp, label, sizeof(label));
1679         close(fd);
1680         return 0;
1681 }
1682
1683 int get_label(const char *btrfs_dev, char *label)
1684 {
1685         int ret;
1686
1687         ret = is_existing_blk_or_reg_file(btrfs_dev);
1688         if (!ret)
1689                 ret = get_label_mounted(btrfs_dev, label);
1690         else if (ret > 0)
1691                 ret = get_label_unmounted(btrfs_dev, label);
1692
1693         return ret;
1694 }
1695
1696 int set_label(const char *btrfs_dev, const char *label)
1697 {
1698         int ret;
1699
1700         if (check_label(label))
1701                 return -1;
1702
1703         ret = is_existing_blk_or_reg_file(btrfs_dev);
1704         if (!ret)
1705                 ret = set_label_mounted(btrfs_dev, label);
1706         else if (ret > 0)
1707                 ret = set_label_unmounted(btrfs_dev, label);
1708
1709         return ret;
1710 }
1711
1712 int btrfs_scan_block_devices(int run_ioctl)
1713 {
1714
1715         struct stat st;
1716         int ret;
1717         int fd;
1718         struct btrfs_fs_devices *tmp_devices;
1719         u64 num_devices;
1720         FILE *proc_partitions;
1721         int i;
1722         char buf[1024];
1723         char fullpath[110];
1724         int scans = 0;
1725         int special;
1726
1727 scan_again:
1728         proc_partitions = fopen("/proc/partitions","r");
1729         if (!proc_partitions) {
1730                 fprintf(stderr, "Unable to open '/proc/partitions' for scanning\n");
1731                 return -ENOENT;
1732         }
1733         /* skip the header */
1734         for (i = 0; i < 2; i++)
1735                 if (!fgets(buf, 1023, proc_partitions)) {
1736                         fprintf(stderr,
1737                                 "Unable to read '/proc/partitions' for scanning\n");
1738                         fclose(proc_partitions);
1739                         return -ENOENT;
1740                 }
1741
1742         strcpy(fullpath,"/dev/");
1743         while(fgets(buf, 1023, proc_partitions)) {
1744                 ret = sscanf(buf," %*d %*d %*d %99s", fullpath + 5);
1745                 if (ret != 1) {
1746                         fprintf(stderr,
1747                                 "failed to scan device name from /proc/partitions\n");
1748                         break;
1749                 }
1750
1751                 /*
1752                  * multipath and MD devices may register as a btrfs filesystem
1753                  * both through the original block device and through
1754                  * the special (/dev/mapper or /dev/mdX) entry.
1755                  * This scans the special entries last
1756                  */
1757                 special = strncmp(fullpath, "/dev/dm-", strlen("/dev/dm-")) == 0;
1758                 if (!special)
1759                         special = strncmp(fullpath, "/dev/md", strlen("/dev/md")) == 0;
1760
1761                 if (scans == 0 && special)
1762                         continue;
1763                 if (scans > 0 && !special)
1764                         continue;
1765
1766                 ret = lstat(fullpath, &st);
1767                 if (ret < 0) {
1768                         fprintf(stderr, "failed to stat %s\n", fullpath);
1769                         continue;
1770                 }
1771                 if (!S_ISBLK(st.st_mode)) {
1772                         continue;
1773                 }
1774
1775                 fd = open(fullpath, O_RDONLY);
1776                 if (fd < 0) {
1777                         if (errno != ENOMEDIUM)
1778                                 fprintf(stderr, "failed to open %s: %s\n",
1779                                         fullpath, strerror(errno));
1780                         continue;
1781                 }
1782                 ret = btrfs_scan_one_device(fd, fullpath, &tmp_devices,
1783                                             &num_devices,
1784                                             BTRFS_SUPER_INFO_OFFSET, 0);
1785                 if (ret == 0 && run_ioctl > 0) {
1786                         btrfs_register_one_device(fullpath);
1787                 }
1788                 close(fd);
1789         }
1790
1791         fclose(proc_partitions);
1792
1793         if (scans == 0) {
1794                 scans++;
1795                 goto scan_again;
1796         }
1797         return 0;
1798 }
1799
1800 /*
1801  * Unsafe subvolume check.
1802  *
1803  * This only checks ino == BTRFS_FIRST_FREE_OBJECTID, even it is not in a
1804  * btrfs mount point.
1805  * Must use together with other reliable method like btrfs ioctl.
1806  */
1807 static int __is_subvol(const char *path)
1808 {
1809         struct stat st;
1810         int ret;
1811
1812         ret = lstat(path, &st);
1813         if (ret < 0)
1814                 return ret;
1815
1816         return st.st_ino == BTRFS_FIRST_FREE_OBJECTID;
1817 }
1818
1819 /*
1820  * A not-so-good version fls64. No fascinating optimization since
1821  * no one except parse_size use it
1822  */
1823 static int fls64(u64 x)
1824 {
1825         int i;
1826
1827         for (i = 0; i <64; i++)
1828                 if (x << i & (1ULL << 63))
1829                         return 64 - i;
1830         return 64 - i;
1831 }
1832
1833 u64 parse_size(char *s)
1834 {
1835         char c;
1836         char *endptr;
1837         u64 mult = 1;
1838         u64 ret;
1839
1840         if (!s) {
1841                 fprintf(stderr, "ERROR: Size value is empty\n");
1842                 exit(1);
1843         }
1844         if (s[0] == '-') {
1845                 fprintf(stderr,
1846                         "ERROR: Size value '%s' is less equal than 0\n", s);
1847                 exit(1);
1848         }
1849         ret = strtoull(s, &endptr, 10);
1850         if (endptr == s) {
1851                 fprintf(stderr, "ERROR: Size value '%s' is invalid\n", s);
1852                 exit(1);
1853         }
1854         if (endptr[0] && endptr[1]) {
1855                 fprintf(stderr, "ERROR: Illegal suffix contains character '%c' in wrong position\n",
1856                         endptr[1]);
1857                 exit(1);
1858         }
1859         /*
1860          * strtoll returns LLONG_MAX when overflow, if this happens,
1861          * need to call strtoull to get the real size
1862          */
1863         if (errno == ERANGE && ret == ULLONG_MAX) {
1864                 fprintf(stderr,
1865                         "ERROR: Size value '%s' is too large for u64\n", s);
1866                 exit(1);
1867         }
1868         if (endptr[0]) {
1869                 c = tolower(endptr[0]);
1870                 switch (c) {
1871                 case 'e':
1872                         mult *= 1024;
1873                         /* fallthrough */
1874                 case 'p':
1875                         mult *= 1024;
1876                         /* fallthrough */
1877                 case 't':
1878                         mult *= 1024;
1879                         /* fallthrough */
1880                 case 'g':
1881                         mult *= 1024;
1882                         /* fallthrough */
1883                 case 'm':
1884                         mult *= 1024;
1885                         /* fallthrough */
1886                 case 'k':
1887                         mult *= 1024;
1888                         /* fallthrough */
1889                 case 'b':
1890                         break;
1891                 default:
1892                         fprintf(stderr, "ERROR: Unknown size descriptor '%c'\n",
1893                                 c);
1894                         exit(1);
1895                 }
1896         }
1897         /* Check whether ret * mult overflow */
1898         if (fls64(ret) + fls64(mult) - 1 > 64) {
1899                 fprintf(stderr,
1900                         "ERROR: Size value '%s' is too large for u64\n", s);
1901                 exit(1);
1902         }
1903         ret *= mult;
1904         return ret;
1905 }
1906
1907 u64 parse_qgroupid(const char *p)
1908 {
1909         char *s = strchr(p, '/');
1910         const char *ptr_src_end = p + strlen(p);
1911         char *ptr_parse_end = NULL;
1912         u64 level;
1913         u64 id;
1914         int fd;
1915         int ret = 0;
1916
1917         if (p[0] == '/')
1918                 goto path;
1919
1920         /* Numeric format like '0/257' is the primary case */
1921         if (!s) {
1922                 id = strtoull(p, &ptr_parse_end, 10);
1923                 if (ptr_parse_end != ptr_src_end)
1924                         goto path;
1925                 return id;
1926         }
1927         level = strtoull(p, &ptr_parse_end, 10);
1928         if (ptr_parse_end != s)
1929                 goto path;
1930
1931         id = strtoull(s + 1, &ptr_parse_end, 10);
1932         if (ptr_parse_end != ptr_src_end)
1933                 goto  path;
1934
1935         return (level << BTRFS_QGROUP_LEVEL_SHIFT) | id;
1936
1937 path:
1938         /* Path format like subv at 'my_subvol' is the fallback case */
1939         ret = __is_subvol(p);
1940         if (ret < 0 || !ret)
1941                 goto err;
1942         fd = open(p, O_RDONLY);
1943         if (fd < 0)
1944                 goto err;
1945         ret = lookup_ino_rootid(fd, &id);
1946         close(fd);
1947         if (ret < 0)
1948                 goto err;
1949         return id;
1950
1951 err:
1952         fprintf(stderr, "ERROR: invalid qgroupid or subvolume path: %s\n", p);
1953         exit(-1);
1954 }
1955
1956 int open_file_or_dir3(const char *fname, DIR **dirstream, int open_flags)
1957 {
1958         int ret;
1959         struct stat st;
1960         int fd;
1961
1962         ret = stat(fname, &st);
1963         if (ret < 0) {
1964                 return -1;
1965         }
1966         if (S_ISDIR(st.st_mode)) {
1967                 *dirstream = opendir(fname);
1968                 if (!*dirstream)
1969                         return -1;
1970                 fd = dirfd(*dirstream);
1971         } else if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
1972                 fd = open(fname, open_flags);
1973         } else {
1974                 /*
1975                  * we set this on purpose, in case the caller output
1976                  * strerror(errno) as success
1977                  */
1978                 errno = EINVAL;
1979                 return -1;
1980         }
1981         if (fd < 0) {
1982                 fd = -1;
1983                 if (*dirstream)
1984                         closedir(*dirstream);
1985         }
1986         return fd;
1987 }
1988
1989 int open_file_or_dir(const char *fname, DIR **dirstream)
1990 {
1991         return open_file_or_dir3(fname, dirstream, O_RDWR);
1992 }
1993
1994 void close_file_or_dir(int fd, DIR *dirstream)
1995 {
1996         if (dirstream)
1997                 closedir(dirstream);
1998         else if (fd >= 0)
1999                 close(fd);
2000 }
2001
2002 int get_device_info(int fd, u64 devid,
2003                 struct btrfs_ioctl_dev_info_args *di_args)
2004 {
2005         int ret;
2006
2007         di_args->devid = devid;
2008         memset(&di_args->uuid, '\0', sizeof(di_args->uuid));
2009
2010         ret = ioctl(fd, BTRFS_IOC_DEV_INFO, di_args);
2011         return ret ? -errno : 0;
2012 }
2013
2014 static u64 find_max_device_id(struct btrfs_ioctl_search_args *search_args,
2015                               int nr_items)
2016 {
2017         struct btrfs_dev_item *dev_item;
2018         char *buf = search_args->buf;
2019
2020         buf += (nr_items - 1) * (sizeof(struct btrfs_ioctl_search_header)
2021                                        + sizeof(struct btrfs_dev_item));
2022         buf += sizeof(struct btrfs_ioctl_search_header);
2023
2024         dev_item = (struct btrfs_dev_item *)buf;
2025
2026         return btrfs_stack_device_id(dev_item);
2027 }
2028
2029 static int search_chunk_tree_for_fs_info(int fd,
2030                                 struct btrfs_ioctl_fs_info_args *fi_args)
2031 {
2032         int ret;
2033         int max_items;
2034         u64 start_devid = 1;
2035         struct btrfs_ioctl_search_args search_args;
2036         struct btrfs_ioctl_search_key *search_key = &search_args.key;
2037
2038         fi_args->num_devices = 0;
2039
2040         max_items = BTRFS_SEARCH_ARGS_BUFSIZE
2041                / (sizeof(struct btrfs_ioctl_search_header)
2042                                + sizeof(struct btrfs_dev_item));
2043
2044         search_key->tree_id = BTRFS_CHUNK_TREE_OBJECTID;
2045         search_key->min_objectid = BTRFS_DEV_ITEMS_OBJECTID;
2046         search_key->max_objectid = BTRFS_DEV_ITEMS_OBJECTID;
2047         search_key->min_type = BTRFS_DEV_ITEM_KEY;
2048         search_key->max_type = BTRFS_DEV_ITEM_KEY;
2049         search_key->min_transid = 0;
2050         search_key->max_transid = (u64)-1;
2051         search_key->nr_items = max_items;
2052         search_key->max_offset = (u64)-1;
2053
2054 again:
2055         search_key->min_offset = start_devid;
2056
2057         ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH, &search_args);
2058         if (ret < 0)
2059                 return -errno;
2060
2061         fi_args->num_devices += (u64)search_key->nr_items;
2062
2063         if (search_key->nr_items == max_items) {
2064                 start_devid = find_max_device_id(&search_args,
2065                                         search_key->nr_items) + 1;
2066                 goto again;
2067         }
2068
2069         /* get the lastest max_id to stay consistent with the num_devices */
2070         if (search_key->nr_items == 0)
2071                 /*
2072                  * last tree_search returns an empty buf, use the devid of
2073                  * the last dev_item of the previous tree_search
2074                  */
2075                 fi_args->max_id = start_devid - 1;
2076         else
2077                 fi_args->max_id = find_max_device_id(&search_args,
2078                                                 search_key->nr_items);
2079
2080         return 0;
2081 }
2082
2083 /*
2084  * For a given path, fill in the ioctl fs_ and info_ args.
2085  * If the path is a btrfs mountpoint, fill info for all devices.
2086  * If the path is a btrfs device, fill in only that device.
2087  *
2088  * The path provided must be either on a mounted btrfs fs,
2089  * or be a mounted btrfs device.
2090  *
2091  * Returns 0 on success, or a negative errno.
2092  */
2093 int get_fs_info(char *path, struct btrfs_ioctl_fs_info_args *fi_args,
2094                 struct btrfs_ioctl_dev_info_args **di_ret)
2095 {
2096         int fd = -1;
2097         int ret = 0;
2098         int ndevs = 0;
2099         int i = 0;
2100         int replacing = 0;
2101         struct btrfs_fs_devices *fs_devices_mnt = NULL;
2102         struct btrfs_ioctl_dev_info_args *di_args;
2103         struct btrfs_ioctl_dev_info_args tmp;
2104         char mp[BTRFS_PATH_NAME_MAX + 1];
2105         DIR *dirstream = NULL;
2106
2107         memset(fi_args, 0, sizeof(*fi_args));
2108
2109         if (is_block_device(path)) {
2110                 struct btrfs_super_block *disk_super;
2111                 char buf[BTRFS_SUPER_INFO_SIZE];
2112                 u64 devid;
2113
2114                 /* Ensure it's mounted, then set path to the mountpoint */
2115                 fd = open(path, O_RDONLY);
2116                 if (fd < 0) {
2117                         ret = -errno;
2118                         fprintf(stderr, "Couldn't open %s: %s\n",
2119                                 path, strerror(errno));
2120                         goto out;
2121                 }
2122                 ret = check_mounted_where(fd, path, mp, sizeof(mp),
2123                                           &fs_devices_mnt);
2124                 if (!ret) {
2125                         ret = -EINVAL;
2126                         goto out;
2127                 }
2128                 if (ret < 0)
2129                         goto out;
2130                 path = mp;
2131                 /* Only fill in this one device */
2132                 fi_args->num_devices = 1;
2133
2134                 disk_super = (struct btrfs_super_block *)buf;
2135                 ret = btrfs_read_dev_super(fd, disk_super,
2136                                            BTRFS_SUPER_INFO_OFFSET, 0);
2137                 if (ret < 0) {
2138                         ret = -EIO;
2139                         goto out;
2140                 }
2141                 devid = btrfs_stack_device_id(&disk_super->dev_item);
2142
2143                 fi_args->max_id = devid;
2144                 i = devid;
2145
2146                 memcpy(fi_args->fsid, fs_devices_mnt->fsid, BTRFS_FSID_SIZE);
2147                 close(fd);
2148         }
2149
2150         /* at this point path must not be for a block device */
2151         fd = open_file_or_dir(path, &dirstream);
2152         if (fd < 0) {
2153                 ret = -errno;
2154                 goto out;
2155         }
2156
2157         /* fill in fi_args if not just a single device */
2158         if (fi_args->num_devices != 1) {
2159                 ret = ioctl(fd, BTRFS_IOC_FS_INFO, fi_args);
2160                 if (ret < 0) {
2161                         ret = -errno;
2162                         goto out;
2163                 }
2164
2165                 /*
2166                  * The fs_args->num_devices does not include seed devices
2167                  */
2168                 ret = search_chunk_tree_for_fs_info(fd, fi_args);
2169                 if (ret)
2170                         goto out;
2171
2172                 /*
2173                  * search_chunk_tree_for_fs_info() will lacks the devid 0
2174                  * so manual probe for it here.
2175                  */
2176                 ret = get_device_info(fd, 0, &tmp);
2177                 if (!ret) {
2178                         fi_args->num_devices++;
2179                         ndevs++;
2180                         replacing = 1;
2181                         if (i == 0)
2182                                 i++;
2183                 }
2184         }
2185
2186         if (!fi_args->num_devices)
2187                 goto out;
2188
2189         di_args = *di_ret = malloc((fi_args->num_devices) * sizeof(*di_args));
2190         if (!di_args) {
2191                 ret = -errno;
2192                 goto out;
2193         }
2194
2195         if (replacing)
2196                 memcpy(di_args, &tmp, sizeof(tmp));
2197         for (; i <= fi_args->max_id; ++i) {
2198                 ret = get_device_info(fd, i, &di_args[ndevs]);
2199                 if (ret == -ENODEV)
2200                         continue;
2201                 if (ret)
2202                         goto out;
2203                 ndevs++;
2204         }
2205
2206         /*
2207         * only when the only dev we wanted to find is not there then
2208         * let any error be returned
2209         */
2210         if (fi_args->num_devices != 1) {
2211                 BUG_ON(ndevs == 0);
2212                 ret = 0;
2213         }
2214
2215 out:
2216         close_file_or_dir(fd, dirstream);
2217         return ret;
2218 }
2219
2220 #define isoctal(c)      (((c) & ~7) == '0')
2221
2222 static inline void translate(char *f, char *t)
2223 {
2224         while (*f != '\0') {
2225                 if (*f == '\\' &&
2226                     isoctal(f[1]) && isoctal(f[2]) && isoctal(f[3])) {
2227                         *t++ = 64*(f[1] & 7) + 8*(f[2] & 7) + (f[3] & 7);
2228                         f += 4;
2229                 } else
2230                         *t++ = *f++;
2231         }
2232         *t = '\0';
2233         return;
2234 }
2235
2236 /*
2237  * Checks if the swap device.
2238  * Returns 1 if swap device, < 0 on error or 0 if not swap device.
2239  */
2240 static int is_swap_device(const char *file)
2241 {
2242         FILE    *f;
2243         struct stat     st_buf;
2244         dev_t   dev;
2245         ino_t   ino = 0;
2246         char    tmp[PATH_MAX];
2247         char    buf[PATH_MAX];
2248         char    *cp;
2249         int     ret = 0;
2250
2251         if (stat(file, &st_buf) < 0)
2252                 return -errno;
2253         if (S_ISBLK(st_buf.st_mode))
2254                 dev = st_buf.st_rdev;
2255         else if (S_ISREG(st_buf.st_mode)) {
2256                 dev = st_buf.st_dev;
2257                 ino = st_buf.st_ino;
2258         } else
2259                 return 0;
2260
2261         if ((f = fopen("/proc/swaps", "r")) == NULL)
2262                 return 0;
2263
2264         /* skip the first line */
2265         if (fgets(tmp, sizeof(tmp), f) == NULL)
2266                 goto out;
2267
2268         while (fgets(tmp, sizeof(tmp), f) != NULL) {
2269                 if ((cp = strchr(tmp, ' ')) != NULL)
2270                         *cp = '\0';
2271                 if ((cp = strchr(tmp, '\t')) != NULL)
2272                         *cp = '\0';
2273                 translate(tmp, buf);
2274                 if (stat(buf, &st_buf) != 0)
2275                         continue;
2276                 if (S_ISBLK(st_buf.st_mode)) {
2277                         if (dev == st_buf.st_rdev) {
2278                                 ret = 1;
2279                                 break;
2280                         }
2281                 } else if (S_ISREG(st_buf.st_mode)) {
2282                         if (dev == st_buf.st_dev && ino == st_buf.st_ino) {
2283                                 ret = 1;
2284                                 break;
2285                         }
2286                 }
2287         }
2288
2289 out:
2290         fclose(f);
2291
2292         return ret;
2293 }
2294
2295 /*
2296  * Check for existing filesystem or partition table on device.
2297  * Returns:
2298  *       1 for existing fs or partition
2299  *       0 for nothing found
2300  *      -1 for internal error
2301  */
2302 static int
2303 check_overwrite(
2304         char            *device)
2305 {
2306         const char      *type;
2307         blkid_probe     pr = NULL;
2308         int             ret;
2309         blkid_loff_t    size;
2310
2311         if (!device || !*device)
2312                 return 0;
2313
2314         ret = -1; /* will reset on success of all setup calls */
2315
2316         pr = blkid_new_probe_from_filename(device);
2317         if (!pr)
2318                 goto out;
2319
2320         size = blkid_probe_get_size(pr);
2321         if (size < 0)
2322                 goto out;
2323
2324         /* nothing to overwrite on a 0-length device */
2325         if (size == 0) {
2326                 ret = 0;
2327                 goto out;
2328         }
2329
2330         ret = blkid_probe_enable_partitions(pr, 1);
2331         if (ret < 0)
2332                 goto out;
2333
2334         ret = blkid_do_fullprobe(pr);
2335         if (ret < 0)
2336                 goto out;
2337
2338         /*
2339          * Blkid returns 1 for nothing found and 0 when it finds a signature,
2340          * but we want the exact opposite, so reverse the return value here.
2341          *
2342          * In addition print some useful diagnostics about what actually is
2343          * on the device.
2344          */
2345         if (ret) {
2346                 ret = 0;
2347                 goto out;
2348         }
2349
2350         if (!blkid_probe_lookup_value(pr, "TYPE", &type, NULL)) {
2351                 fprintf(stderr,
2352                         "%s appears to contain an existing "
2353                         "filesystem (%s).\n", device, type);
2354         } else if (!blkid_probe_lookup_value(pr, "PTTYPE", &type, NULL)) {
2355                 fprintf(stderr,
2356                         "%s appears to contain a partition "
2357                         "table (%s).\n", device, type);
2358         } else {
2359                 fprintf(stderr,
2360                         "%s appears to contain something weird "
2361                         "according to blkid\n", device);
2362         }
2363         ret = 1;
2364
2365 out:
2366         if (pr)
2367                 blkid_free_probe(pr);
2368         if (ret == -1)
2369                 fprintf(stderr,
2370                         "probe of %s failed, cannot detect "
2371                           "existing filesystem.\n", device);
2372         return ret;
2373 }
2374
2375 static int group_profile_devs_min(u64 flag)
2376 {
2377         switch (flag & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
2378         case 0: /* single */
2379         case BTRFS_BLOCK_GROUP_DUP:
2380                 return 1;
2381         case BTRFS_BLOCK_GROUP_RAID0:
2382         case BTRFS_BLOCK_GROUP_RAID1:
2383         case BTRFS_BLOCK_GROUP_RAID5:
2384                 return 2;
2385         case BTRFS_BLOCK_GROUP_RAID6:
2386                 return 3;
2387         case BTRFS_BLOCK_GROUP_RAID10:
2388                 return 4;
2389         default:
2390                 return -1;
2391         }
2392 }
2393
2394 int test_num_disk_vs_raid(u64 metadata_profile, u64 data_profile,
2395         u64 dev_cnt, int mixed, char *estr)
2396 {
2397         size_t sz = 100;
2398         u64 allowed = 0;
2399
2400         switch (dev_cnt) {
2401         default:
2402         case 4:
2403                 allowed |= BTRFS_BLOCK_GROUP_RAID10;
2404         case 3:
2405                 allowed |= BTRFS_BLOCK_GROUP_RAID6;
2406         case 2:
2407                 allowed |= BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
2408                         BTRFS_BLOCK_GROUP_RAID5;
2409                 break;
2410         case 1:
2411                 allowed |= BTRFS_BLOCK_GROUP_DUP;
2412         }
2413
2414         if (dev_cnt > 1 &&
2415             ((metadata_profile | data_profile) & BTRFS_BLOCK_GROUP_DUP)) {
2416                 snprintf(estr, sz,
2417                         "DUP is not allowed when FS has multiple devices\n");
2418                 return 1;
2419         }
2420         if (metadata_profile & ~allowed) {
2421                 snprintf(estr, sz,
2422                         "unable to create FS with metadata profile %s "
2423                         "(have %llu devices but %d devices are required)\n",
2424                         btrfs_group_profile_str(metadata_profile), dev_cnt,
2425                         group_profile_devs_min(metadata_profile));
2426                 return 1;
2427         }
2428         if (data_profile & ~allowed) {
2429                 snprintf(estr, sz,
2430                         "unable to create FS with data profile %s "
2431                         "(have %llu devices but %d devices are required)\n",
2432                         btrfs_group_profile_str(data_profile), dev_cnt,
2433                         group_profile_devs_min(data_profile));
2434                 return 1;
2435         }
2436
2437         if (!mixed && (data_profile & BTRFS_BLOCK_GROUP_DUP)) {
2438                 snprintf(estr, sz,
2439                         "dup for data is allowed only in mixed mode");
2440                 return 1;
2441         }
2442         return 0;
2443 }
2444
2445 /* Check if disk is suitable for btrfs
2446  * returns:
2447  *  1: something is wrong, estr provides the error
2448  *  0: all is fine
2449  */
2450 int test_dev_for_mkfs(char *file, int force_overwrite, char *estr)
2451 {
2452         int ret, fd;
2453         size_t sz = 100;
2454         struct stat st;
2455
2456         ret = is_swap_device(file);
2457         if (ret < 0) {
2458                 snprintf(estr, sz, "error checking %s status: %s\n", file,
2459                         strerror(-ret));
2460                 return 1;
2461         }
2462         if (ret == 1) {
2463                 snprintf(estr, sz, "%s is a swap device\n", file);
2464                 return 1;
2465         }
2466         if (!force_overwrite) {
2467                 if (check_overwrite(file)) {
2468                         snprintf(estr, sz, "Use the -f option to force overwrite.\n");
2469                         return 1;
2470                 }
2471         }
2472         ret = check_mounted(file);
2473         if (ret < 0) {
2474                 snprintf(estr, sz, "error checking %s mount status\n",
2475                         file);
2476                 return 1;
2477         }
2478         if (ret == 1) {
2479                 snprintf(estr, sz, "%s is mounted\n", file);
2480                 return 1;
2481         }
2482         /* check if the device is busy */
2483         fd = open(file, O_RDWR|O_EXCL);
2484         if (fd < 0) {
2485                 snprintf(estr, sz, "unable to open %s: %s\n", file,
2486                         strerror(errno));
2487                 return 1;
2488         }
2489         if (fstat(fd, &st)) {
2490                 snprintf(estr, sz, "unable to stat %s: %s\n", file,
2491                         strerror(errno));
2492                 close(fd);
2493                 return 1;
2494         }
2495         if (!S_ISBLK(st.st_mode)) {
2496                 fprintf(stderr, "'%s' is not a block device\n", file);
2497                 close(fd);
2498                 return 1;
2499         }
2500         close(fd);
2501         return 0;
2502 }
2503
2504 int btrfs_scan_lblkid()
2505 {
2506         int fd = -1;
2507         int ret;
2508         u64 num_devices;
2509         struct btrfs_fs_devices *tmp_devices;
2510         blkid_dev_iterate iter = NULL;
2511         blkid_dev dev = NULL;
2512         blkid_cache cache = NULL;
2513         char path[PATH_MAX];
2514
2515         if (btrfs_scan_done)
2516                 return 0;
2517
2518         if (blkid_get_cache(&cache, 0) < 0) {
2519                 printf("ERROR: lblkid cache get failed\n");
2520                 return 1;
2521         }
2522         blkid_probe_all(cache);
2523         iter = blkid_dev_iterate_begin(cache);
2524         blkid_dev_set_search(iter, "TYPE", "btrfs");
2525         while (blkid_dev_next(iter, &dev) == 0) {
2526                 dev = blkid_verify(cache, dev);
2527                 if (!dev)
2528                         continue;
2529                 /* if we are here its definitely a btrfs disk*/
2530                 strncpy_null(path, blkid_dev_devname(dev));
2531
2532                 fd = open(path, O_RDONLY);
2533                 if (fd < 0) {
2534                         printf("ERROR: could not open %s\n", path);
2535                         continue;
2536                 }
2537                 ret = btrfs_scan_one_device(fd, path, &tmp_devices,
2538                                 &num_devices, BTRFS_SUPER_INFO_OFFSET, 0);
2539                 if (ret) {
2540                         printf("ERROR: could not scan %s\n", path);
2541                         close (fd);
2542                         continue;
2543                 }
2544
2545                 close(fd);
2546         }
2547         blkid_dev_iterate_end(iter);
2548         blkid_put_cache(cache);
2549
2550         btrfs_scan_done = 1;
2551
2552         return 0;
2553 }
2554
2555 int is_vol_small(char *file)
2556 {
2557         int fd = -1;
2558         int e;
2559         struct stat st;
2560         u64 size;
2561
2562         fd = open(file, O_RDONLY);
2563         if (fd < 0)
2564                 return -errno;
2565         if (fstat(fd, &st) < 0) {
2566                 e = -errno;
2567                 close(fd);
2568                 return e;
2569         }
2570         size = btrfs_device_size(fd, &st);
2571         if (size == 0) {
2572                 close(fd);
2573                 return -1;
2574         }
2575         if (size < BTRFS_MKFS_SMALL_VOLUME_SIZE) {
2576                 close(fd);
2577                 return 1;
2578         } else {
2579                 close(fd);
2580                 return 0;
2581         }
2582 }
2583
2584 /*
2585  * This reads a line from the stdin and only returns non-zero if the
2586  * first whitespace delimited token is a case insensitive match with yes
2587  * or y.
2588  */
2589 int ask_user(char *question)
2590 {
2591         char buf[30] = {0,};
2592         char *saveptr = NULL;
2593         char *answer;
2594
2595         printf("%s [y/N]: ", question);
2596
2597         return fgets(buf, sizeof(buf) - 1, stdin) &&
2598                (answer = strtok_r(buf, " \t\n\r", &saveptr)) &&
2599                (!strcasecmp(answer, "yes") || !strcasecmp(answer, "y"));
2600 }
2601
2602 /*
2603  * For a given:
2604  * - file or directory return the containing tree root id
2605  * - subvolume return its own tree id
2606  * - BTRFS_EMPTY_SUBVOL_DIR_OBJECTID (directory with ino == 2) the result is
2607  *   undefined and function returns -1
2608  */
2609 int lookup_ino_rootid(int fd, u64 *rootid)
2610 {
2611         struct btrfs_ioctl_ino_lookup_args args;
2612         int ret;
2613         int e;
2614
2615         memset(&args, 0, sizeof(args));
2616         args.treeid = 0;
2617         args.objectid = BTRFS_FIRST_FREE_OBJECTID;
2618
2619         ret = ioctl(fd, BTRFS_IOC_INO_LOOKUP, &args);
2620         e = errno;
2621         if (ret) {
2622                 fprintf(stderr, "ERROR: Failed to lookup root id - %s\n",
2623                         strerror(e));
2624                 return ret;
2625         }
2626
2627         *rootid = args.treeid;
2628
2629         return 0;
2630 }
2631
2632 /*
2633  * return 0 if a btrfs mount point is found
2634  * return 1 if a mount point is found but not btrfs
2635  * return <0 if something goes wrong
2636  */
2637 int find_mount_root(const char *path, char **mount_root)
2638 {
2639         FILE *mnttab;
2640         int fd;
2641         struct mntent *ent;
2642         int len;
2643         int ret;
2644         int not_btrfs = 1;
2645         int longest_matchlen = 0;
2646         char *longest_match = NULL;
2647
2648         fd = open(path, O_RDONLY | O_NOATIME);
2649         if (fd < 0)
2650                 return -errno;
2651         close(fd);
2652
2653         mnttab = setmntent("/proc/self/mounts", "r");
2654         if (!mnttab)
2655                 return -errno;
2656
2657         while ((ent = getmntent(mnttab))) {
2658                 len = strlen(ent->mnt_dir);
2659                 if (strncmp(ent->mnt_dir, path, len) == 0) {
2660                         /* match found and use the latest match */
2661                         if (longest_matchlen <= len) {
2662                                 free(longest_match);
2663                                 longest_matchlen = len;
2664                                 longest_match = strdup(ent->mnt_dir);
2665                                 not_btrfs = strcmp(ent->mnt_type, "btrfs");
2666                         }
2667                 }
2668         }
2669         endmntent(mnttab);
2670
2671         if (!longest_match)
2672                 return -ENOENT;
2673         if (not_btrfs) {
2674                 free(longest_match);
2675                 return 1;
2676         }
2677
2678         ret = 0;
2679         *mount_root = realpath(longest_match, NULL);
2680         if (!*mount_root)
2681                 ret = -errno;
2682
2683         free(longest_match);
2684         return ret;
2685 }
2686
2687 int test_minimum_size(const char *file, u32 nodesize)
2688 {
2689         int fd;
2690         struct stat statbuf;
2691
2692         fd = open(file, O_RDONLY);
2693         if (fd < 0)
2694                 return -errno;
2695         if (stat(file, &statbuf) < 0) {
2696                 close(fd);
2697                 return -errno;
2698         }
2699         if (btrfs_device_size(fd, &statbuf) < btrfs_min_dev_size(nodesize)) {
2700                 close(fd);
2701                 return 1;
2702         }
2703         close(fd);
2704         return 0;
2705 }
2706
2707 /*
2708  * test if name is a correct subvolume name
2709  * this function return
2710  * 0-> name is not a correct subvolume name
2711  * 1-> name is a correct subvolume name
2712  */
2713 int test_issubvolname(const char *name)
2714 {
2715         return name[0] != '\0' && !strchr(name, '/') &&
2716                 strcmp(name, ".") && strcmp(name, "..");
2717 }
2718
2719 /*
2720  * test if path is a directory
2721  * this function return
2722  * 0-> path exists but it is not a directory
2723  * 1-> path exists and it is a directory
2724  * -1 -> path is unaccessible
2725  */
2726 int test_isdir(const char *path)
2727 {
2728         struct stat st;
2729         int ret;
2730
2731         ret = stat(path, &st);
2732         if(ret < 0 )
2733                 return -1;
2734
2735         return S_ISDIR(st.st_mode);
2736 }
2737
2738 void units_set_mode(unsigned *units, unsigned mode)
2739 {
2740         unsigned base = *units & UNITS_MODE_MASK;
2741
2742         *units = base | mode;
2743 }
2744
2745 void units_set_base(unsigned *units, unsigned base)
2746 {
2747         unsigned mode = *units & ~UNITS_MODE_MASK;
2748
2749         *units = base | mode;
2750 }
2751
2752 int find_next_key(struct btrfs_path *path, struct btrfs_key *key)
2753 {
2754         int level;
2755
2756         for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2757                 if (!path->nodes[level])
2758                         break;
2759                 if (path->slots[level] + 1 >=
2760                     btrfs_header_nritems(path->nodes[level]))
2761                         continue;
2762                 if (level == 0)
2763                         btrfs_item_key_to_cpu(path->nodes[level], key,
2764                                               path->slots[level] + 1);
2765                 else
2766                         btrfs_node_key_to_cpu(path->nodes[level], key,
2767                                               path->slots[level] + 1);
2768                 return 0;
2769         }
2770         return 1;
2771 }
2772
2773 char* btrfs_group_type_str(u64 flag)
2774 {
2775         u64 mask = BTRFS_BLOCK_GROUP_TYPE_MASK |
2776                 BTRFS_SPACE_INFO_GLOBAL_RSV;
2777
2778         switch (flag & mask) {
2779         case BTRFS_BLOCK_GROUP_DATA:
2780                 return "Data";
2781         case BTRFS_BLOCK_GROUP_SYSTEM:
2782                 return "System";
2783         case BTRFS_BLOCK_GROUP_METADATA:
2784                 return "Metadata";
2785         case BTRFS_BLOCK_GROUP_DATA|BTRFS_BLOCK_GROUP_METADATA:
2786                 return "Data+Metadata";
2787         case BTRFS_SPACE_INFO_GLOBAL_RSV:
2788                 return "GlobalReserve";
2789         default:
2790                 return "unknown";
2791         }
2792 }
2793
2794 char* btrfs_group_profile_str(u64 flag)
2795 {
2796         switch (flag & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
2797         case 0:
2798                 return "single";
2799         case BTRFS_BLOCK_GROUP_RAID0:
2800                 return "RAID0";
2801         case BTRFS_BLOCK_GROUP_RAID1:
2802                 return "RAID1";
2803         case BTRFS_BLOCK_GROUP_RAID5:
2804                 return "RAID5";
2805         case BTRFS_BLOCK_GROUP_RAID6:
2806                 return "RAID6";
2807         case BTRFS_BLOCK_GROUP_DUP:
2808                 return "DUP";
2809         case BTRFS_BLOCK_GROUP_RAID10:
2810                 return "RAID10";
2811         default:
2812                 return "unknown";
2813         }
2814 }
2815
2816 u64 disk_size(char *path)
2817 {
2818         struct statfs sfs;
2819
2820         if (statfs(path, &sfs) < 0)
2821                 return 0;
2822         else
2823                 return sfs.f_bsize * sfs.f_blocks;
2824 }
2825
2826 u64 get_partition_size(char *dev)
2827 {
2828         u64 result;
2829         int fd = open(dev, O_RDONLY);
2830
2831         if (fd < 0)
2832                 return 0;
2833         if (ioctl(fd, BLKGETSIZE64, &result) < 0) {
2834                 close(fd);
2835                 return 0;
2836         }
2837         close(fd);
2838
2839         return result;
2840 }
2841
2842 int btrfs_tree_search2_ioctl_supported(int fd)
2843 {
2844         struct btrfs_ioctl_search_args_v2 *args2;
2845         struct btrfs_ioctl_search_key *sk;
2846         int args2_size = 1024;
2847         char args2_buf[args2_size];
2848         int ret;
2849         static int v2_supported = -1;
2850
2851         if (v2_supported != -1)
2852                 return v2_supported;
2853
2854         args2 = (struct btrfs_ioctl_search_args_v2 *)args2_buf;
2855         sk = &(args2->key);
2856
2857         /*
2858          * Search for the extent tree item in the root tree.
2859          */
2860         sk->tree_id = BTRFS_ROOT_TREE_OBJECTID;
2861         sk->min_objectid = BTRFS_EXTENT_TREE_OBJECTID;
2862         sk->max_objectid = BTRFS_EXTENT_TREE_OBJECTID;
2863         sk->min_type = BTRFS_ROOT_ITEM_KEY;
2864         sk->max_type = BTRFS_ROOT_ITEM_KEY;
2865         sk->min_offset = 0;
2866         sk->max_offset = (u64)-1;
2867         sk->min_transid = 0;
2868         sk->max_transid = (u64)-1;
2869         sk->nr_items = 1;
2870         args2->buf_size = args2_size - sizeof(struct btrfs_ioctl_search_args_v2);
2871         ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH_V2, args2);
2872         if (ret == -EOPNOTSUPP)
2873                 v2_supported = 0;
2874         else if (ret == 0)
2875                 v2_supported = 1;
2876         else
2877                 return ret;
2878
2879         return v2_supported;
2880 }
2881
2882 int btrfs_check_nodesize(u32 nodesize, u32 sectorsize)
2883 {
2884         if (nodesize < sectorsize) {
2885                 fprintf(stderr,
2886                         "ERROR: Illegal nodesize %u (smaller than %u)\n",
2887                         nodesize, sectorsize);
2888                 return -1;
2889         } else if (nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
2890                 fprintf(stderr,
2891                         "ERROR: Illegal nodesize %u (larger than %u)\n",
2892                         nodesize, BTRFS_MAX_METADATA_BLOCKSIZE);
2893                 return -1;
2894         } else if (nodesize & (sectorsize - 1)) {
2895                 fprintf(stderr,
2896                         "ERROR: Illegal nodesize %u (not aligned to %u)\n",
2897                         nodesize, sectorsize);
2898                 return -1;
2899         }
2900         return 0;
2901 }