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