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