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