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