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