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