a4bc213e23fec7e79fad39964c0e50c4226b6172
[platform/upstream/btrfs-progs.git] / utils.c
1 /*
2  * Copyright (C) 2007 Oracle.  All rights reserved.
3  * Copyright (C) 2008 Morey Roof.  All rights reserved.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public
7  * License v2 as published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public
15  * License along with this program; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 021110-1307, USA.
18  */
19
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <sys/ioctl.h>
24 #include <sys/mount.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <uuid/uuid.h>
28 #include <fcntl.h>
29 #include <unistd.h>
30 #include <mntent.h>
31 #include <ctype.h>
32 #include <linux/loop.h>
33 #include <linux/major.h>
34 #include <linux/kdev_t.h>
35 #include <limits.h>
36 #include <blkid/blkid.h>
37 #include <sys/vfs.h>
38 #include <sys/statfs.h>
39 #include <linux/magic.h>
40 #include <sys/utsname.h>
41 #include <linux/version.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 #include "commands.h"
53 #include "mkfs/common.h"
54 #include "convert/common.h"
55
56 #ifndef BLKDISCARD
57 #define BLKDISCARD      _IO(0x12,119)
58 #endif
59
60 static int btrfs_scan_done = 0;
61
62 static int rand_seed_initlized = 0;
63 static unsigned short rand_seed[3];
64
65 struct btrfs_config bconf;
66
67 /*
68  * Discard the given range in one go
69  */
70 static int discard_range(int fd, u64 start, u64 len)
71 {
72         u64 range[2] = { start, len };
73
74         if (ioctl(fd, BLKDISCARD, &range) < 0)
75                 return errno;
76         return 0;
77 }
78
79 /*
80  * Discard blocks in the given range in 1G chunks, the process is interruptible
81  */
82 static int discard_blocks(int fd, u64 start, u64 len)
83 {
84         while (len > 0) {
85                 /* 1G granularity */
86                 u64 chunk_size = min_t(u64, len, SZ_1G);
87                 int ret;
88
89                 ret = discard_range(fd, start, chunk_size);
90                 if (ret)
91                         return ret;
92                 len -= chunk_size;
93                 start += chunk_size;
94         }
95
96         return 0;
97 }
98
99 int test_uuid_unique(char *fs_uuid)
100 {
101         int unique = 1;
102         blkid_dev_iterate iter = NULL;
103         blkid_dev dev = NULL;
104         blkid_cache cache = NULL;
105
106         if (blkid_get_cache(&cache, NULL) < 0) {
107                 printf("ERROR: lblkid cache get failed\n");
108                 return 1;
109         }
110         blkid_probe_all(cache);
111         iter = blkid_dev_iterate_begin(cache);
112         blkid_dev_set_search(iter, "UUID", fs_uuid);
113
114         while (blkid_dev_next(iter, &dev) == 0) {
115                 dev = blkid_verify(cache, dev);
116                 if (dev) {
117                         unique = 0;
118                         break;
119                 }
120         }
121
122         blkid_dev_iterate_end(iter);
123         blkid_put_cache(cache);
124
125         return unique;
126 }
127
128 /*
129  * Reserve space from free_tree.
130  * The algorithm is very simple, find the first cache_extent with enough space
131  * and allocate from its beginning.
132  */
133 static int reserve_free_space(struct cache_tree *free_tree, u64 len,
134                               u64 *ret_start)
135 {
136         struct cache_extent *cache;
137         int found = 0;
138
139         ASSERT(ret_start != NULL);
140         cache = first_cache_extent(free_tree);
141         while (cache) {
142                 if (cache->size > len) {
143                         found = 1;
144                         *ret_start = cache->start;
145
146                         cache->size -= len;
147                         if (cache->size == 0) {
148                                 remove_cache_extent(free_tree, cache);
149                                 free(cache);
150                         } else {
151                                 cache->start += len;
152                         }
153                         break;
154                 }
155                 cache = next_cache_extent(cache);
156         }
157         if (!found)
158                 return -ENOSPC;
159         return 0;
160 }
161
162 static inline int write_temp_super(int fd, struct btrfs_super_block *sb,
163                                    u64 sb_bytenr)
164 {
165         u32 crc = ~(u32)0;
166         int ret;
167
168         crc = btrfs_csum_data(NULL, (char *)sb + BTRFS_CSUM_SIZE, crc,
169                               BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
170         btrfs_csum_final(crc, &sb->csum[0]);
171         ret = pwrite(fd, sb, BTRFS_SUPER_INFO_SIZE, sb_bytenr);
172         if (ret < BTRFS_SUPER_INFO_SIZE)
173                 ret = (ret < 0 ? -errno : -EIO);
174         else
175                 ret = 0;
176         return ret;
177 }
178
179 /*
180  * Setup temporary superblock at cfg->super_bynter
181  * Needed info are extracted from cfg, and root_bytenr, chunk_bytenr
182  *
183  * For now sys chunk array will be empty and dev_item is empty too.
184  * They will be re-initialized at temp chunk tree setup.
185  *
186  * The superblock signature is not valid, denotes a partially created
187  * filesystem, needs to be finalized.
188  */
189 static int setup_temp_super(int fd, struct btrfs_mkfs_config *cfg,
190                             u64 root_bytenr, u64 chunk_bytenr)
191 {
192         unsigned char chunk_uuid[BTRFS_UUID_SIZE];
193         char super_buf[BTRFS_SUPER_INFO_SIZE];
194         struct btrfs_super_block *super = (struct btrfs_super_block *)super_buf;
195         int ret;
196
197         memset(super_buf, 0, BTRFS_SUPER_INFO_SIZE);
198         cfg->num_bytes = round_down(cfg->num_bytes, cfg->sectorsize);
199
200         if (*cfg->fs_uuid) {
201                 if (uuid_parse(cfg->fs_uuid, super->fsid) != 0) {
202                         error("cound not parse UUID: %s", cfg->fs_uuid);
203                         ret = -EINVAL;
204                         goto out;
205                 }
206                 if (!test_uuid_unique(cfg->fs_uuid)) {
207                         error("non-unique UUID: %s", cfg->fs_uuid);
208                         ret = -EINVAL;
209                         goto out;
210                 }
211         } else {
212                 uuid_generate(super->fsid);
213                 uuid_unparse(super->fsid, cfg->fs_uuid);
214         }
215         uuid_generate(chunk_uuid);
216         uuid_unparse(chunk_uuid, cfg->chunk_uuid);
217
218         btrfs_set_super_bytenr(super, cfg->super_bytenr);
219         btrfs_set_super_num_devices(super, 1);
220         btrfs_set_super_magic(super, BTRFS_MAGIC_PARTIAL);
221         btrfs_set_super_generation(super, 1);
222         btrfs_set_super_root(super, root_bytenr);
223         btrfs_set_super_chunk_root(super, chunk_bytenr);
224         btrfs_set_super_total_bytes(super, cfg->num_bytes);
225         /*
226          * Temporary filesystem will only have 6 tree roots:
227          * chunk tree, root tree, extent_tree, device tree, fs tree
228          * and csum tree.
229          */
230         btrfs_set_super_bytes_used(super, 6 * cfg->nodesize);
231         btrfs_set_super_sectorsize(super, cfg->sectorsize);
232         btrfs_set_super_leafsize(super, cfg->nodesize);
233         btrfs_set_super_nodesize(super, cfg->nodesize);
234         btrfs_set_super_stripesize(super, cfg->stripesize);
235         btrfs_set_super_csum_type(super, BTRFS_CSUM_TYPE_CRC32);
236         btrfs_set_super_chunk_root(super, chunk_bytenr);
237         btrfs_set_super_cache_generation(super, -1);
238         btrfs_set_super_incompat_flags(super, cfg->features);
239         if (cfg->label)
240                 __strncpy_null(super->label, cfg->label, BTRFS_LABEL_SIZE - 1);
241
242         /* Sys chunk array will be re-initialized at chunk tree init time */
243         super->sys_chunk_array_size = 0;
244
245         ret = write_temp_super(fd, super, cfg->super_bytenr);
246 out:
247         return ret;
248 }
249
250 /*
251  * Setup an extent buffer for tree block.
252  */
253 static int setup_temp_extent_buffer(struct extent_buffer *buf,
254                                     struct btrfs_mkfs_config *cfg,
255                                     u64 bytenr, u64 owner)
256 {
257         unsigned char fsid[BTRFS_FSID_SIZE];
258         unsigned char chunk_uuid[BTRFS_UUID_SIZE];
259         int ret;
260
261         ret = uuid_parse(cfg->fs_uuid, fsid);
262         if (ret)
263                 return -EINVAL;
264         ret = uuid_parse(cfg->chunk_uuid, chunk_uuid);
265         if (ret)
266                 return -EINVAL;
267
268         memset(buf->data, 0, cfg->nodesize);
269         buf->len = cfg->nodesize;
270         btrfs_set_header_bytenr(buf, bytenr);
271         btrfs_set_header_generation(buf, 1);
272         btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
273         btrfs_set_header_owner(buf, owner);
274         btrfs_set_header_flags(buf, BTRFS_HEADER_FLAG_WRITTEN);
275         write_extent_buffer(buf, chunk_uuid, btrfs_header_chunk_tree_uuid(buf),
276                             BTRFS_UUID_SIZE);
277         write_extent_buffer(buf, fsid, btrfs_header_fsid(), BTRFS_FSID_SIZE);
278         return 0;
279 }
280
281 static inline int write_temp_extent_buffer(int fd, struct extent_buffer *buf,
282                                            u64 bytenr)
283 {
284         int ret;
285
286         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
287
288         /* Temporary extent buffer is always mapped 1:1 on disk */
289         ret = pwrite(fd, buf->data, buf->len, bytenr);
290         if (ret < buf->len)
291                 ret = (ret < 0 ? ret : -EIO);
292         else
293                 ret = 0;
294         return ret;
295 }
296
297 /*
298  * Insert a root item for temporary tree root
299  *
300  * Only used in make_btrfs_v2().
301  */
302 static void insert_temp_root_item(struct extent_buffer *buf,
303                                   struct btrfs_mkfs_config *cfg,
304                                   int *slot, u32 *itemoff, u64 objectid,
305                                   u64 bytenr)
306 {
307         struct btrfs_root_item root_item;
308         struct btrfs_inode_item *inode_item;
309         struct btrfs_disk_key disk_key;
310
311         btrfs_set_header_nritems(buf, *slot + 1);
312         (*itemoff) -= sizeof(root_item);
313         memset(&root_item, 0, sizeof(root_item));
314         inode_item = &root_item.inode;
315         btrfs_set_stack_inode_generation(inode_item, 1);
316         btrfs_set_stack_inode_size(inode_item, 3);
317         btrfs_set_stack_inode_nlink(inode_item, 1);
318         btrfs_set_stack_inode_nbytes(inode_item, cfg->nodesize);
319         btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
320         btrfs_set_root_refs(&root_item, 1);
321         btrfs_set_root_used(&root_item, cfg->nodesize);
322         btrfs_set_root_generation(&root_item, 1);
323         btrfs_set_root_bytenr(&root_item, bytenr);
324
325         memset(&disk_key, 0, sizeof(disk_key));
326         btrfs_set_disk_key_type(&disk_key, BTRFS_ROOT_ITEM_KEY);
327         btrfs_set_disk_key_objectid(&disk_key, objectid);
328         btrfs_set_disk_key_offset(&disk_key, 0);
329
330         btrfs_set_item_key(buf, &disk_key, *slot);
331         btrfs_set_item_offset(buf, btrfs_item_nr(*slot), *itemoff);
332         btrfs_set_item_size(buf, btrfs_item_nr(*slot), sizeof(root_item));
333         write_extent_buffer(buf, &root_item,
334                             btrfs_item_ptr_offset(buf, *slot),
335                             sizeof(root_item));
336         (*slot)++;
337 }
338
339 static int setup_temp_root_tree(int fd, struct btrfs_mkfs_config *cfg,
340                                 u64 root_bytenr, u64 extent_bytenr,
341                                 u64 dev_bytenr, u64 fs_bytenr, u64 csum_bytenr)
342 {
343         struct extent_buffer *buf = NULL;
344         u32 itemoff = __BTRFS_LEAF_DATA_SIZE(cfg->nodesize);
345         int slot = 0;
346         int ret;
347
348         /*
349          * Provided bytenr must in ascending order, or tree root will have a
350          * bad key order.
351          */
352         if (!(root_bytenr < extent_bytenr && extent_bytenr < dev_bytenr &&
353               dev_bytenr < fs_bytenr && fs_bytenr < csum_bytenr)) {
354                 error("bad tree bytenr order: "
355                                 "root < extent %llu < %llu, "
356                                 "extent < dev %llu < %llu, "
357                                 "dev < fs %llu < %llu, "
358                                 "fs < csum %llu < %llu",
359                                 (unsigned long long)root_bytenr,
360                                 (unsigned long long)extent_bytenr,
361                                 (unsigned long long)extent_bytenr,
362                                 (unsigned long long)dev_bytenr,
363                                 (unsigned long long)dev_bytenr,
364                                 (unsigned long long)fs_bytenr,
365                                 (unsigned long long)fs_bytenr,
366                                 (unsigned long long)csum_bytenr);
367                 return -EINVAL;
368         }
369         buf = malloc(sizeof(*buf) + cfg->nodesize);
370         if (!buf)
371                 return -ENOMEM;
372
373         ret = setup_temp_extent_buffer(buf, cfg, root_bytenr,
374                                        BTRFS_ROOT_TREE_OBJECTID);
375         if (ret < 0)
376                 goto out;
377
378         insert_temp_root_item(buf, cfg, &slot, &itemoff,
379                               BTRFS_EXTENT_TREE_OBJECTID, extent_bytenr);
380         insert_temp_root_item(buf, cfg, &slot, &itemoff,
381                               BTRFS_DEV_TREE_OBJECTID, dev_bytenr);
382         insert_temp_root_item(buf, cfg, &slot, &itemoff,
383                               BTRFS_FS_TREE_OBJECTID, fs_bytenr);
384         insert_temp_root_item(buf, cfg, &slot, &itemoff,
385                               BTRFS_CSUM_TREE_OBJECTID, csum_bytenr);
386
387         ret = write_temp_extent_buffer(fd, buf, root_bytenr);
388 out:
389         free(buf);
390         return ret;
391 }
392
393 static int insert_temp_dev_item(int fd, struct extent_buffer *buf,
394                                 struct btrfs_mkfs_config *cfg,
395                                 int *slot, u32 *itemoff)
396 {
397         struct btrfs_disk_key disk_key;
398         struct btrfs_dev_item *dev_item;
399         char super_buf[BTRFS_SUPER_INFO_SIZE];
400         unsigned char dev_uuid[BTRFS_UUID_SIZE];
401         unsigned char fsid[BTRFS_FSID_SIZE];
402         struct btrfs_super_block *super = (struct btrfs_super_block *)super_buf;
403         int ret;
404
405         ret = pread(fd, super_buf, BTRFS_SUPER_INFO_SIZE, cfg->super_bytenr);
406         if (ret < BTRFS_SUPER_INFO_SIZE) {
407                 ret = (ret < 0 ? -errno : -EIO);
408                 goto out;
409         }
410
411         btrfs_set_header_nritems(buf, *slot + 1);
412         (*itemoff) -= sizeof(*dev_item);
413         /* setup device item 1, 0 is for replace case */
414         btrfs_set_disk_key_type(&disk_key, BTRFS_DEV_ITEM_KEY);
415         btrfs_set_disk_key_objectid(&disk_key, BTRFS_DEV_ITEMS_OBJECTID);
416         btrfs_set_disk_key_offset(&disk_key, 1);
417         btrfs_set_item_key(buf, &disk_key, *slot);
418         btrfs_set_item_offset(buf, btrfs_item_nr(*slot), *itemoff);
419         btrfs_set_item_size(buf, btrfs_item_nr(*slot), sizeof(*dev_item));
420
421         dev_item = btrfs_item_ptr(buf, *slot, struct btrfs_dev_item);
422         /* Generate device uuid */
423         uuid_generate(dev_uuid);
424         write_extent_buffer(buf, dev_uuid,
425                         (unsigned long)btrfs_device_uuid(dev_item),
426                         BTRFS_UUID_SIZE);
427         uuid_parse(cfg->fs_uuid, fsid);
428         write_extent_buffer(buf, fsid,
429                         (unsigned long)btrfs_device_fsid(dev_item),
430                         BTRFS_FSID_SIZE);
431         btrfs_set_device_id(buf, dev_item, 1);
432         btrfs_set_device_generation(buf, dev_item, 0);
433         btrfs_set_device_total_bytes(buf, dev_item, cfg->num_bytes);
434         /*
435          * The number must match the initial SYSTEM and META chunk size
436          */
437         btrfs_set_device_bytes_used(buf, dev_item,
438                         BTRFS_MKFS_SYSTEM_GROUP_SIZE +
439                         BTRFS_CONVERT_META_GROUP_SIZE);
440         btrfs_set_device_io_align(buf, dev_item, cfg->sectorsize);
441         btrfs_set_device_io_width(buf, dev_item, cfg->sectorsize);
442         btrfs_set_device_sector_size(buf, dev_item, cfg->sectorsize);
443         btrfs_set_device_type(buf, dev_item, 0);
444
445         /* Super dev_item is not complete, copy the complete one to sb */
446         read_extent_buffer(buf, &super->dev_item, (unsigned long)dev_item,
447                            sizeof(*dev_item));
448         ret = write_temp_super(fd, super, cfg->super_bytenr);
449         (*slot)++;
450 out:
451         return ret;
452 }
453
454 static int insert_temp_chunk_item(int fd, struct extent_buffer *buf,
455                                   struct btrfs_mkfs_config *cfg,
456                                   int *slot, u32 *itemoff, u64 start, u64 len,
457                                   u64 type)
458 {
459         struct btrfs_chunk *chunk;
460         struct btrfs_disk_key disk_key;
461         char super_buf[BTRFS_SUPER_INFO_SIZE];
462         struct btrfs_super_block *sb = (struct btrfs_super_block *)super_buf;
463         int ret = 0;
464
465         ret = pread(fd, super_buf, BTRFS_SUPER_INFO_SIZE,
466                     cfg->super_bytenr);
467         if (ret < BTRFS_SUPER_INFO_SIZE) {
468                 ret = (ret < 0 ? ret : -EIO);
469                 return ret;
470         }
471
472         btrfs_set_header_nritems(buf, *slot + 1);
473         (*itemoff) -= btrfs_chunk_item_size(1);
474         btrfs_set_disk_key_type(&disk_key, BTRFS_CHUNK_ITEM_KEY);
475         btrfs_set_disk_key_objectid(&disk_key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
476         btrfs_set_disk_key_offset(&disk_key, start);
477         btrfs_set_item_key(buf, &disk_key, *slot);
478         btrfs_set_item_offset(buf, btrfs_item_nr(*slot), *itemoff);
479         btrfs_set_item_size(buf, btrfs_item_nr(*slot),
480                             btrfs_chunk_item_size(1));
481
482         chunk = btrfs_item_ptr(buf, *slot, struct btrfs_chunk);
483         btrfs_set_chunk_length(buf, chunk, len);
484         btrfs_set_chunk_owner(buf, chunk, BTRFS_EXTENT_TREE_OBJECTID);
485         btrfs_set_chunk_stripe_len(buf, chunk, BTRFS_STRIPE_LEN);
486         btrfs_set_chunk_type(buf, chunk, type);
487         btrfs_set_chunk_io_align(buf, chunk, cfg->sectorsize);
488         btrfs_set_chunk_io_width(buf, chunk, cfg->sectorsize);
489         btrfs_set_chunk_sector_size(buf, chunk, cfg->sectorsize);
490         btrfs_set_chunk_num_stripes(buf, chunk, 1);
491         /* TODO: Support DUP profile for system chunk */
492         btrfs_set_stripe_devid_nr(buf, chunk, 0, 1);
493         /* We are doing 1:1 mapping, so start is its dev offset */
494         btrfs_set_stripe_offset_nr(buf, chunk, 0, start);
495         write_extent_buffer(buf, &sb->dev_item.uuid,
496                             (unsigned long)btrfs_stripe_dev_uuid_nr(chunk, 0),
497                             BTRFS_UUID_SIZE);
498         (*slot)++;
499
500         /*
501          * If it's system chunk, also copy it to super block.
502          */
503         if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
504                 char *cur;
505                 u32 array_size;
506
507                 cur = (char *)sb->sys_chunk_array
508                         + btrfs_super_sys_array_size(sb);
509                 memcpy(cur, &disk_key, sizeof(disk_key));
510                 cur += sizeof(disk_key);
511                 read_extent_buffer(buf, cur, (unsigned long int)chunk,
512                                    btrfs_chunk_item_size(1));
513                 array_size = btrfs_super_sys_array_size(sb);
514                 array_size += btrfs_chunk_item_size(1) +
515                                             sizeof(disk_key);
516                 btrfs_set_super_sys_array_size(sb, array_size);
517
518                 ret = write_temp_super(fd, sb, cfg->super_bytenr);
519         }
520         return ret;
521 }
522
523 static int setup_temp_chunk_tree(int fd, struct btrfs_mkfs_config *cfg,
524                                  u64 sys_chunk_start, u64 meta_chunk_start,
525                                  u64 chunk_bytenr)
526 {
527         struct extent_buffer *buf = NULL;
528         u32 itemoff = __BTRFS_LEAF_DATA_SIZE(cfg->nodesize);
529         int slot = 0;
530         int ret;
531
532         /* Must ensure SYS chunk starts before META chunk */
533         if (meta_chunk_start < sys_chunk_start) {
534                 error("wrong chunk order: meta < system %llu < %llu",
535                                 (unsigned long long)meta_chunk_start,
536                                 (unsigned long long)sys_chunk_start);
537                 return -EINVAL;
538         }
539         buf = malloc(sizeof(*buf) + cfg->nodesize);
540         if (!buf)
541                 return -ENOMEM;
542         ret = setup_temp_extent_buffer(buf, cfg, chunk_bytenr,
543                                        BTRFS_CHUNK_TREE_OBJECTID);
544         if (ret < 0)
545                 goto out;
546
547         ret = insert_temp_dev_item(fd, buf, cfg, &slot, &itemoff);
548         if (ret < 0)
549                 goto out;
550         ret = insert_temp_chunk_item(fd, buf, cfg, &slot, &itemoff,
551                                      sys_chunk_start,
552                                      BTRFS_MKFS_SYSTEM_GROUP_SIZE,
553                                      BTRFS_BLOCK_GROUP_SYSTEM);
554         if (ret < 0)
555                 goto out;
556         ret = insert_temp_chunk_item(fd, buf, cfg, &slot, &itemoff,
557                                      meta_chunk_start,
558                                      BTRFS_CONVERT_META_GROUP_SIZE,
559                                      BTRFS_BLOCK_GROUP_METADATA);
560         if (ret < 0)
561                 goto out;
562         ret = write_temp_extent_buffer(fd, buf, chunk_bytenr);
563
564 out:
565         free(buf);
566         return ret;
567 }
568
569 static void insert_temp_dev_extent(struct extent_buffer *buf,
570                                    int *slot, u32 *itemoff, u64 start, u64 len)
571 {
572         struct btrfs_dev_extent *dev_extent;
573         struct btrfs_disk_key disk_key;
574
575         btrfs_set_header_nritems(buf, *slot + 1);
576         (*itemoff) -= sizeof(*dev_extent);
577         btrfs_set_disk_key_type(&disk_key, BTRFS_DEV_EXTENT_KEY);
578         btrfs_set_disk_key_objectid(&disk_key, 1);
579         btrfs_set_disk_key_offset(&disk_key, start);
580         btrfs_set_item_key(buf, &disk_key, *slot);
581         btrfs_set_item_offset(buf, btrfs_item_nr(*slot), *itemoff);
582         btrfs_set_item_size(buf, btrfs_item_nr(*slot), sizeof(*dev_extent));
583
584         dev_extent = btrfs_item_ptr(buf, *slot, struct btrfs_dev_extent);
585         btrfs_set_dev_extent_chunk_objectid(buf, dev_extent,
586                                             BTRFS_FIRST_CHUNK_TREE_OBJECTID);
587         btrfs_set_dev_extent_length(buf, dev_extent, len);
588         btrfs_set_dev_extent_chunk_offset(buf, dev_extent, start);
589         btrfs_set_dev_extent_chunk_tree(buf, dev_extent,
590                                         BTRFS_CHUNK_TREE_OBJECTID);
591         (*slot)++;
592 }
593
594 static int setup_temp_dev_tree(int fd, struct btrfs_mkfs_config *cfg,
595                                u64 sys_chunk_start, u64 meta_chunk_start,
596                                u64 dev_bytenr)
597 {
598         struct extent_buffer *buf = NULL;
599         u32 itemoff = __BTRFS_LEAF_DATA_SIZE(cfg->nodesize);
600         int slot = 0;
601         int ret;
602
603         /* Must ensure SYS chunk starts before META chunk */
604         if (meta_chunk_start < sys_chunk_start) {
605                 error("wrong chunk order: meta < system %llu < %llu",
606                                 (unsigned long long)meta_chunk_start,
607                                 (unsigned long long)sys_chunk_start);
608                 return -EINVAL;
609         }
610         buf = malloc(sizeof(*buf) + cfg->nodesize);
611         if (!buf)
612                 return -ENOMEM;
613         ret = setup_temp_extent_buffer(buf, cfg, dev_bytenr,
614                                        BTRFS_DEV_TREE_OBJECTID);
615         if (ret < 0)
616                 goto out;
617         insert_temp_dev_extent(buf, &slot, &itemoff, sys_chunk_start,
618                                BTRFS_MKFS_SYSTEM_GROUP_SIZE);
619         insert_temp_dev_extent(buf, &slot, &itemoff, meta_chunk_start,
620                                BTRFS_CONVERT_META_GROUP_SIZE);
621         ret = write_temp_extent_buffer(fd, buf, dev_bytenr);
622 out:
623         free(buf);
624         return ret;
625 }
626
627 static int setup_temp_fs_tree(int fd, struct btrfs_mkfs_config *cfg,
628                               u64 fs_bytenr)
629 {
630         struct extent_buffer *buf = NULL;
631         int ret;
632
633         buf = malloc(sizeof(*buf) + cfg->nodesize);
634         if (!buf)
635                 return -ENOMEM;
636         ret = setup_temp_extent_buffer(buf, cfg, fs_bytenr,
637                                        BTRFS_FS_TREE_OBJECTID);
638         if (ret < 0)
639                 goto out;
640         /*
641          * Temporary fs tree is completely empty.
642          */
643         ret = write_temp_extent_buffer(fd, buf, fs_bytenr);
644 out:
645         free(buf);
646         return ret;
647 }
648
649 static int setup_temp_csum_tree(int fd, struct btrfs_mkfs_config *cfg,
650                                 u64 csum_bytenr)
651 {
652         struct extent_buffer *buf = NULL;
653         int ret;
654
655         buf = malloc(sizeof(*buf) + cfg->nodesize);
656         if (!buf)
657                 return -ENOMEM;
658         ret = setup_temp_extent_buffer(buf, cfg, csum_bytenr,
659                                        BTRFS_CSUM_TREE_OBJECTID);
660         if (ret < 0)
661                 goto out;
662         /*
663          * Temporary csum tree is completely empty.
664          */
665         ret = write_temp_extent_buffer(fd, buf, csum_bytenr);
666 out:
667         free(buf);
668         return ret;
669 }
670
671 /*
672  * Insert one temporary extent item.
673  *
674  * NOTE: if skinny_metadata is not enabled, this function must be called
675  * after all other trees are initialized.
676  * Or fs without skinny-metadata will be screwed up.
677  */
678 static int insert_temp_extent_item(int fd, struct extent_buffer *buf,
679                                    struct btrfs_mkfs_config *cfg,
680                                    int *slot, u32 *itemoff, u64 bytenr,
681                                    u64 ref_root)
682 {
683         struct extent_buffer *tmp;
684         struct btrfs_extent_item *ei;
685         struct btrfs_extent_inline_ref *iref;
686         struct btrfs_disk_key disk_key;
687         struct btrfs_disk_key tree_info_key;
688         struct btrfs_tree_block_info *info;
689         int itemsize;
690         int skinny_metadata = cfg->features &
691                               BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA;
692         int ret;
693
694         if (skinny_metadata)
695                 itemsize = sizeof(*ei) + sizeof(*iref);
696         else
697                 itemsize = sizeof(*ei) + sizeof(*iref) +
698                            sizeof(struct btrfs_tree_block_info);
699
700         btrfs_set_header_nritems(buf, *slot + 1);
701         *(itemoff) -= itemsize;
702
703         if (skinny_metadata) {
704                 btrfs_set_disk_key_type(&disk_key, BTRFS_METADATA_ITEM_KEY);
705                 btrfs_set_disk_key_offset(&disk_key, 0);
706         } else {
707                 btrfs_set_disk_key_type(&disk_key, BTRFS_EXTENT_ITEM_KEY);
708                 btrfs_set_disk_key_offset(&disk_key, cfg->nodesize);
709         }
710         btrfs_set_disk_key_objectid(&disk_key, bytenr);
711
712         btrfs_set_item_key(buf, &disk_key, *slot);
713         btrfs_set_item_offset(buf, btrfs_item_nr(*slot), *itemoff);
714         btrfs_set_item_size(buf, btrfs_item_nr(*slot), itemsize);
715
716         ei = btrfs_item_ptr(buf, *slot, struct btrfs_extent_item);
717         btrfs_set_extent_refs(buf, ei, 1);
718         btrfs_set_extent_generation(buf, ei, 1);
719         btrfs_set_extent_flags(buf, ei, BTRFS_EXTENT_FLAG_TREE_BLOCK);
720
721         if (skinny_metadata) {
722                 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
723         } else {
724                 info = (struct btrfs_tree_block_info *)(ei + 1);
725                 iref = (struct btrfs_extent_inline_ref *)(info + 1);
726         }
727         btrfs_set_extent_inline_ref_type(buf, iref,
728                                          BTRFS_TREE_BLOCK_REF_KEY);
729         btrfs_set_extent_inline_ref_offset(buf, iref, ref_root);
730
731         (*slot)++;
732         if (skinny_metadata)
733                 return 0;
734
735         /*
736          * Lastly, check the tree block key by read the tree block
737          * Since we do 1:1 mapping for convert case, we can directly
738          * read the bytenr from disk
739          */
740         tmp = malloc(sizeof(*tmp) + cfg->nodesize);
741         if (!tmp)
742                 return -ENOMEM;
743         ret = setup_temp_extent_buffer(tmp, cfg, bytenr, ref_root);
744         if (ret < 0)
745                 goto out;
746         ret = pread(fd, tmp->data, cfg->nodesize, bytenr);
747         if (ret < cfg->nodesize) {
748                 ret = (ret < 0 ? -errno : -EIO);
749                 goto out;
750         }
751         if (btrfs_header_nritems(tmp) == 0) {
752                 btrfs_set_disk_key_type(&tree_info_key, 0);
753                 btrfs_set_disk_key_objectid(&tree_info_key, 0);
754                 btrfs_set_disk_key_offset(&tree_info_key, 0);
755         } else {
756                 btrfs_item_key(tmp, &tree_info_key, 0);
757         }
758         btrfs_set_tree_block_key(buf, info, &tree_info_key);
759
760 out:
761         free(tmp);
762         return ret;
763 }
764
765 static void insert_temp_block_group(struct extent_buffer *buf,
766                                    struct btrfs_mkfs_config *cfg,
767                                    int *slot, u32 *itemoff,
768                                    u64 bytenr, u64 len, u64 used, u64 flag)
769 {
770         struct btrfs_block_group_item bgi;
771         struct btrfs_disk_key disk_key;
772
773         btrfs_set_header_nritems(buf, *slot + 1);
774         (*itemoff) -= sizeof(bgi);
775         btrfs_set_disk_key_type(&disk_key, BTRFS_BLOCK_GROUP_ITEM_KEY);
776         btrfs_set_disk_key_objectid(&disk_key, bytenr);
777         btrfs_set_disk_key_offset(&disk_key, len);
778         btrfs_set_item_key(buf, &disk_key, *slot);
779         btrfs_set_item_offset(buf, btrfs_item_nr(*slot), *itemoff);
780         btrfs_set_item_size(buf, btrfs_item_nr(*slot), sizeof(bgi));
781
782         btrfs_set_block_group_flags(&bgi, flag);
783         btrfs_set_block_group_used(&bgi, used);
784         btrfs_set_block_group_chunk_objectid(&bgi,
785                         BTRFS_FIRST_CHUNK_TREE_OBJECTID);
786         write_extent_buffer(buf, &bgi, btrfs_item_ptr_offset(buf, *slot),
787                             sizeof(bgi));
788         (*slot)++;
789 }
790
791 static int setup_temp_extent_tree(int fd, struct btrfs_mkfs_config *cfg,
792                                   u64 chunk_bytenr, u64 root_bytenr,
793                                   u64 extent_bytenr, u64 dev_bytenr,
794                                   u64 fs_bytenr, u64 csum_bytenr)
795 {
796         struct extent_buffer *buf = NULL;
797         u32 itemoff = __BTRFS_LEAF_DATA_SIZE(cfg->nodesize);
798         int slot = 0;
799         int ret;
800
801         /*
802          * We must ensure provided bytenr are in ascending order,
803          * or extent tree key order will be broken.
804          */
805         if (!(chunk_bytenr < root_bytenr && root_bytenr < extent_bytenr &&
806               extent_bytenr < dev_bytenr && dev_bytenr < fs_bytenr &&
807               fs_bytenr < csum_bytenr)) {
808                 error("bad tree bytenr order: "
809                                 "chunk < root %llu < %llu, "
810                                 "root < extent %llu < %llu, "
811                                 "extent < dev %llu < %llu, "
812                                 "dev < fs %llu < %llu, "
813                                 "fs < csum %llu < %llu",
814                                 (unsigned long long)chunk_bytenr,
815                                 (unsigned long long)root_bytenr,
816                                 (unsigned long long)root_bytenr,
817                                 (unsigned long long)extent_bytenr,
818                                 (unsigned long long)extent_bytenr,
819                                 (unsigned long long)dev_bytenr,
820                                 (unsigned long long)dev_bytenr,
821                                 (unsigned long long)fs_bytenr,
822                                 (unsigned long long)fs_bytenr,
823                                 (unsigned long long)csum_bytenr);
824                 return -EINVAL;
825         }
826         buf = malloc(sizeof(*buf) + cfg->nodesize);
827         if (!buf)
828                 return -ENOMEM;
829
830         ret = setup_temp_extent_buffer(buf, cfg, extent_bytenr,
831                                        BTRFS_EXTENT_TREE_OBJECTID);
832         if (ret < 0)
833                 goto out;
834
835         ret = insert_temp_extent_item(fd, buf, cfg, &slot, &itemoff,
836                         chunk_bytenr, BTRFS_CHUNK_TREE_OBJECTID);
837         if (ret < 0)
838                 goto out;
839
840         insert_temp_block_group(buf, cfg, &slot, &itemoff, chunk_bytenr,
841                         BTRFS_MKFS_SYSTEM_GROUP_SIZE, cfg->nodesize,
842                         BTRFS_BLOCK_GROUP_SYSTEM);
843
844         ret = insert_temp_extent_item(fd, buf, cfg, &slot, &itemoff,
845                         root_bytenr, BTRFS_ROOT_TREE_OBJECTID);
846         if (ret < 0)
847                 goto out;
848
849         /* 5 tree block used, root, extent, dev, fs and csum*/
850         insert_temp_block_group(buf, cfg, &slot, &itemoff, root_bytenr,
851                         BTRFS_CONVERT_META_GROUP_SIZE, cfg->nodesize * 5,
852                         BTRFS_BLOCK_GROUP_METADATA);
853
854         ret = insert_temp_extent_item(fd, buf, cfg, &slot, &itemoff,
855                         extent_bytenr, BTRFS_EXTENT_TREE_OBJECTID);
856         if (ret < 0)
857                 goto out;
858         ret = insert_temp_extent_item(fd, buf, cfg, &slot, &itemoff,
859                         dev_bytenr, BTRFS_DEV_TREE_OBJECTID);
860         if (ret < 0)
861                 goto out;
862         ret = insert_temp_extent_item(fd, buf, cfg, &slot, &itemoff,
863                         fs_bytenr, BTRFS_FS_TREE_OBJECTID);
864         if (ret < 0)
865                 goto out;
866         ret = insert_temp_extent_item(fd, buf, cfg, &slot, &itemoff,
867                         csum_bytenr, BTRFS_CSUM_TREE_OBJECTID);
868         if (ret < 0)
869                 goto out;
870
871         ret = write_temp_extent_buffer(fd, buf, extent_bytenr);
872 out:
873         free(buf);
874         return ret;
875 }
876
877 /*
878  * Improved version of make_btrfs().
879  *
880  * This one will
881  * 1) Do chunk allocation to avoid used data
882  *    And after this function, extent type matches chunk type
883  * 2) Better structured code
884  *    No super long hand written codes to initialized all tree blocks
885  *    Split into small blocks and reuse codes.
886  *    TODO: Reuse tree operation facilities by introducing new flags
887  */
888 int make_convert_btrfs(int fd, struct btrfs_mkfs_config *cfg,
889                               struct btrfs_convert_context *cctx)
890 {
891         struct cache_tree *free = &cctx->free;
892         struct cache_tree *used = &cctx->used;
893         u64 sys_chunk_start;
894         u64 meta_chunk_start;
895         /* chunk tree bytenr, in system chunk */
896         u64 chunk_bytenr;
897         /* metadata trees bytenr, in metadata chunk */
898         u64 root_bytenr;
899         u64 extent_bytenr;
900         u64 dev_bytenr;
901         u64 fs_bytenr;
902         u64 csum_bytenr;
903         int ret;
904
905         /* Shouldn't happen */
906         BUG_ON(cache_tree_empty(used));
907
908         /*
909          * reserve space for temporary superblock first
910          * Here we allocate a little larger space, to keep later
911          * free space will be STRIPE_LEN aligned
912          */
913         ret = reserve_free_space(free, BTRFS_STRIPE_LEN,
914                                  &cfg->super_bytenr);
915         if (ret < 0)
916                 goto out;
917
918         /*
919          * Then reserve system chunk space
920          * TODO: Change system group size depending on cctx->total_bytes.
921          * If using current 4M, it can only handle less than one TB for
922          * worst case and then run out of sys space.
923          */
924         ret = reserve_free_space(free, BTRFS_MKFS_SYSTEM_GROUP_SIZE,
925                                  &sys_chunk_start);
926         if (ret < 0)
927                 goto out;
928         ret = reserve_free_space(free, BTRFS_CONVERT_META_GROUP_SIZE,
929                                  &meta_chunk_start);
930         if (ret < 0)
931                 goto out;
932
933         /*
934          * Allocated meta/sys chunks will be mapped 1:1 with device offset.
935          *
936          * Inside the allocated metadata chunk, the layout will be:
937          *  | offset            | contents      |
938          *  -------------------------------------
939          *  | +0                | tree root     |
940          *  | +nodesize         | extent root   |
941          *  | +nodesize * 2     | device root   |
942          *  | +nodesize * 3     | fs tree       |
943          *  | +nodesize * 4     | csum tree     |
944          *  -------------------------------------
945          * Inside the allocated system chunk, the layout will be:
946          *  | offset            | contents      |
947          *  -------------------------------------
948          *  | +0                | chunk root    |
949          *  -------------------------------------
950          */
951         chunk_bytenr = sys_chunk_start;
952         root_bytenr = meta_chunk_start;
953         extent_bytenr = meta_chunk_start + cfg->nodesize;
954         dev_bytenr = meta_chunk_start + cfg->nodesize * 2;
955         fs_bytenr = meta_chunk_start + cfg->nodesize * 3;
956         csum_bytenr = meta_chunk_start + cfg->nodesize * 4;
957
958         ret = setup_temp_super(fd, cfg, root_bytenr, chunk_bytenr);
959         if (ret < 0)
960                 goto out;
961
962         ret = setup_temp_root_tree(fd, cfg, root_bytenr, extent_bytenr,
963                                    dev_bytenr, fs_bytenr, csum_bytenr);
964         if (ret < 0)
965                 goto out;
966         ret = setup_temp_chunk_tree(fd, cfg, sys_chunk_start, meta_chunk_start,
967                                     chunk_bytenr);
968         if (ret < 0)
969                 goto out;
970         ret = setup_temp_dev_tree(fd, cfg, sys_chunk_start, meta_chunk_start,
971                                   dev_bytenr);
972         if (ret < 0)
973                 goto out;
974         ret = setup_temp_fs_tree(fd, cfg, fs_bytenr);
975         if (ret < 0)
976                 goto out;
977         ret = setup_temp_csum_tree(fd, cfg, csum_bytenr);
978         if (ret < 0)
979                 goto out;
980         /*
981          * Setup extent tree last, since it may need to read tree block key
982          * for non-skinny metadata case.
983          */
984         ret = setup_temp_extent_tree(fd, cfg, chunk_bytenr, root_bytenr,
985                                      extent_bytenr, dev_bytenr, fs_bytenr,
986                                      csum_bytenr);
987 out:
988         return ret;
989 }
990
991 #define VERSION_TO_STRING3(a,b,c)       #a "." #b "." #c, KERNEL_VERSION(a,b,c)
992 #define VERSION_TO_STRING2(a,b)         #a "." #b, KERNEL_VERSION(a,b,0)
993
994 /*
995  * Feature stability status and versions: compat <= safe <= default
996  */
997 static const struct btrfs_fs_feature {
998         const char *name;
999         u64 flag;
1000         const char *sysfs_name;
1001         /*
1002          * Compatibility with kernel of given version. Filesystem can be
1003          * mounted.
1004          */
1005         const char *compat_str;
1006         u32 compat_ver;
1007         /*
1008          * Considered safe for use, but is not on by default, even if the
1009          * kernel supports the feature.
1010          */
1011         const char *safe_str;
1012         u32 safe_ver;
1013         /*
1014          * Considered safe for use and will be turned on by default if
1015          * supported by the running kernel.
1016          */
1017         const char *default_str;
1018         u32 default_ver;
1019         const char *desc;
1020 } mkfs_features[] = {
1021         { "mixed-bg", BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS,
1022                 "mixed_groups",
1023                 VERSION_TO_STRING3(2,6,37),
1024                 VERSION_TO_STRING3(2,6,37),
1025                 NULL, 0,
1026                 "mixed data and metadata block groups" },
1027         { "extref", BTRFS_FEATURE_INCOMPAT_EXTENDED_IREF,
1028                 "extended_iref",
1029                 VERSION_TO_STRING2(3,7),
1030                 VERSION_TO_STRING2(3,12),
1031                 VERSION_TO_STRING2(3,12),
1032                 "increased hardlink limit per file to 65536" },
1033         { "raid56", BTRFS_FEATURE_INCOMPAT_RAID56,
1034                 "raid56",
1035                 VERSION_TO_STRING2(3,9),
1036                 NULL, 0,
1037                 NULL, 0,
1038                 "raid56 extended format" },
1039         { "skinny-metadata", BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA,
1040                 "skinny_metadata",
1041                 VERSION_TO_STRING2(3,10),
1042                 VERSION_TO_STRING2(3,18),
1043                 VERSION_TO_STRING2(3,18),
1044                 "reduced-size metadata extent refs" },
1045         { "no-holes", BTRFS_FEATURE_INCOMPAT_NO_HOLES,
1046                 "no_holes",
1047                 VERSION_TO_STRING2(3,14),
1048                 VERSION_TO_STRING2(4,0),
1049                 NULL, 0,
1050                 "no explicit hole extents for files" },
1051         /* Keep this one last */
1052         { "list-all", BTRFS_FEATURE_LIST_ALL, NULL }
1053 };
1054
1055 static int parse_one_fs_feature(const char *name, u64 *flags)
1056 {
1057         int i;
1058         int found = 0;
1059
1060         for (i = 0; i < ARRAY_SIZE(mkfs_features); i++) {
1061                 if (name[0] == '^' &&
1062                         !strcmp(mkfs_features[i].name, name + 1)) {
1063                         *flags &= ~ mkfs_features[i].flag;
1064                         found = 1;
1065                 } else if (!strcmp(mkfs_features[i].name, name)) {
1066                         *flags |= mkfs_features[i].flag;
1067                         found = 1;
1068                 }
1069         }
1070
1071         return !found;
1072 }
1073
1074 void btrfs_parse_features_to_string(char *buf, u64 flags)
1075 {
1076         int i;
1077
1078         buf[0] = 0;
1079
1080         for (i = 0; i < ARRAY_SIZE(mkfs_features); i++) {
1081                 if (flags & mkfs_features[i].flag) {
1082                         if (*buf)
1083                                 strcat(buf, ", ");
1084                         strcat(buf, mkfs_features[i].name);
1085                 }
1086         }
1087 }
1088
1089 void btrfs_process_fs_features(u64 flags)
1090 {
1091         int i;
1092
1093         for (i = 0; i < ARRAY_SIZE(mkfs_features); i++) {
1094                 if (flags & mkfs_features[i].flag) {
1095                         printf("Turning ON incompat feature '%s': %s\n",
1096                                 mkfs_features[i].name,
1097                                 mkfs_features[i].desc);
1098                 }
1099         }
1100 }
1101
1102 void btrfs_list_all_fs_features(u64 mask_disallowed)
1103 {
1104         int i;
1105
1106         fprintf(stderr, "Filesystem features available:\n");
1107         for (i = 0; i < ARRAY_SIZE(mkfs_features) - 1; i++) {
1108                 const struct btrfs_fs_feature *feat = &mkfs_features[i];
1109
1110                 if (feat->flag & mask_disallowed)
1111                         continue;
1112                 fprintf(stderr, "%-20s- %s (0x%llx", feat->name, feat->desc,
1113                                 feat->flag);
1114                 if (feat->compat_ver)
1115                         fprintf(stderr, ", compat=%s", feat->compat_str);
1116                 if (feat->safe_ver)
1117                         fprintf(stderr, ", safe=%s", feat->safe_str);
1118                 if (feat->default_ver)
1119                         fprintf(stderr, ", default=%s", feat->default_str);
1120                 fprintf(stderr, ")\n");
1121         }
1122 }
1123
1124 /*
1125  * Return NULL if all features were parsed fine, otherwise return the name of
1126  * the first unparsed.
1127  */
1128 char* btrfs_parse_fs_features(char *namelist, u64 *flags)
1129 {
1130         char *this_char;
1131         char *save_ptr = NULL; /* Satisfy static checkers */
1132
1133         for (this_char = strtok_r(namelist, ",", &save_ptr);
1134              this_char != NULL;
1135              this_char = strtok_r(NULL, ",", &save_ptr)) {
1136                 if (parse_one_fs_feature(this_char, flags))
1137                         return this_char;
1138         }
1139
1140         return NULL;
1141 }
1142
1143 void print_kernel_version(FILE *stream, u32 version)
1144 {
1145         u32 v[3];
1146
1147         v[0] = version & 0xFF;
1148         v[1] = (version >> 8) & 0xFF;
1149         v[2] = version >> 16;
1150         fprintf(stream, "%u.%u", v[2], v[1]);
1151         if (v[0])
1152                 fprintf(stream, ".%u", v[0]);
1153 }
1154
1155 u32 get_running_kernel_version(void)
1156 {
1157         struct utsname utsbuf;
1158         char *tmp;
1159         char *saveptr = NULL;
1160         u32 version;
1161
1162         uname(&utsbuf);
1163         if (strcmp(utsbuf.sysname, "Linux") != 0) {
1164                 error("unsupported system: %s", utsbuf.sysname);
1165                 exit(1);
1166         }
1167         /* 1.2.3-4-name */
1168         tmp = strchr(utsbuf.release, '-');
1169         if (tmp)
1170                 *tmp = 0;
1171
1172         tmp = strtok_r(utsbuf.release, ".", &saveptr);
1173         if (!string_is_numerical(tmp))
1174                 return (u32)-1;
1175         version = atoi(tmp) << 16;
1176         tmp = strtok_r(NULL, ".", &saveptr);
1177         if (!string_is_numerical(tmp))
1178                 return (u32)-1;
1179         version |= atoi(tmp) << 8;
1180         tmp = strtok_r(NULL, ".", &saveptr);
1181         if (tmp) {
1182                 if (!string_is_numerical(tmp))
1183                         return (u32)-1;
1184                 version |= atoi(tmp);
1185         }
1186
1187         return version;
1188 }
1189
1190 u64 btrfs_device_size(int fd, struct stat *st)
1191 {
1192         u64 size;
1193         if (S_ISREG(st->st_mode)) {
1194                 return st->st_size;
1195         }
1196         if (!S_ISBLK(st->st_mode)) {
1197                 return 0;
1198         }
1199         if (ioctl(fd, BLKGETSIZE64, &size) >= 0) {
1200                 return size;
1201         }
1202         return 0;
1203 }
1204
1205 static int zero_blocks(int fd, off_t start, size_t len)
1206 {
1207         char *buf = malloc(len);
1208         int ret = 0;
1209         ssize_t written;
1210
1211         if (!buf)
1212                 return -ENOMEM;
1213         memset(buf, 0, len);
1214         written = pwrite(fd, buf, len, start);
1215         if (written != len)
1216                 ret = -EIO;
1217         free(buf);
1218         return ret;
1219 }
1220
1221 #define ZERO_DEV_BYTES SZ_2M
1222
1223 /* don't write outside the device by clamping the region to the device size */
1224 static int zero_dev_clamped(int fd, off_t start, ssize_t len, u64 dev_size)
1225 {
1226         off_t end = max(start, start + len);
1227
1228 #ifdef __sparc__
1229         /* and don't overwrite the disk labels on sparc */
1230         start = max(start, 1024);
1231         end = max(end, 1024);
1232 #endif
1233
1234         start = min_t(u64, start, dev_size);
1235         end = min_t(u64, end, dev_size);
1236
1237         return zero_blocks(fd, start, end - start);
1238 }
1239
1240 int btrfs_add_to_fsid(struct btrfs_trans_handle *trans,
1241                       struct btrfs_root *root, int fd, const char *path,
1242                       u64 device_total_bytes, u32 io_width, u32 io_align,
1243                       u32 sectorsize)
1244 {
1245         struct btrfs_super_block *disk_super;
1246         struct btrfs_super_block *super = root->fs_info->super_copy;
1247         struct btrfs_device *device;
1248         struct btrfs_dev_item *dev_item;
1249         char *buf = NULL;
1250         u64 fs_total_bytes;
1251         u64 num_devs;
1252         int ret;
1253
1254         device_total_bytes = (device_total_bytes / sectorsize) * sectorsize;
1255
1256         device = calloc(1, sizeof(*device));
1257         if (!device) {
1258                 ret = -ENOMEM;
1259                 goto out;
1260         }
1261         buf = calloc(1, sectorsize);
1262         if (!buf) {
1263                 ret = -ENOMEM;
1264                 goto out;
1265         }
1266
1267         disk_super = (struct btrfs_super_block *)buf;
1268         dev_item = &disk_super->dev_item;
1269
1270         uuid_generate(device->uuid);
1271         device->devid = 0;
1272         device->type = 0;
1273         device->io_width = io_width;
1274         device->io_align = io_align;
1275         device->sector_size = sectorsize;
1276         device->fd = fd;
1277         device->writeable = 1;
1278         device->total_bytes = device_total_bytes;
1279         device->bytes_used = 0;
1280         device->total_ios = 0;
1281         device->dev_root = root->fs_info->dev_root;
1282         device->name = strdup(path);
1283         if (!device->name) {
1284                 ret = -ENOMEM;
1285                 goto out;
1286         }
1287
1288         INIT_LIST_HEAD(&device->dev_list);
1289         ret = btrfs_add_device(trans, root, device);
1290         if (ret)
1291                 goto out;
1292
1293         fs_total_bytes = btrfs_super_total_bytes(super) + device_total_bytes;
1294         btrfs_set_super_total_bytes(super, fs_total_bytes);
1295
1296         num_devs = btrfs_super_num_devices(super) + 1;
1297         btrfs_set_super_num_devices(super, num_devs);
1298
1299         memcpy(disk_super, super, sizeof(*disk_super));
1300
1301         btrfs_set_super_bytenr(disk_super, BTRFS_SUPER_INFO_OFFSET);
1302         btrfs_set_stack_device_id(dev_item, device->devid);
1303         btrfs_set_stack_device_type(dev_item, device->type);
1304         btrfs_set_stack_device_io_align(dev_item, device->io_align);
1305         btrfs_set_stack_device_io_width(dev_item, device->io_width);
1306         btrfs_set_stack_device_sector_size(dev_item, device->sector_size);
1307         btrfs_set_stack_device_total_bytes(dev_item, device->total_bytes);
1308         btrfs_set_stack_device_bytes_used(dev_item, device->bytes_used);
1309         memcpy(&dev_item->uuid, device->uuid, BTRFS_UUID_SIZE);
1310
1311         ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
1312         BUG_ON(ret != sectorsize);
1313
1314         free(buf);
1315         list_add(&device->dev_list, &root->fs_info->fs_devices->devices);
1316         device->fs_devices = root->fs_info->fs_devices;
1317         return 0;
1318
1319 out:
1320         free(device);
1321         free(buf);
1322         return ret;
1323 }
1324
1325 static int btrfs_wipe_existing_sb(int fd)
1326 {
1327         const char *off = NULL;
1328         size_t len = 0;
1329         loff_t offset;
1330         char buf[BUFSIZ];
1331         int ret = 0;
1332         blkid_probe pr = NULL;
1333
1334         pr = blkid_new_probe();
1335         if (!pr)
1336                 return -1;
1337
1338         if (blkid_probe_set_device(pr, fd, 0, 0)) {
1339                 ret = -1;
1340                 goto out;
1341         }
1342
1343         ret = blkid_probe_lookup_value(pr, "SBMAGIC_OFFSET", &off, NULL);
1344         if (!ret)
1345                 ret = blkid_probe_lookup_value(pr, "SBMAGIC", NULL, &len);
1346
1347         if (ret || len == 0 || off == NULL) {
1348                 /*
1349                  * If lookup fails, the probe did not find any values, eg. for
1350                  * a file image or a loop device. Soft error.
1351                  */
1352                 ret = 1;
1353                 goto out;
1354         }
1355
1356         offset = strtoll(off, NULL, 10);
1357         if (len > sizeof(buf))
1358                 len = sizeof(buf);
1359
1360         memset(buf, 0, len);
1361         ret = pwrite(fd, buf, len, offset);
1362         if (ret < 0) {
1363                 error("cannot wipe existing superblock: %s", strerror(errno));
1364                 ret = -1;
1365         } else if (ret != len) {
1366                 error("cannot wipe existing superblock: wrote %d of %zd", ret, len);
1367                 ret = -1;
1368         }
1369         fsync(fd);
1370
1371 out:
1372         blkid_free_probe(pr);
1373         return ret;
1374 }
1375
1376 int btrfs_prepare_device(int fd, const char *file, u64 *block_count_ret,
1377                 u64 max_block_count, unsigned opflags)
1378 {
1379         u64 block_count;
1380         struct stat st;
1381         int i, ret;
1382
1383         ret = fstat(fd, &st);
1384         if (ret < 0) {
1385                 error("unable to stat %s: %s", file, strerror(errno));
1386                 return 1;
1387         }
1388
1389         block_count = btrfs_device_size(fd, &st);
1390         if (block_count == 0) {
1391                 error("unable to determine size of %s", file);
1392                 return 1;
1393         }
1394         if (max_block_count)
1395                 block_count = min(block_count, max_block_count);
1396
1397         if (opflags & PREP_DEVICE_DISCARD) {
1398                 /*
1399                  * We intentionally ignore errors from the discard ioctl.  It
1400                  * is not necessary for the mkfs functionality but just an
1401                  * optimization.
1402                  */
1403                 if (discard_range(fd, 0, 0) == 0) {
1404                         if (opflags & PREP_DEVICE_VERBOSE)
1405                                 printf("Performing full device TRIM %s (%s) ...\n",
1406                                                 file, pretty_size(block_count));
1407                         discard_blocks(fd, 0, block_count);
1408                 }
1409         }
1410
1411         ret = zero_dev_clamped(fd, 0, ZERO_DEV_BYTES, block_count);
1412         for (i = 0 ; !ret && i < BTRFS_SUPER_MIRROR_MAX; i++)
1413                 ret = zero_dev_clamped(fd, btrfs_sb_offset(i),
1414                                        BTRFS_SUPER_INFO_SIZE, block_count);
1415         if (!ret && (opflags & PREP_DEVICE_ZERO_END))
1416                 ret = zero_dev_clamped(fd, block_count - ZERO_DEV_BYTES,
1417                                        ZERO_DEV_BYTES, block_count);
1418
1419         if (ret < 0) {
1420                 error("failed to zero device '%s': %s", file, strerror(-ret));
1421                 return 1;
1422         }
1423
1424         ret = btrfs_wipe_existing_sb(fd);
1425         if (ret < 0) {
1426                 error("cannot wipe superblocks on %s", file);
1427                 return 1;
1428         }
1429
1430         *block_count_ret = block_count;
1431         return 0;
1432 }
1433
1434 int btrfs_make_root_dir(struct btrfs_trans_handle *trans,
1435                         struct btrfs_root *root, u64 objectid)
1436 {
1437         int ret;
1438         struct btrfs_inode_item inode_item;
1439         time_t now = time(NULL);
1440
1441         memset(&inode_item, 0, sizeof(inode_item));
1442         btrfs_set_stack_inode_generation(&inode_item, trans->transid);
1443         btrfs_set_stack_inode_size(&inode_item, 0);
1444         btrfs_set_stack_inode_nlink(&inode_item, 1);
1445         btrfs_set_stack_inode_nbytes(&inode_item, root->nodesize);
1446         btrfs_set_stack_inode_mode(&inode_item, S_IFDIR | 0755);
1447         btrfs_set_stack_timespec_sec(&inode_item.atime, now);
1448         btrfs_set_stack_timespec_nsec(&inode_item.atime, 0);
1449         btrfs_set_stack_timespec_sec(&inode_item.ctime, now);
1450         btrfs_set_stack_timespec_nsec(&inode_item.ctime, 0);
1451         btrfs_set_stack_timespec_sec(&inode_item.mtime, now);
1452         btrfs_set_stack_timespec_nsec(&inode_item.mtime, 0);
1453         btrfs_set_stack_timespec_sec(&inode_item.otime, now);
1454         btrfs_set_stack_timespec_nsec(&inode_item.otime, 0);
1455
1456         if (root->fs_info->tree_root == root)
1457                 btrfs_set_super_root_dir(root->fs_info->super_copy, objectid);
1458
1459         ret = btrfs_insert_inode(trans, root, objectid, &inode_item);
1460         if (ret)
1461                 goto error;
1462
1463         ret = btrfs_insert_inode_ref(trans, root, "..", 2, objectid, objectid, 0);
1464         if (ret)
1465                 goto error;
1466
1467         btrfs_set_root_dirid(&root->root_item, objectid);
1468         ret = 0;
1469 error:
1470         return ret;
1471 }
1472
1473 /*
1474  * checks if a path is a block device node
1475  * Returns negative errno on failure, otherwise
1476  * returns 1 for blockdev, 0 for not-blockdev
1477  */
1478 int is_block_device(const char *path)
1479 {
1480         struct stat statbuf;
1481
1482         if (stat(path, &statbuf) < 0)
1483                 return -errno;
1484
1485         return !!S_ISBLK(statbuf.st_mode);
1486 }
1487
1488 /*
1489  * check if given path is a mount point
1490  * return 1 if yes. 0 if no. -1 for error
1491  */
1492 int is_mount_point(const char *path)
1493 {
1494         FILE *f;
1495         struct mntent *mnt;
1496         int ret = 0;
1497
1498         f = setmntent("/proc/self/mounts", "r");
1499         if (f == NULL)
1500                 return -1;
1501
1502         while ((mnt = getmntent(f)) != NULL) {
1503                 if (strcmp(mnt->mnt_dir, path))
1504                         continue;
1505                 ret = 1;
1506                 break;
1507         }
1508         endmntent(f);
1509         return ret;
1510 }
1511
1512 static int is_reg_file(const char *path)
1513 {
1514         struct stat statbuf;
1515
1516         if (stat(path, &statbuf) < 0)
1517                 return -errno;
1518         return S_ISREG(statbuf.st_mode);
1519 }
1520
1521 /*
1522  * This function checks if the given input parameter is
1523  * an uuid or a path
1524  * return <0 : some error in the given input
1525  * return BTRFS_ARG_UNKNOWN:    unknown input
1526  * return BTRFS_ARG_UUID:       given input is uuid
1527  * return BTRFS_ARG_MNTPOINT:   given input is path
1528  * return BTRFS_ARG_REG:        given input is regular file
1529  * return BTRFS_ARG_BLKDEV:     given input is block device
1530  */
1531 int check_arg_type(const char *input)
1532 {
1533         uuid_t uuid;
1534         char path[PATH_MAX];
1535
1536         if (!input)
1537                 return -EINVAL;
1538
1539         if (realpath(input, path)) {
1540                 if (is_block_device(path) == 1)
1541                         return BTRFS_ARG_BLKDEV;
1542
1543                 if (is_mount_point(path) == 1)
1544                         return BTRFS_ARG_MNTPOINT;
1545
1546                 if (is_reg_file(path))
1547                         return BTRFS_ARG_REG;
1548
1549                 return BTRFS_ARG_UNKNOWN;
1550         }
1551
1552         if (strlen(input) == (BTRFS_UUID_UNPARSED_SIZE - 1) &&
1553                 !uuid_parse(input, uuid))
1554                 return BTRFS_ARG_UUID;
1555
1556         return BTRFS_ARG_UNKNOWN;
1557 }
1558
1559 /*
1560  * Find the mount point for a mounted device.
1561  * On success, returns 0 with mountpoint in *mp.
1562  * On failure, returns -errno (not mounted yields -EINVAL)
1563  * Is noisy on failures, expects to be given a mounted device.
1564  */
1565 int get_btrfs_mount(const char *dev, char *mp, size_t mp_size)
1566 {
1567         int ret;
1568         int fd = -1;
1569
1570         ret = is_block_device(dev);
1571         if (ret <= 0) {
1572                 if (!ret) {
1573                         error("not a block device: %s", dev);
1574                         ret = -EINVAL;
1575                 } else {
1576                         error("cannot check %s: %s", dev, strerror(-ret));
1577                 }
1578                 goto out;
1579         }
1580
1581         fd = open(dev, O_RDONLY);
1582         if (fd < 0) {
1583                 ret = -errno;
1584                 error("cannot open %s: %s", dev, strerror(errno));
1585                 goto out;
1586         }
1587
1588         ret = check_mounted_where(fd, dev, mp, mp_size, NULL);
1589         if (!ret) {
1590                 ret = -EINVAL;
1591         } else { /* mounted, all good */
1592                 ret = 0;
1593         }
1594 out:
1595         if (fd != -1)
1596                 close(fd);
1597         return ret;
1598 }
1599
1600 /*
1601  * Given a pathname, return a filehandle to:
1602  *      the original pathname or,
1603  *      if the pathname is a mounted btrfs device, to its mountpoint.
1604  *
1605  * On error, return -1, errno should be set.
1606  */
1607 int open_path_or_dev_mnt(const char *path, DIR **dirstream, int verbose)
1608 {
1609         char mp[PATH_MAX];
1610         int ret;
1611
1612         if (is_block_device(path)) {
1613                 ret = get_btrfs_mount(path, mp, sizeof(mp));
1614                 if (ret < 0) {
1615                         /* not a mounted btrfs dev */
1616                         error_on(verbose, "'%s' is not a mounted btrfs device",
1617                                  path);
1618                         errno = EINVAL;
1619                         return -1;
1620                 }
1621                 ret = open_file_or_dir(mp, dirstream);
1622                 error_on(verbose && ret < 0, "can't access '%s': %s",
1623                          path, strerror(errno));
1624         } else {
1625                 ret = btrfs_open_dir(path, dirstream, 1);
1626         }
1627
1628         return ret;
1629 }
1630
1631 /*
1632  * Do the following checks before calling open_file_or_dir():
1633  * 1: path is in a btrfs filesystem
1634  * 2: path is a directory
1635  */
1636 int btrfs_open_dir(const char *path, DIR **dirstream, int verbose)
1637 {
1638         struct statfs stfs;
1639         struct stat st;
1640         int ret;
1641
1642         if (statfs(path, &stfs) != 0) {
1643                 error_on(verbose, "cannot access '%s': %s", path,
1644                                 strerror(errno));
1645                 return -1;
1646         }
1647
1648         if (stfs.f_type != BTRFS_SUPER_MAGIC) {
1649                 error_on(verbose, "not a btrfs filesystem: %s", path);
1650                 return -2;
1651         }
1652
1653         if (stat(path, &st) != 0) {
1654                 error_on(verbose, "cannot access '%s': %s", path,
1655                                 strerror(errno));
1656                 return -1;
1657         }
1658
1659         if (!S_ISDIR(st.st_mode)) {
1660                 error_on(verbose, "not a directory: %s", path);
1661                 return -3;
1662         }
1663
1664         ret = open_file_or_dir(path, dirstream);
1665         if (ret < 0) {
1666                 error_on(verbose, "cannot access '%s': %s", path,
1667                                 strerror(errno));
1668         }
1669
1670         return ret;
1671 }
1672
1673 /* checks if a device is a loop device */
1674 static int is_loop_device (const char* device) {
1675         struct stat statbuf;
1676
1677         if(stat(device, &statbuf) < 0)
1678                 return -errno;
1679
1680         return (S_ISBLK(statbuf.st_mode) &&
1681                 MAJOR(statbuf.st_rdev) == LOOP_MAJOR);
1682 }
1683
1684 /*
1685  * Takes a loop device path (e.g. /dev/loop0) and returns
1686  * the associated file (e.g. /images/my_btrfs.img) using
1687  * loopdev API
1688  */
1689 static int resolve_loop_device_with_loopdev(const char* loop_dev, char* loop_file)
1690 {
1691         int fd;
1692         int ret;
1693         struct loop_info64 lo64;
1694
1695         fd = open(loop_dev, O_RDONLY | O_NONBLOCK);
1696         if (fd < 0)
1697                 return -errno;
1698         ret = ioctl(fd, LOOP_GET_STATUS64, &lo64);
1699         if (ret < 0) {
1700                 ret = -errno;
1701                 goto out;
1702         }
1703
1704         memcpy(loop_file, lo64.lo_file_name, sizeof(lo64.lo_file_name));
1705         loop_file[sizeof(lo64.lo_file_name)] = 0;
1706
1707 out:
1708         close(fd);
1709
1710         return ret;
1711 }
1712
1713 /* Takes a loop device path (e.g. /dev/loop0) and returns
1714  * the associated file (e.g. /images/my_btrfs.img) */
1715 static int resolve_loop_device(const char* loop_dev, char* loop_file,
1716                 int max_len)
1717 {
1718         int ret;
1719         FILE *f;
1720         char fmt[20];
1721         char p[PATH_MAX];
1722         char real_loop_dev[PATH_MAX];
1723
1724         if (!realpath(loop_dev, real_loop_dev))
1725                 return -errno;
1726         snprintf(p, PATH_MAX, "/sys/block/%s/loop/backing_file", strrchr(real_loop_dev, '/'));
1727         if (!(f = fopen(p, "r"))) {
1728                 if (errno == ENOENT)
1729                         /*
1730                          * It's possibly a partitioned loop device, which is
1731                          * resolvable with loopdev API.
1732                          */
1733                         return resolve_loop_device_with_loopdev(loop_dev, loop_file);
1734                 return -errno;
1735         }
1736
1737         snprintf(fmt, 20, "%%%i[^\n]", max_len-1);
1738         ret = fscanf(f, fmt, loop_file);
1739         fclose(f);
1740         if (ret == EOF)
1741                 return -errno;
1742
1743         return 0;
1744 }
1745
1746 /*
1747  * Checks whether a and b are identical or device
1748  * files associated with the same block device
1749  */
1750 static int is_same_blk_file(const char* a, const char* b)
1751 {
1752         struct stat st_buf_a, st_buf_b;
1753         char real_a[PATH_MAX];
1754         char real_b[PATH_MAX];
1755
1756         if (!realpath(a, real_a))
1757                 strncpy_null(real_a, a);
1758
1759         if (!realpath(b, real_b))
1760                 strncpy_null(real_b, b);
1761
1762         /* Identical path? */
1763         if (strcmp(real_a, real_b) == 0)
1764                 return 1;
1765
1766         if (stat(a, &st_buf_a) < 0 || stat(b, &st_buf_b) < 0) {
1767                 if (errno == ENOENT)
1768                         return 0;
1769                 return -errno;
1770         }
1771
1772         /* Same blockdevice? */
1773         if (S_ISBLK(st_buf_a.st_mode) && S_ISBLK(st_buf_b.st_mode) &&
1774             st_buf_a.st_rdev == st_buf_b.st_rdev) {
1775                 return 1;
1776         }
1777
1778         /* Hardlink? */
1779         if (st_buf_a.st_dev == st_buf_b.st_dev &&
1780             st_buf_a.st_ino == st_buf_b.st_ino) {
1781                 return 1;
1782         }
1783
1784         return 0;
1785 }
1786
1787 /* checks if a and b are identical or device
1788  * files associated with the same block device or
1789  * if one file is a loop device that uses the other
1790  * file.
1791  */
1792 static int is_same_loop_file(const char* a, const char* b)
1793 {
1794         char res_a[PATH_MAX];
1795         char res_b[PATH_MAX];
1796         const char* final_a = NULL;
1797         const char* final_b = NULL;
1798         int ret;
1799
1800         /* Resolve a if it is a loop device */
1801         if((ret = is_loop_device(a)) < 0) {
1802                 if (ret == -ENOENT)
1803                         return 0;
1804                 return ret;
1805         } else if (ret) {
1806                 ret = resolve_loop_device(a, res_a, sizeof(res_a));
1807                 if (ret < 0) {
1808                         if (errno != EPERM)
1809                                 return ret;
1810                 } else {
1811                         final_a = res_a;
1812                 }
1813         } else {
1814                 final_a = a;
1815         }
1816
1817         /* Resolve b if it is a loop device */
1818         if ((ret = is_loop_device(b)) < 0) {
1819                 if (ret == -ENOENT)
1820                         return 0;
1821                 return ret;
1822         } else if (ret) {
1823                 ret = resolve_loop_device(b, res_b, sizeof(res_b));
1824                 if (ret < 0) {
1825                         if (errno != EPERM)
1826                                 return ret;
1827                 } else {
1828                         final_b = res_b;
1829                 }
1830         } else {
1831                 final_b = b;
1832         }
1833
1834         return is_same_blk_file(final_a, final_b);
1835 }
1836
1837 /* Checks if a file exists and is a block or regular file*/
1838 static int is_existing_blk_or_reg_file(const char* filename)
1839 {
1840         struct stat st_buf;
1841
1842         if(stat(filename, &st_buf) < 0) {
1843                 if(errno == ENOENT)
1844                         return 0;
1845                 else
1846                         return -errno;
1847         }
1848
1849         return (S_ISBLK(st_buf.st_mode) || S_ISREG(st_buf.st_mode));
1850 }
1851
1852 /* Checks if a file is used (directly or indirectly via a loop device)
1853  * by a device in fs_devices
1854  */
1855 static int blk_file_in_dev_list(struct btrfs_fs_devices* fs_devices,
1856                 const char* file)
1857 {
1858         int ret;
1859         struct list_head *head;
1860         struct list_head *cur;
1861         struct btrfs_device *device;
1862
1863         head = &fs_devices->devices;
1864         list_for_each(cur, head) {
1865                 device = list_entry(cur, struct btrfs_device, dev_list);
1866
1867                 if((ret = is_same_loop_file(device->name, file)))
1868                         return ret;
1869         }
1870
1871         return 0;
1872 }
1873
1874 /*
1875  * Resolve a pathname to a device mapper node to /dev/mapper/<name>
1876  * Returns NULL on invalid input or malloc failure; Other failures
1877  * will be handled by the caller using the input pathame.
1878  */
1879 char *canonicalize_dm_name(const char *ptname)
1880 {
1881         FILE    *f;
1882         size_t  sz;
1883         char    path[PATH_MAX], name[PATH_MAX], *res = NULL;
1884
1885         if (!ptname || !*ptname)
1886                 return NULL;
1887
1888         snprintf(path, sizeof(path), "/sys/block/%s/dm/name", ptname);
1889         if (!(f = fopen(path, "r")))
1890                 return NULL;
1891
1892         /* read <name>\n from sysfs */
1893         if (fgets(name, sizeof(name), f) && (sz = strlen(name)) > 1) {
1894                 name[sz - 1] = '\0';
1895                 snprintf(path, sizeof(path), "/dev/mapper/%s", name);
1896
1897                 if (access(path, F_OK) == 0)
1898                         res = strdup(path);
1899         }
1900         fclose(f);
1901         return res;
1902 }
1903
1904 /*
1905  * Resolve a pathname to a canonical device node, e.g. /dev/sda1 or
1906  * to a device mapper pathname.
1907  * Returns NULL on invalid input or malloc failure; Other failures
1908  * will be handled by the caller using the input pathame.
1909  */
1910 char *canonicalize_path(const char *path)
1911 {
1912         char *canonical, *p;
1913
1914         if (!path || !*path)
1915                 return NULL;
1916
1917         canonical = realpath(path, NULL);
1918         if (!canonical)
1919                 return strdup(path);
1920         p = strrchr(canonical, '/');
1921         if (p && strncmp(p, "/dm-", 4) == 0 && isdigit(*(p + 4))) {
1922                 char *dm = canonicalize_dm_name(p + 1);
1923
1924                 if (dm) {
1925                         free(canonical);
1926                         return dm;
1927                 }
1928         }
1929         return canonical;
1930 }
1931
1932 /*
1933  * returns 1 if the device was mounted, < 0 on error or 0 if everything
1934  * is safe to continue.
1935  */
1936 int check_mounted(const char* file)
1937 {
1938         int fd;
1939         int ret;
1940
1941         fd = open(file, O_RDONLY);
1942         if (fd < 0) {
1943                 error("mount check: cannot open %s: %s", file,
1944                                 strerror(errno));
1945                 return -errno;
1946         }
1947
1948         ret =  check_mounted_where(fd, file, NULL, 0, NULL);
1949         close(fd);
1950
1951         return ret;
1952 }
1953
1954 int check_mounted_where(int fd, const char *file, char *where, int size,
1955                         struct btrfs_fs_devices **fs_dev_ret)
1956 {
1957         int ret;
1958         u64 total_devs = 1;
1959         int is_btrfs;
1960         struct btrfs_fs_devices *fs_devices_mnt = NULL;
1961         FILE *f;
1962         struct mntent *mnt;
1963
1964         /* scan the initial device */
1965         ret = btrfs_scan_one_device(fd, file, &fs_devices_mnt,
1966                     &total_devs, BTRFS_SUPER_INFO_OFFSET, SBREAD_DEFAULT);
1967         is_btrfs = (ret >= 0);
1968
1969         /* scan other devices */
1970         if (is_btrfs && total_devs > 1) {
1971                 ret = btrfs_scan_devices();
1972                 if (ret)
1973                         return ret;
1974         }
1975
1976         /* iterate over the list of currently mounted filesystems */
1977         if ((f = setmntent ("/proc/self/mounts", "r")) == NULL)
1978                 return -errno;
1979
1980         while ((mnt = getmntent (f)) != NULL) {
1981                 if(is_btrfs) {
1982                         if(strcmp(mnt->mnt_type, "btrfs") != 0)
1983                                 continue;
1984
1985                         ret = blk_file_in_dev_list(fs_devices_mnt, mnt->mnt_fsname);
1986                 } else {
1987                         /* ignore entries in the mount table that are not
1988                            associated with a file*/
1989                         if((ret = is_existing_blk_or_reg_file(mnt->mnt_fsname)) < 0)
1990                                 goto out_mntloop_err;
1991                         else if(!ret)
1992                                 continue;
1993
1994                         ret = is_same_loop_file(file, mnt->mnt_fsname);
1995                 }
1996
1997                 if(ret < 0)
1998                         goto out_mntloop_err;
1999                 else if(ret)
2000                         break;
2001         }
2002
2003         /* Did we find an entry in mnt table? */
2004         if (mnt && size && where) {
2005                 strncpy(where, mnt->mnt_dir, size);
2006                 where[size-1] = 0;
2007         }
2008         if (fs_dev_ret)
2009                 *fs_dev_ret = fs_devices_mnt;
2010
2011         ret = (mnt != NULL);
2012
2013 out_mntloop_err:
2014         endmntent (f);
2015
2016         return ret;
2017 }
2018
2019 struct pending_dir {
2020         struct list_head list;
2021         char name[PATH_MAX];
2022 };
2023
2024 int btrfs_register_one_device(const char *fname)
2025 {
2026         struct btrfs_ioctl_vol_args args;
2027         int fd;
2028         int ret;
2029
2030         fd = open("/dev/btrfs-control", O_RDWR);
2031         if (fd < 0) {
2032                 warning(
2033         "failed to open /dev/btrfs-control, skipping device registration: %s",
2034                         strerror(errno));
2035                 return -errno;
2036         }
2037         memset(&args, 0, sizeof(args));
2038         strncpy_null(args.name, fname);
2039         ret = ioctl(fd, BTRFS_IOC_SCAN_DEV, &args);
2040         if (ret < 0) {
2041                 error("device scan failed on '%s': %s", fname,
2042                                 strerror(errno));
2043                 ret = -errno;
2044         }
2045         close(fd);
2046         return ret;
2047 }
2048
2049 /*
2050  * Register all devices in the fs_uuid list created in the user
2051  * space. Ensure btrfs_scan_devices() is called before this func.
2052  */
2053 int btrfs_register_all_devices(void)
2054 {
2055         int err = 0;
2056         int ret = 0;
2057         struct btrfs_fs_devices *fs_devices;
2058         struct btrfs_device *device;
2059         struct list_head *all_uuids;
2060
2061         all_uuids = btrfs_scanned_uuids();
2062
2063         list_for_each_entry(fs_devices, all_uuids, list) {
2064                 list_for_each_entry(device, &fs_devices->devices, dev_list) {
2065                         if (*device->name)
2066                                 err = btrfs_register_one_device(device->name);
2067
2068                         if (err)
2069                                 ret++;
2070                 }
2071         }
2072
2073         return ret;
2074 }
2075
2076 int btrfs_device_already_in_root(struct btrfs_root *root, int fd,
2077                                  int super_offset)
2078 {
2079         struct btrfs_super_block *disk_super;
2080         char *buf;
2081         int ret = 0;
2082
2083         buf = malloc(BTRFS_SUPER_INFO_SIZE);
2084         if (!buf) {
2085                 ret = -ENOMEM;
2086                 goto out;
2087         }
2088         ret = pread(fd, buf, BTRFS_SUPER_INFO_SIZE, super_offset);
2089         if (ret != BTRFS_SUPER_INFO_SIZE)
2090                 goto brelse;
2091
2092         ret = 0;
2093         disk_super = (struct btrfs_super_block *)buf;
2094         /*
2095          * Accept devices from the same filesystem, allow partially created
2096          * structures.
2097          */
2098         if (btrfs_super_magic(disk_super) != BTRFS_MAGIC &&
2099                         btrfs_super_magic(disk_super) != BTRFS_MAGIC_PARTIAL)
2100                 goto brelse;
2101
2102         if (!memcmp(disk_super->fsid, root->fs_info->super_copy->fsid,
2103                     BTRFS_FSID_SIZE))
2104                 ret = 1;
2105 brelse:
2106         free(buf);
2107 out:
2108         return ret;
2109 }
2110
2111 /*
2112  * Note: this function uses a static per-thread buffer. Do not call this
2113  * function more than 10 times within one argument list!
2114  */
2115 const char *pretty_size_mode(u64 size, unsigned mode)
2116 {
2117         static __thread int ps_index = 0;
2118         static __thread char ps_array[10][32];
2119         char *ret;
2120
2121         ret = ps_array[ps_index];
2122         ps_index++;
2123         ps_index %= 10;
2124         (void)pretty_size_snprintf(size, ret, 32, mode);
2125
2126         return ret;
2127 }
2128
2129 static const char* unit_suffix_binary[] =
2130         { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"};
2131 static const char* unit_suffix_decimal[] =
2132         { "B", "kB", "MB", "GB", "TB", "PB", "EB"};
2133
2134 int pretty_size_snprintf(u64 size, char *str, size_t str_size, unsigned unit_mode)
2135 {
2136         int num_divs;
2137         float fraction;
2138         u64 base = 0;
2139         int mult = 0;
2140         const char** suffix = NULL;
2141         u64 last_size;
2142         int negative;
2143
2144         if (str_size == 0)
2145                 return 0;
2146
2147         negative = !!(unit_mode & UNITS_NEGATIVE);
2148         unit_mode &= ~UNITS_NEGATIVE;
2149
2150         if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_RAW) {
2151                 if (negative)
2152                         snprintf(str, str_size, "%lld", size);
2153                 else
2154                         snprintf(str, str_size, "%llu", size);
2155                 return 0;
2156         }
2157
2158         if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_BINARY) {
2159                 base = 1024;
2160                 mult = 1024;
2161                 suffix = unit_suffix_binary;
2162         } else if ((unit_mode & ~UNITS_MODE_MASK) == UNITS_DECIMAL) {
2163                 base = 1000;
2164                 mult = 1000;
2165                 suffix = unit_suffix_decimal;
2166         }
2167
2168         /* Unknown mode */
2169         if (!base) {
2170                 fprintf(stderr, "INTERNAL ERROR: unknown unit base, mode %d\n",
2171                                 unit_mode);
2172                 assert(0);
2173                 return -1;
2174         }
2175
2176         num_divs = 0;
2177         last_size = size;
2178         switch (unit_mode & UNITS_MODE_MASK) {
2179         case UNITS_TBYTES: base *= mult; num_divs++;
2180         case UNITS_GBYTES: base *= mult; num_divs++;
2181         case UNITS_MBYTES: base *= mult; num_divs++;
2182         case UNITS_KBYTES: num_divs++;
2183                            break;
2184         case UNITS_BYTES:
2185                            base = 1;
2186                            num_divs = 0;
2187                            break;
2188         default:
2189                 if (negative) {
2190                         s64 ssize = (s64)size;
2191                         s64 last_ssize = ssize;
2192
2193                         while ((ssize < 0 ? -ssize : ssize) >= mult) {
2194                                 last_ssize = ssize;
2195                                 ssize /= mult;
2196                                 num_divs++;
2197                         }
2198                         last_size = (u64)last_ssize;
2199                 } else {
2200                         while (size >= mult) {
2201                                 last_size = size;
2202                                 size /= mult;
2203                                 num_divs++;
2204                         }
2205                 }
2206                 /*
2207                  * If the value is smaller than base, we didn't do any
2208                  * division, in that case, base should be 1, not original
2209                  * base, or the unit will be wrong
2210                  */
2211                 if (num_divs == 0)
2212                         base = 1;
2213         }
2214
2215         if (num_divs >= ARRAY_SIZE(unit_suffix_binary)) {
2216                 str[0] = '\0';
2217                 printf("INTERNAL ERROR: unsupported unit suffix, index %d\n",
2218                                 num_divs);
2219                 assert(0);
2220                 return -1;
2221         }
2222
2223         if (negative) {
2224                 fraction = (float)(s64)last_size / base;
2225         } else {
2226                 fraction = (float)last_size / base;
2227         }
2228
2229         return snprintf(str, str_size, "%.2f%s", fraction, suffix[num_divs]);
2230 }
2231
2232 /*
2233  * __strncpy_null - strncpy with null termination
2234  * @dest:       the target array
2235  * @src:        the source string
2236  * @n:          maximum bytes to copy (size of *dest)
2237  *
2238  * Like strncpy, but ensures destination is null-terminated.
2239  *
2240  * Copies the string pointed to by src, including the terminating null
2241  * byte ('\0'), to the buffer pointed to by dest, up to a maximum
2242  * of n bytes.  Then ensure that dest is null-terminated.
2243  */
2244 char *__strncpy_null(char *dest, const char *src, size_t n)
2245 {
2246         strncpy(dest, src, n);
2247         if (n > 0)
2248                 dest[n - 1] = '\0';
2249         return dest;
2250 }
2251
2252 /*
2253  * Checks to make sure that the label matches our requirements.
2254  * Returns:
2255        0    if everything is safe and usable
2256       -1    if the label is too long
2257  */
2258 static int check_label(const char *input)
2259 {
2260        int len = strlen(input);
2261
2262        if (len > BTRFS_LABEL_SIZE - 1) {
2263                 error("label %s is too long (max %d)", input,
2264                                 BTRFS_LABEL_SIZE - 1);
2265                return -1;
2266        }
2267
2268        return 0;
2269 }
2270
2271 static int set_label_unmounted(const char *dev, const char *label)
2272 {
2273         struct btrfs_trans_handle *trans;
2274         struct btrfs_root *root;
2275         int ret;
2276
2277         ret = check_mounted(dev);
2278         if (ret < 0) {
2279                error("checking mount status of %s failed: %d", dev, ret);
2280                return -1;
2281         }
2282         if (ret > 0) {
2283                 error("device %s is mounted, use mount point", dev);
2284                 return -1;
2285         }
2286
2287         /* Open the super_block at the default location
2288          * and as read-write.
2289          */
2290         root = open_ctree(dev, 0, OPEN_CTREE_WRITES);
2291         if (!root) /* errors are printed by open_ctree() */
2292                 return -1;
2293
2294         trans = btrfs_start_transaction(root, 1);
2295         __strncpy_null(root->fs_info->super_copy->label, label, BTRFS_LABEL_SIZE - 1);
2296
2297         btrfs_commit_transaction(trans, root);
2298
2299         /* Now we close it since we are done. */
2300         close_ctree(root);
2301         return 0;
2302 }
2303
2304 static int set_label_mounted(const char *mount_path, const char *labelp)
2305 {
2306         int fd;
2307         char label[BTRFS_LABEL_SIZE];
2308
2309         fd = open(mount_path, O_RDONLY | O_NOATIME);
2310         if (fd < 0) {
2311                 error("unable to access %s: %s", mount_path, strerror(errno));
2312                 return -1;
2313         }
2314
2315         memset(label, 0, sizeof(label));
2316         __strncpy_null(label, labelp, BTRFS_LABEL_SIZE - 1);
2317         if (ioctl(fd, BTRFS_IOC_SET_FSLABEL, label) < 0) {
2318                 error("unable to set label of %s: %s", mount_path,
2319                                 strerror(errno));
2320                 close(fd);
2321                 return -1;
2322         }
2323
2324         close(fd);
2325         return 0;
2326 }
2327
2328 int get_label_unmounted(const char *dev, char *label)
2329 {
2330         struct btrfs_root *root;
2331         int ret;
2332
2333         ret = check_mounted(dev);
2334         if (ret < 0) {
2335                error("checking mount status of %s failed: %d", dev, ret);
2336                return -1;
2337         }
2338
2339         /* Open the super_block at the default location
2340          * and as read-only.
2341          */
2342         root = open_ctree(dev, 0, 0);
2343         if(!root)
2344                 return -1;
2345
2346         __strncpy_null(label, root->fs_info->super_copy->label,
2347                         BTRFS_LABEL_SIZE - 1);
2348
2349         /* Now we close it since we are done. */
2350         close_ctree(root);
2351         return 0;
2352 }
2353
2354 /*
2355  * If a partition is mounted, try to get the filesystem label via its
2356  * mounted path rather than device.  Return the corresponding error
2357  * the user specified the device path.
2358  */
2359 int get_label_mounted(const char *mount_path, char *labelp)
2360 {
2361         char label[BTRFS_LABEL_SIZE];
2362         int fd;
2363         int ret;
2364
2365         fd = open(mount_path, O_RDONLY | O_NOATIME);
2366         if (fd < 0) {
2367                 error("unable to access %s: %s", mount_path, strerror(errno));
2368                 return -1;
2369         }
2370
2371         memset(label, '\0', sizeof(label));
2372         ret = ioctl(fd, BTRFS_IOC_GET_FSLABEL, label);
2373         if (ret < 0) {
2374                 if (errno != ENOTTY)
2375                         error("unable to get label of %s: %s", mount_path,
2376                                         strerror(errno));
2377                 ret = -errno;
2378                 close(fd);
2379                 return ret;
2380         }
2381
2382         __strncpy_null(labelp, label, BTRFS_LABEL_SIZE - 1);
2383         close(fd);
2384         return 0;
2385 }
2386
2387 int get_label(const char *btrfs_dev, char *label)
2388 {
2389         int ret;
2390
2391         ret = is_existing_blk_or_reg_file(btrfs_dev);
2392         if (!ret)
2393                 ret = get_label_mounted(btrfs_dev, label);
2394         else if (ret > 0)
2395                 ret = get_label_unmounted(btrfs_dev, label);
2396
2397         return ret;
2398 }
2399
2400 int set_label(const char *btrfs_dev, const char *label)
2401 {
2402         int ret;
2403
2404         if (check_label(label))
2405                 return -1;
2406
2407         ret = is_existing_blk_or_reg_file(btrfs_dev);
2408         if (!ret)
2409                 ret = set_label_mounted(btrfs_dev, label);
2410         else if (ret > 0)
2411                 ret = set_label_unmounted(btrfs_dev, label);
2412
2413         return ret;
2414 }
2415
2416 /*
2417  * A not-so-good version fls64. No fascinating optimization since
2418  * no one except parse_size use it
2419  */
2420 static int fls64(u64 x)
2421 {
2422         int i;
2423
2424         for (i = 0; i <64; i++)
2425                 if (x << i & (1ULL << 63))
2426                         return 64 - i;
2427         return 64 - i;
2428 }
2429
2430 u64 parse_size(char *s)
2431 {
2432         char c;
2433         char *endptr;
2434         u64 mult = 1;
2435         u64 ret;
2436
2437         if (!s) {
2438                 error("size value is empty");
2439                 exit(1);
2440         }
2441         if (s[0] == '-') {
2442                 error("size value '%s' is less equal than 0", s);
2443                 exit(1);
2444         }
2445         ret = strtoull(s, &endptr, 10);
2446         if (endptr == s) {
2447                 error("size value '%s' is invalid", s);
2448                 exit(1);
2449         }
2450         if (endptr[0] && endptr[1]) {
2451                 error("illegal suffix contains character '%c' in wrong position",
2452                         endptr[1]);
2453                 exit(1);
2454         }
2455         /*
2456          * strtoll returns LLONG_MAX when overflow, if this happens,
2457          * need to call strtoull to get the real size
2458          */
2459         if (errno == ERANGE && ret == ULLONG_MAX) {
2460                 error("size value '%s' is too large for u64", s);
2461                 exit(1);
2462         }
2463         if (endptr[0]) {
2464                 c = tolower(endptr[0]);
2465                 switch (c) {
2466                 case 'e':
2467                         mult *= 1024;
2468                         /* fallthrough */
2469                 case 'p':
2470                         mult *= 1024;
2471                         /* fallthrough */
2472                 case 't':
2473                         mult *= 1024;
2474                         /* fallthrough */
2475                 case 'g':
2476                         mult *= 1024;
2477                         /* fallthrough */
2478                 case 'm':
2479                         mult *= 1024;
2480                         /* fallthrough */
2481                 case 'k':
2482                         mult *= 1024;
2483                         /* fallthrough */
2484                 case 'b':
2485                         break;
2486                 default:
2487                         error("unknown size descriptor '%c'", c);
2488                         exit(1);
2489                 }
2490         }
2491         /* Check whether ret * mult overflow */
2492         if (fls64(ret) + fls64(mult) - 1 > 64) {
2493                 error("size value '%s' is too large for u64", s);
2494                 exit(1);
2495         }
2496         ret *= mult;
2497         return ret;
2498 }
2499
2500 u64 parse_qgroupid(const char *p)
2501 {
2502         char *s = strchr(p, '/');
2503         const char *ptr_src_end = p + strlen(p);
2504         char *ptr_parse_end = NULL;
2505         u64 level;
2506         u64 id;
2507         int fd;
2508         int ret = 0;
2509
2510         if (p[0] == '/')
2511                 goto path;
2512
2513         /* Numeric format like '0/257' is the primary case */
2514         if (!s) {
2515                 id = strtoull(p, &ptr_parse_end, 10);
2516                 if (ptr_parse_end != ptr_src_end)
2517                         goto path;
2518                 return id;
2519         }
2520         level = strtoull(p, &ptr_parse_end, 10);
2521         if (ptr_parse_end != s)
2522                 goto path;
2523
2524         id = strtoull(s + 1, &ptr_parse_end, 10);
2525         if (ptr_parse_end != ptr_src_end)
2526                 goto  path;
2527
2528         return (level << BTRFS_QGROUP_LEVEL_SHIFT) | id;
2529
2530 path:
2531         /* Path format like subv at 'my_subvol' is the fallback case */
2532         ret = test_issubvolume(p);
2533         if (ret < 0 || !ret)
2534                 goto err;
2535         fd = open(p, O_RDONLY);
2536         if (fd < 0)
2537                 goto err;
2538         ret = lookup_path_rootid(fd, &id);
2539         if (ret)
2540                 error("failed to lookup root id: %s", strerror(-ret));
2541         close(fd);
2542         if (ret < 0)
2543                 goto err;
2544         return id;
2545
2546 err:
2547         error("invalid qgroupid or subvolume path: %s", p);
2548         exit(-1);
2549 }
2550
2551 int open_file_or_dir3(const char *fname, DIR **dirstream, int open_flags)
2552 {
2553         int ret;
2554         struct stat st;
2555         int fd;
2556
2557         ret = stat(fname, &st);
2558         if (ret < 0) {
2559                 return -1;
2560         }
2561         if (S_ISDIR(st.st_mode)) {
2562                 *dirstream = opendir(fname);
2563                 if (!*dirstream)
2564                         return -1;
2565                 fd = dirfd(*dirstream);
2566         } else if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
2567                 fd = open(fname, open_flags);
2568         } else {
2569                 /*
2570                  * we set this on purpose, in case the caller output
2571                  * strerror(errno) as success
2572                  */
2573                 errno = EINVAL;
2574                 return -1;
2575         }
2576         if (fd < 0) {
2577                 fd = -1;
2578                 if (*dirstream) {
2579                         closedir(*dirstream);
2580                         *dirstream = NULL;
2581                 }
2582         }
2583         return fd;
2584 }
2585
2586 int open_file_or_dir(const char *fname, DIR **dirstream)
2587 {
2588         return open_file_or_dir3(fname, dirstream, O_RDWR);
2589 }
2590
2591 void close_file_or_dir(int fd, DIR *dirstream)
2592 {
2593         if (dirstream)
2594                 closedir(dirstream);
2595         else if (fd >= 0)
2596                 close(fd);
2597 }
2598
2599 int get_device_info(int fd, u64 devid,
2600                 struct btrfs_ioctl_dev_info_args *di_args)
2601 {
2602         int ret;
2603
2604         di_args->devid = devid;
2605         memset(&di_args->uuid, '\0', sizeof(di_args->uuid));
2606
2607         ret = ioctl(fd, BTRFS_IOC_DEV_INFO, di_args);
2608         return ret < 0 ? -errno : 0;
2609 }
2610
2611 static u64 find_max_device_id(struct btrfs_ioctl_search_args *search_args,
2612                               int nr_items)
2613 {
2614         struct btrfs_dev_item *dev_item;
2615         char *buf = search_args->buf;
2616
2617         buf += (nr_items - 1) * (sizeof(struct btrfs_ioctl_search_header)
2618                                        + sizeof(struct btrfs_dev_item));
2619         buf += sizeof(struct btrfs_ioctl_search_header);
2620
2621         dev_item = (struct btrfs_dev_item *)buf;
2622
2623         return btrfs_stack_device_id(dev_item);
2624 }
2625
2626 static int search_chunk_tree_for_fs_info(int fd,
2627                                 struct btrfs_ioctl_fs_info_args *fi_args)
2628 {
2629         int ret;
2630         int max_items;
2631         u64 start_devid = 1;
2632         struct btrfs_ioctl_search_args search_args;
2633         struct btrfs_ioctl_search_key *search_key = &search_args.key;
2634
2635         fi_args->num_devices = 0;
2636
2637         max_items = BTRFS_SEARCH_ARGS_BUFSIZE
2638                / (sizeof(struct btrfs_ioctl_search_header)
2639                                + sizeof(struct btrfs_dev_item));
2640
2641         search_key->tree_id = BTRFS_CHUNK_TREE_OBJECTID;
2642         search_key->min_objectid = BTRFS_DEV_ITEMS_OBJECTID;
2643         search_key->max_objectid = BTRFS_DEV_ITEMS_OBJECTID;
2644         search_key->min_type = BTRFS_DEV_ITEM_KEY;
2645         search_key->max_type = BTRFS_DEV_ITEM_KEY;
2646         search_key->min_transid = 0;
2647         search_key->max_transid = (u64)-1;
2648         search_key->nr_items = max_items;
2649         search_key->max_offset = (u64)-1;
2650
2651 again:
2652         search_key->min_offset = start_devid;
2653
2654         ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH, &search_args);
2655         if (ret < 0)
2656                 return -errno;
2657
2658         fi_args->num_devices += (u64)search_key->nr_items;
2659
2660         if (search_key->nr_items == max_items) {
2661                 start_devid = find_max_device_id(&search_args,
2662                                         search_key->nr_items) + 1;
2663                 goto again;
2664         }
2665
2666         /* get the lastest max_id to stay consistent with the num_devices */
2667         if (search_key->nr_items == 0)
2668                 /*
2669                  * last tree_search returns an empty buf, use the devid of
2670                  * the last dev_item of the previous tree_search
2671                  */
2672                 fi_args->max_id = start_devid - 1;
2673         else
2674                 fi_args->max_id = find_max_device_id(&search_args,
2675                                                 search_key->nr_items);
2676
2677         return 0;
2678 }
2679
2680 /*
2681  * For a given path, fill in the ioctl fs_ and info_ args.
2682  * If the path is a btrfs mountpoint, fill info for all devices.
2683  * If the path is a btrfs device, fill in only that device.
2684  *
2685  * The path provided must be either on a mounted btrfs fs,
2686  * or be a mounted btrfs device.
2687  *
2688  * Returns 0 on success, or a negative errno.
2689  */
2690 int get_fs_info(const char *path, struct btrfs_ioctl_fs_info_args *fi_args,
2691                 struct btrfs_ioctl_dev_info_args **di_ret)
2692 {
2693         int fd = -1;
2694         int ret = 0;
2695         int ndevs = 0;
2696         u64 last_devid = 0;
2697         int replacing = 0;
2698         struct btrfs_fs_devices *fs_devices_mnt = NULL;
2699         struct btrfs_ioctl_dev_info_args *di_args;
2700         struct btrfs_ioctl_dev_info_args tmp;
2701         char mp[PATH_MAX];
2702         DIR *dirstream = NULL;
2703
2704         memset(fi_args, 0, sizeof(*fi_args));
2705
2706         if (is_block_device(path) == 1) {
2707                 struct btrfs_super_block *disk_super;
2708                 char buf[BTRFS_SUPER_INFO_SIZE];
2709
2710                 /* Ensure it's mounted, then set path to the mountpoint */
2711                 fd = open(path, O_RDONLY);
2712                 if (fd < 0) {
2713                         ret = -errno;
2714                         error("cannot open %s: %s", path, strerror(errno));
2715                         goto out;
2716                 }
2717                 ret = check_mounted_where(fd, path, mp, sizeof(mp),
2718                                           &fs_devices_mnt);
2719                 if (!ret) {
2720                         ret = -EINVAL;
2721                         goto out;
2722                 }
2723                 if (ret < 0)
2724                         goto out;
2725                 path = mp;
2726                 /* Only fill in this one device */
2727                 fi_args->num_devices = 1;
2728
2729                 disk_super = (struct btrfs_super_block *)buf;
2730                 ret = btrfs_read_dev_super(fd, disk_super,
2731                                            BTRFS_SUPER_INFO_OFFSET, 0);
2732                 if (ret < 0) {
2733                         ret = -EIO;
2734                         goto out;
2735                 }
2736                 last_devid = btrfs_stack_device_id(&disk_super->dev_item);
2737                 fi_args->max_id = last_devid;
2738
2739                 memcpy(fi_args->fsid, fs_devices_mnt->fsid, BTRFS_FSID_SIZE);
2740                 close(fd);
2741         }
2742
2743         /* at this point path must not be for a block device */
2744         fd = open_file_or_dir(path, &dirstream);
2745         if (fd < 0) {
2746                 ret = -errno;
2747                 goto out;
2748         }
2749
2750         /* fill in fi_args if not just a single device */
2751         if (fi_args->num_devices != 1) {
2752                 ret = ioctl(fd, BTRFS_IOC_FS_INFO, fi_args);
2753                 if (ret < 0) {
2754                         ret = -errno;
2755                         goto out;
2756                 }
2757
2758                 /*
2759                  * The fs_args->num_devices does not include seed devices
2760                  */
2761                 ret = search_chunk_tree_for_fs_info(fd, fi_args);
2762                 if (ret)
2763                         goto out;
2764
2765                 /*
2766                  * search_chunk_tree_for_fs_info() will lacks the devid 0
2767                  * so manual probe for it here.
2768                  */
2769                 ret = get_device_info(fd, 0, &tmp);
2770                 if (!ret) {
2771                         fi_args->num_devices++;
2772                         ndevs++;
2773                         replacing = 1;
2774                         if (last_devid == 0)
2775                                 last_devid++;
2776                 }
2777         }
2778
2779         if (!fi_args->num_devices)
2780                 goto out;
2781
2782         di_args = *di_ret = malloc((fi_args->num_devices) * sizeof(*di_args));
2783         if (!di_args) {
2784                 ret = -errno;
2785                 goto out;
2786         }
2787
2788         if (replacing)
2789                 memcpy(di_args, &tmp, sizeof(tmp));
2790         for (; last_devid <= fi_args->max_id; last_devid++) {
2791                 ret = get_device_info(fd, last_devid, &di_args[ndevs]);
2792                 if (ret == -ENODEV)
2793                         continue;
2794                 if (ret)
2795                         goto out;
2796                 ndevs++;
2797         }
2798
2799         /*
2800         * only when the only dev we wanted to find is not there then
2801         * let any error be returned
2802         */
2803         if (fi_args->num_devices != 1) {
2804                 BUG_ON(ndevs == 0);
2805                 ret = 0;
2806         }
2807
2808 out:
2809         close_file_or_dir(fd, dirstream);
2810         return ret;
2811 }
2812
2813 #define isoctal(c)      (((c) & ~7) == '0')
2814
2815 static inline void translate(char *f, char *t)
2816 {
2817         while (*f != '\0') {
2818                 if (*f == '\\' &&
2819                     isoctal(f[1]) && isoctal(f[2]) && isoctal(f[3])) {
2820                         *t++ = 64*(f[1] & 7) + 8*(f[2] & 7) + (f[3] & 7);
2821                         f += 4;
2822                 } else
2823                         *t++ = *f++;
2824         }
2825         *t = '\0';
2826         return;
2827 }
2828
2829 /*
2830  * Checks if the swap device.
2831  * Returns 1 if swap device, < 0 on error or 0 if not swap device.
2832  */
2833 static int is_swap_device(const char *file)
2834 {
2835         FILE    *f;
2836         struct stat     st_buf;
2837         dev_t   dev;
2838         ino_t   ino = 0;
2839         char    tmp[PATH_MAX];
2840         char    buf[PATH_MAX];
2841         char    *cp;
2842         int     ret = 0;
2843
2844         if (stat(file, &st_buf) < 0)
2845                 return -errno;
2846         if (S_ISBLK(st_buf.st_mode))
2847                 dev = st_buf.st_rdev;
2848         else if (S_ISREG(st_buf.st_mode)) {
2849                 dev = st_buf.st_dev;
2850                 ino = st_buf.st_ino;
2851         } else
2852                 return 0;
2853
2854         if ((f = fopen("/proc/swaps", "r")) == NULL)
2855                 return 0;
2856
2857         /* skip the first line */
2858         if (fgets(tmp, sizeof(tmp), f) == NULL)
2859                 goto out;
2860
2861         while (fgets(tmp, sizeof(tmp), f) != NULL) {
2862                 if ((cp = strchr(tmp, ' ')) != NULL)
2863                         *cp = '\0';
2864                 if ((cp = strchr(tmp, '\t')) != NULL)
2865                         *cp = '\0';
2866                 translate(tmp, buf);
2867                 if (stat(buf, &st_buf) != 0)
2868                         continue;
2869                 if (S_ISBLK(st_buf.st_mode)) {
2870                         if (dev == st_buf.st_rdev) {
2871                                 ret = 1;
2872                                 break;
2873                         }
2874                 } else if (S_ISREG(st_buf.st_mode)) {
2875                         if (dev == st_buf.st_dev && ino == st_buf.st_ino) {
2876                                 ret = 1;
2877                                 break;
2878                         }
2879                 }
2880         }
2881
2882 out:
2883         fclose(f);
2884
2885         return ret;
2886 }
2887
2888 /*
2889  * Check for existing filesystem or partition table on device.
2890  * Returns:
2891  *       1 for existing fs or partition
2892  *       0 for nothing found
2893  *      -1 for internal error
2894  */
2895 static int check_overwrite(const char *device)
2896 {
2897         const char      *type;
2898         blkid_probe     pr = NULL;
2899         int             ret;
2900         blkid_loff_t    size;
2901
2902         if (!device || !*device)
2903                 return 0;
2904
2905         ret = -1; /* will reset on success of all setup calls */
2906
2907         pr = blkid_new_probe_from_filename(device);
2908         if (!pr)
2909                 goto out;
2910
2911         size = blkid_probe_get_size(pr);
2912         if (size < 0)
2913                 goto out;
2914
2915         /* nothing to overwrite on a 0-length device */
2916         if (size == 0) {
2917                 ret = 0;
2918                 goto out;
2919         }
2920
2921         ret = blkid_probe_enable_partitions(pr, 1);
2922         if (ret < 0)
2923                 goto out;
2924
2925         ret = blkid_do_fullprobe(pr);
2926         if (ret < 0)
2927                 goto out;
2928
2929         /*
2930          * Blkid returns 1 for nothing found and 0 when it finds a signature,
2931          * but we want the exact opposite, so reverse the return value here.
2932          *
2933          * In addition print some useful diagnostics about what actually is
2934          * on the device.
2935          */
2936         if (ret) {
2937                 ret = 0;
2938                 goto out;
2939         }
2940
2941         if (!blkid_probe_lookup_value(pr, "TYPE", &type, NULL)) {
2942                 fprintf(stderr,
2943                         "%s appears to contain an existing "
2944                         "filesystem (%s).\n", device, type);
2945         } else if (!blkid_probe_lookup_value(pr, "PTTYPE", &type, NULL)) {
2946                 fprintf(stderr,
2947                         "%s appears to contain a partition "
2948                         "table (%s).\n", device, type);
2949         } else {
2950                 fprintf(stderr,
2951                         "%s appears to contain something weird "
2952                         "according to blkid\n", device);
2953         }
2954         ret = 1;
2955
2956 out:
2957         if (pr)
2958                 blkid_free_probe(pr);
2959         if (ret == -1)
2960                 fprintf(stderr,
2961                         "probe of %s failed, cannot detect "
2962                           "existing filesystem.\n", device);
2963         return ret;
2964 }
2965
2966 static int group_profile_devs_min(u64 flag)
2967 {
2968         switch (flag & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
2969         case 0: /* single */
2970         case BTRFS_BLOCK_GROUP_DUP:
2971                 return 1;
2972         case BTRFS_BLOCK_GROUP_RAID0:
2973         case BTRFS_BLOCK_GROUP_RAID1:
2974         case BTRFS_BLOCK_GROUP_RAID5:
2975                 return 2;
2976         case BTRFS_BLOCK_GROUP_RAID6:
2977                 return 3;
2978         case BTRFS_BLOCK_GROUP_RAID10:
2979                 return 4;
2980         default:
2981                 return -1;
2982         }
2983 }
2984
2985 int test_num_disk_vs_raid(u64 metadata_profile, u64 data_profile,
2986         u64 dev_cnt, int mixed, int ssd)
2987 {
2988         u64 allowed = 0;
2989         u64 profile = metadata_profile | data_profile;
2990
2991         switch (dev_cnt) {
2992         default:
2993         case 4:
2994                 allowed |= BTRFS_BLOCK_GROUP_RAID10;
2995         case 3:
2996                 allowed |= BTRFS_BLOCK_GROUP_RAID6;
2997         case 2:
2998                 allowed |= BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
2999                         BTRFS_BLOCK_GROUP_RAID5;
3000         case 1:
3001                 allowed |= BTRFS_BLOCK_GROUP_DUP;
3002         }
3003
3004         if (dev_cnt > 1 && profile & BTRFS_BLOCK_GROUP_DUP) {
3005                 warning("DUP is not recommended on filesystem with multiple devices");
3006         }
3007         if (metadata_profile & ~allowed) {
3008                 fprintf(stderr,
3009                         "ERROR: unable to create FS with metadata profile %s "
3010                         "(have %llu devices but %d devices are required)\n",
3011                         btrfs_group_profile_str(metadata_profile), dev_cnt,
3012                         group_profile_devs_min(metadata_profile));
3013                 return 1;
3014         }
3015         if (data_profile & ~allowed) {
3016                 fprintf(stderr,
3017                         "ERROR: unable to create FS with data profile %s "
3018                         "(have %llu devices but %d devices are required)\n",
3019                         btrfs_group_profile_str(data_profile), dev_cnt,
3020                         group_profile_devs_min(data_profile));
3021                 return 1;
3022         }
3023
3024         if (dev_cnt == 3 && profile & BTRFS_BLOCK_GROUP_RAID6) {
3025                 warning("RAID6 is not recommended on filesystem with 3 devices only");
3026         }
3027         if (dev_cnt == 2 && profile & BTRFS_BLOCK_GROUP_RAID5) {
3028                 warning("RAID5 is not recommended on filesystem with 2 devices only");
3029         }
3030         warning_on(!mixed && (data_profile & BTRFS_BLOCK_GROUP_DUP) && ssd,
3031                    "DUP may not actually lead to 2 copies on the device, see manual page");
3032
3033         return 0;
3034 }
3035
3036 int group_profile_max_safe_loss(u64 flags)
3037 {
3038         switch (flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
3039         case 0: /* single */
3040         case BTRFS_BLOCK_GROUP_DUP:
3041         case BTRFS_BLOCK_GROUP_RAID0:
3042                 return 0;
3043         case BTRFS_BLOCK_GROUP_RAID1:
3044         case BTRFS_BLOCK_GROUP_RAID5:
3045         case BTRFS_BLOCK_GROUP_RAID10:
3046                 return 1;
3047         case BTRFS_BLOCK_GROUP_RAID6:
3048                 return 2;
3049         default:
3050                 return -1;
3051         }
3052 }
3053
3054 /*
3055  * Check if a device is suitable for btrfs
3056  * returns:
3057  *  1: something is wrong, an error is printed
3058  *  0: all is fine
3059  */
3060 int test_dev_for_mkfs(const char *file, int force_overwrite)
3061 {
3062         int ret, fd;
3063         struct stat st;
3064
3065         ret = is_swap_device(file);
3066         if (ret < 0) {
3067                 error("checking status of %s: %s", file, strerror(-ret));
3068                 return 1;
3069         }
3070         if (ret == 1) {
3071                 error("%s is a swap device", file);
3072                 return 1;
3073         }
3074         if (!force_overwrite) {
3075                 if (check_overwrite(file)) {
3076                         error("use the -f option to force overwrite of %s",
3077                                         file);
3078                         return 1;
3079                 }
3080         }
3081         ret = check_mounted(file);
3082         if (ret < 0) {
3083                 error("cannot check mount status of %s: %s", file,
3084                                 strerror(-ret));
3085                 return 1;
3086         }
3087         if (ret == 1) {
3088                 error("%s is mounted", file);
3089                 return 1;
3090         }
3091         /* check if the device is busy */
3092         fd = open(file, O_RDWR|O_EXCL);
3093         if (fd < 0) {
3094                 error("unable to open %s: %s", file, strerror(errno));
3095                 return 1;
3096         }
3097         if (fstat(fd, &st)) {
3098                 error("unable to stat %s: %s", file, strerror(errno));
3099                 close(fd);
3100                 return 1;
3101         }
3102         if (!S_ISBLK(st.st_mode)) {
3103                 error("%s is not a block device", file);
3104                 close(fd);
3105                 return 1;
3106         }
3107         close(fd);
3108         return 0;
3109 }
3110
3111 int btrfs_scan_devices(void)
3112 {
3113         int fd = -1;
3114         int ret;
3115         u64 num_devices;
3116         struct btrfs_fs_devices *tmp_devices;
3117         blkid_dev_iterate iter = NULL;
3118         blkid_dev dev = NULL;
3119         blkid_cache cache = NULL;
3120         char path[PATH_MAX];
3121
3122         if (btrfs_scan_done)
3123                 return 0;
3124
3125         if (blkid_get_cache(&cache, NULL) < 0) {
3126                 error("blkid cache get failed");
3127                 return 1;
3128         }
3129         blkid_probe_all(cache);
3130         iter = blkid_dev_iterate_begin(cache);
3131         blkid_dev_set_search(iter, "TYPE", "btrfs");
3132         while (blkid_dev_next(iter, &dev) == 0) {
3133                 dev = blkid_verify(cache, dev);
3134                 if (!dev)
3135                         continue;
3136                 /* if we are here its definitely a btrfs disk*/
3137                 strncpy_null(path, blkid_dev_devname(dev));
3138
3139                 fd = open(path, O_RDONLY);
3140                 if (fd < 0) {
3141                         error("cannot open %s: %s", path, strerror(errno));
3142                         continue;
3143                 }
3144                 ret = btrfs_scan_one_device(fd, path, &tmp_devices,
3145                                 &num_devices, BTRFS_SUPER_INFO_OFFSET,
3146                                 SBREAD_DEFAULT);
3147                 if (ret) {
3148                         error("cannot scan %s: %s", path, strerror(-ret));
3149                         close (fd);
3150                         continue;
3151                 }
3152
3153                 close(fd);
3154         }
3155         blkid_dev_iterate_end(iter);
3156         blkid_put_cache(cache);
3157
3158         btrfs_scan_done = 1;
3159
3160         return 0;
3161 }
3162
3163 int is_vol_small(const char *file)
3164 {
3165         int fd = -1;
3166         int e;
3167         struct stat st;
3168         u64 size;
3169
3170         fd = open(file, O_RDONLY);
3171         if (fd < 0)
3172                 return -errno;
3173         if (fstat(fd, &st) < 0) {
3174                 e = -errno;
3175                 close(fd);
3176                 return e;
3177         }
3178         size = btrfs_device_size(fd, &st);
3179         if (size == 0) {
3180                 close(fd);
3181                 return -1;
3182         }
3183         if (size < BTRFS_MKFS_SMALL_VOLUME_SIZE) {
3184                 close(fd);
3185                 return 1;
3186         } else {
3187                 close(fd);
3188                 return 0;
3189         }
3190 }
3191
3192 /*
3193  * This reads a line from the stdin and only returns non-zero if the
3194  * first whitespace delimited token is a case insensitive match with yes
3195  * or y.
3196  */
3197 int ask_user(const char *question)
3198 {
3199         char buf[30] = {0,};
3200         char *saveptr = NULL;
3201         char *answer;
3202
3203         printf("%s [y/N]: ", question);
3204
3205         return fgets(buf, sizeof(buf) - 1, stdin) &&
3206                (answer = strtok_r(buf, " \t\n\r", &saveptr)) &&
3207                (!strcasecmp(answer, "yes") || !strcasecmp(answer, "y"));
3208 }
3209
3210 /*
3211  * return 0 if a btrfs mount point is found
3212  * return 1 if a mount point is found but not btrfs
3213  * return <0 if something goes wrong
3214  */
3215 int find_mount_root(const char *path, char **mount_root)
3216 {
3217         FILE *mnttab;
3218         int fd;
3219         struct mntent *ent;
3220         int len;
3221         int ret;
3222         int not_btrfs = 1;
3223         int longest_matchlen = 0;
3224         char *longest_match = NULL;
3225
3226         fd = open(path, O_RDONLY | O_NOATIME);
3227         if (fd < 0)
3228                 return -errno;
3229         close(fd);
3230
3231         mnttab = setmntent("/proc/self/mounts", "r");
3232         if (!mnttab)
3233                 return -errno;
3234
3235         while ((ent = getmntent(mnttab))) {
3236                 len = strlen(ent->mnt_dir);
3237                 if (strncmp(ent->mnt_dir, path, len) == 0) {
3238                         /* match found and use the latest match */
3239                         if (longest_matchlen <= len) {
3240                                 free(longest_match);
3241                                 longest_matchlen = len;
3242                                 longest_match = strdup(ent->mnt_dir);
3243                                 not_btrfs = strcmp(ent->mnt_type, "btrfs");
3244                         }
3245                 }
3246         }
3247         endmntent(mnttab);
3248
3249         if (!longest_match)
3250                 return -ENOENT;
3251         if (not_btrfs) {
3252                 free(longest_match);
3253                 return 1;
3254         }
3255
3256         ret = 0;
3257         *mount_root = realpath(longest_match, NULL);
3258         if (!*mount_root)
3259                 ret = -errno;
3260
3261         free(longest_match);
3262         return ret;
3263 }
3264
3265 int test_minimum_size(const char *file, u32 nodesize)
3266 {
3267         int fd;
3268         struct stat statbuf;
3269
3270         fd = open(file, O_RDONLY);
3271         if (fd < 0)
3272                 return -errno;
3273         if (stat(file, &statbuf) < 0) {
3274                 close(fd);
3275                 return -errno;
3276         }
3277         if (btrfs_device_size(fd, &statbuf) < btrfs_min_dev_size(nodesize)) {
3278                 close(fd);
3279                 return 1;
3280         }
3281         close(fd);
3282         return 0;
3283 }
3284
3285
3286 /*
3287  * Test if path is a directory
3288  * Returns:
3289  *   0 - path exists but it is not a directory
3290  *   1 - path exists and it is a directory
3291  * < 0 - error
3292  */
3293 int test_isdir(const char *path)
3294 {
3295         struct stat st;
3296         int ret;
3297
3298         ret = stat(path, &st);
3299         if (ret < 0)
3300                 return -errno;
3301
3302         return !!S_ISDIR(st.st_mode);
3303 }
3304
3305 void units_set_mode(unsigned *units, unsigned mode)
3306 {
3307         unsigned base = *units & UNITS_MODE_MASK;
3308
3309         *units = base | mode;
3310 }
3311
3312 void units_set_base(unsigned *units, unsigned base)
3313 {
3314         unsigned mode = *units & ~UNITS_MODE_MASK;
3315
3316         *units = base | mode;
3317 }
3318
3319 int find_next_key(struct btrfs_path *path, struct btrfs_key *key)
3320 {
3321         int level;
3322
3323         for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
3324                 if (!path->nodes[level])
3325                         break;
3326                 if (path->slots[level] + 1 >=
3327                     btrfs_header_nritems(path->nodes[level]))
3328                         continue;
3329                 if (level == 0)
3330                         btrfs_item_key_to_cpu(path->nodes[level], key,
3331                                               path->slots[level] + 1);
3332                 else
3333                         btrfs_node_key_to_cpu(path->nodes[level], key,
3334                                               path->slots[level] + 1);
3335                 return 0;
3336         }
3337         return 1;
3338 }
3339
3340 const char* btrfs_group_type_str(u64 flag)
3341 {
3342         u64 mask = BTRFS_BLOCK_GROUP_TYPE_MASK |
3343                 BTRFS_SPACE_INFO_GLOBAL_RSV;
3344
3345         switch (flag & mask) {
3346         case BTRFS_BLOCK_GROUP_DATA:
3347                 return "Data";
3348         case BTRFS_BLOCK_GROUP_SYSTEM:
3349                 return "System";
3350         case BTRFS_BLOCK_GROUP_METADATA:
3351                 return "Metadata";
3352         case BTRFS_BLOCK_GROUP_DATA|BTRFS_BLOCK_GROUP_METADATA:
3353                 return "Data+Metadata";
3354         case BTRFS_SPACE_INFO_GLOBAL_RSV:
3355                 return "GlobalReserve";
3356         default:
3357                 return "unknown";
3358         }
3359 }
3360
3361 const char* btrfs_group_profile_str(u64 flag)
3362 {
3363         switch (flag & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
3364         case 0:
3365                 return "single";
3366         case BTRFS_BLOCK_GROUP_RAID0:
3367                 return "RAID0";
3368         case BTRFS_BLOCK_GROUP_RAID1:
3369                 return "RAID1";
3370         case BTRFS_BLOCK_GROUP_RAID5:
3371                 return "RAID5";
3372         case BTRFS_BLOCK_GROUP_RAID6:
3373                 return "RAID6";
3374         case BTRFS_BLOCK_GROUP_DUP:
3375                 return "DUP";
3376         case BTRFS_BLOCK_GROUP_RAID10:
3377                 return "RAID10";
3378         default:
3379                 return "unknown";
3380         }
3381 }
3382
3383 u64 disk_size(const char *path)
3384 {
3385         struct statfs sfs;
3386
3387         if (statfs(path, &sfs) < 0)
3388                 return 0;
3389         else
3390                 return sfs.f_bsize * sfs.f_blocks;
3391 }
3392
3393 u64 get_partition_size(const char *dev)
3394 {
3395         u64 result;
3396         int fd = open(dev, O_RDONLY);
3397
3398         if (fd < 0)
3399                 return 0;
3400         if (ioctl(fd, BLKGETSIZE64, &result) < 0) {
3401                 close(fd);
3402                 return 0;
3403         }
3404         close(fd);
3405
3406         return result;
3407 }
3408
3409 /*
3410  * Check if the BTRFS_IOC_TREE_SEARCH_V2 ioctl is supported on a given
3411  * filesystem, opened at fd
3412  */
3413 int btrfs_tree_search2_ioctl_supported(int fd)
3414 {
3415         struct btrfs_ioctl_search_args_v2 *args2;
3416         struct btrfs_ioctl_search_key *sk;
3417         int args2_size = 1024;
3418         char args2_buf[args2_size];
3419         int ret;
3420
3421         args2 = (struct btrfs_ioctl_search_args_v2 *)args2_buf;
3422         sk = &(args2->key);
3423
3424         /*
3425          * Search for the extent tree item in the root tree.
3426          */
3427         sk->tree_id = BTRFS_ROOT_TREE_OBJECTID;
3428         sk->min_objectid = BTRFS_EXTENT_TREE_OBJECTID;
3429         sk->max_objectid = BTRFS_EXTENT_TREE_OBJECTID;
3430         sk->min_type = BTRFS_ROOT_ITEM_KEY;
3431         sk->max_type = BTRFS_ROOT_ITEM_KEY;
3432         sk->min_offset = 0;
3433         sk->max_offset = (u64)-1;
3434         sk->min_transid = 0;
3435         sk->max_transid = (u64)-1;
3436         sk->nr_items = 1;
3437         args2->buf_size = args2_size - sizeof(struct btrfs_ioctl_search_args_v2);
3438         ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH_V2, args2);
3439         if (ret == -EOPNOTSUPP)
3440                 return 0;
3441         else if (ret == 0)
3442                 return 1;
3443         return ret;
3444 }
3445
3446 int btrfs_check_nodesize(u32 nodesize, u32 sectorsize, u64 features)
3447 {
3448         if (nodesize < sectorsize) {
3449                 error("illegal nodesize %u (smaller than %u)",
3450                                 nodesize, sectorsize);
3451                 return -1;
3452         } else if (nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
3453                 error("illegal nodesize %u (larger than %u)",
3454                         nodesize, BTRFS_MAX_METADATA_BLOCKSIZE);
3455                 return -1;
3456         } else if (nodesize & (sectorsize - 1)) {
3457                 error("illegal nodesize %u (not aligned to %u)",
3458                         nodesize, sectorsize);
3459                 return -1;
3460         } else if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS &&
3461                    nodesize != sectorsize) {
3462                 error("illegal nodesize %u (not equal to %u for mixed block group)",
3463                         nodesize, sectorsize);
3464                 return -1;
3465         }
3466         return 0;
3467 }
3468
3469 /*
3470  * Copy a path argument from SRC to DEST and check the SRC length if it's at
3471  * most PATH_MAX and fits into DEST. DESTLEN is supposed to be exact size of
3472  * the buffer.
3473  * The destination buffer is zero terminated.
3474  * Return < 0 for error, 0 otherwise.
3475  */
3476 int arg_copy_path(char *dest, const char *src, int destlen)
3477 {
3478         size_t len = strlen(src);
3479
3480         if (len >= PATH_MAX || len >= destlen)
3481                 return -ENAMETOOLONG;
3482
3483         __strncpy_null(dest, src, destlen);
3484
3485         return 0;
3486 }
3487
3488 unsigned int get_unit_mode_from_arg(int *argc, char *argv[], int df_mode)
3489 {
3490         unsigned int unit_mode = UNITS_DEFAULT;
3491         int arg_i;
3492         int arg_end;
3493
3494         for (arg_i = 0; arg_i < *argc; arg_i++) {
3495                 if (!strcmp(argv[arg_i], "--"))
3496                         break;
3497
3498                 if (!strcmp(argv[arg_i], "--raw")) {
3499                         unit_mode = UNITS_RAW;
3500                         argv[arg_i] = NULL;
3501                         continue;
3502                 }
3503                 if (!strcmp(argv[arg_i], "--human-readable")) {
3504                         unit_mode = UNITS_HUMAN_BINARY;
3505                         argv[arg_i] = NULL;
3506                         continue;
3507                 }
3508
3509                 if (!strcmp(argv[arg_i], "--iec")) {
3510                         units_set_mode(&unit_mode, UNITS_BINARY);
3511                         argv[arg_i] = NULL;
3512                         continue;
3513                 }
3514                 if (!strcmp(argv[arg_i], "--si")) {
3515                         units_set_mode(&unit_mode, UNITS_DECIMAL);
3516                         argv[arg_i] = NULL;
3517                         continue;
3518                 }
3519
3520                 if (!strcmp(argv[arg_i], "--kbytes")) {
3521                         units_set_base(&unit_mode, UNITS_KBYTES);
3522                         argv[arg_i] = NULL;
3523                         continue;
3524                 }
3525                 if (!strcmp(argv[arg_i], "--mbytes")) {
3526                         units_set_base(&unit_mode, UNITS_MBYTES);
3527                         argv[arg_i] = NULL;
3528                         continue;
3529                 }
3530                 if (!strcmp(argv[arg_i], "--gbytes")) {
3531                         units_set_base(&unit_mode, UNITS_GBYTES);
3532                         argv[arg_i] = NULL;
3533                         continue;
3534                 }
3535                 if (!strcmp(argv[arg_i], "--tbytes")) {
3536                         units_set_base(&unit_mode, UNITS_TBYTES);
3537                         argv[arg_i] = NULL;
3538                         continue;
3539                 }
3540
3541                 if (!df_mode)
3542                         continue;
3543
3544                 if (!strcmp(argv[arg_i], "-b")) {
3545                         unit_mode = UNITS_RAW;
3546                         argv[arg_i] = NULL;
3547                         continue;
3548                 }
3549                 if (!strcmp(argv[arg_i], "-h")) {
3550                         unit_mode = UNITS_HUMAN_BINARY;
3551                         argv[arg_i] = NULL;
3552                         continue;
3553                 }
3554                 if (!strcmp(argv[arg_i], "-H")) {
3555                         unit_mode = UNITS_HUMAN_DECIMAL;
3556                         argv[arg_i] = NULL;
3557                         continue;
3558                 }
3559                 if (!strcmp(argv[arg_i], "-k")) {
3560                         units_set_base(&unit_mode, UNITS_KBYTES);
3561                         argv[arg_i] = NULL;
3562                         continue;
3563                 }
3564                 if (!strcmp(argv[arg_i], "-m")) {
3565                         units_set_base(&unit_mode, UNITS_MBYTES);
3566                         argv[arg_i] = NULL;
3567                         continue;
3568                 }
3569                 if (!strcmp(argv[arg_i], "-g")) {
3570                         units_set_base(&unit_mode, UNITS_GBYTES);
3571                         argv[arg_i] = NULL;
3572                         continue;
3573                 }
3574                 if (!strcmp(argv[arg_i], "-t")) {
3575                         units_set_base(&unit_mode, UNITS_TBYTES);
3576                         argv[arg_i] = NULL;
3577                         continue;
3578                 }
3579         }
3580
3581         for (arg_i = 0, arg_end = 0; arg_i < *argc; arg_i++) {
3582                 if (!argv[arg_i])
3583                         continue;
3584                 argv[arg_end] = argv[arg_i];
3585                 arg_end++;
3586         }
3587
3588         *argc = arg_end;
3589
3590         return unit_mode;
3591 }
3592
3593 int string_is_numerical(const char *str)
3594 {
3595         if (!str)
3596                 return 0;
3597         if (!(*str >= '0' && *str <= '9'))
3598                 return 0;
3599         while (*str >= '0' && *str <= '9')
3600                 str++;
3601         if (*str != '\0')
3602                 return 0;
3603         return 1;
3604 }
3605
3606 /* Subvolume helper functions */
3607 /*
3608  * test if name is a correct subvolume name
3609  * this function return
3610  * 0-> name is not a correct subvolume name
3611  * 1-> name is a correct subvolume name
3612  */
3613 int test_issubvolname(const char *name)
3614 {
3615         return name[0] != '\0' && !strchr(name, '/') &&
3616                 strcmp(name, ".") && strcmp(name, "..");
3617 }
3618
3619 /*
3620  * Test if path is a subvolume
3621  * Returns:
3622  *   0 - path exists but it is not a subvolume
3623  *   1 - path exists and it is  a subvolume
3624  * < 0 - error
3625  */
3626 int test_issubvolume(const char *path)
3627 {
3628         struct stat     st;
3629         struct statfs stfs;
3630         int             res;
3631
3632         res = stat(path, &st);
3633         if (res < 0)
3634                 return -errno;
3635
3636         if (st.st_ino != BTRFS_FIRST_FREE_OBJECTID || !S_ISDIR(st.st_mode))
3637                 return 0;
3638
3639         res = statfs(path, &stfs);
3640         if (res < 0)
3641                 return -errno;
3642
3643         return (int)stfs.f_type == BTRFS_SUPER_MAGIC;
3644 }
3645
3646 const char *subvol_strip_mountpoint(const char *mnt, const char *full_path)
3647 {
3648         int len = strlen(mnt);
3649         if (!len)
3650                 return full_path;
3651
3652         if (mnt[len - 1] != '/')
3653                 len += 1;
3654
3655         return full_path + len;
3656 }
3657
3658 /*
3659  * Returns
3660  * <0: Std error
3661  * 0: All fine
3662  * 1: Error; and error info printed to the terminal. Fixme.
3663  * 2: If the fullpath is root tree instead of subvol tree
3664  */
3665 int get_subvol_info(const char *fullpath, struct root_info *get_ri)
3666 {
3667         u64 sv_id;
3668         int ret = 1;
3669         int fd = -1;
3670         int mntfd = -1;
3671         char *mnt = NULL;
3672         const char *svpath = NULL;
3673         DIR *dirstream1 = NULL;
3674         DIR *dirstream2 = NULL;
3675
3676         ret = test_issubvolume(fullpath);
3677         if (ret < 0)
3678                 return ret;
3679         if (!ret) {
3680                 error("not a subvolume: %s", fullpath);
3681                 return 1;
3682         }
3683
3684         ret = find_mount_root(fullpath, &mnt);
3685         if (ret < 0)
3686                 return ret;
3687         if (ret > 0) {
3688                 error("%s doesn't belong to btrfs mount point", fullpath);
3689                 return 1;
3690         }
3691         ret = 1;
3692         svpath = subvol_strip_mountpoint(mnt, fullpath);
3693
3694         fd = btrfs_open_dir(fullpath, &dirstream1, 1);
3695         if (fd < 0)
3696                 goto out;
3697
3698         ret = btrfs_list_get_path_rootid(fd, &sv_id);
3699         if (ret)
3700                 goto out;
3701
3702         mntfd = btrfs_open_dir(mnt, &dirstream2, 1);
3703         if (mntfd < 0)
3704                 goto out;
3705
3706         memset(get_ri, 0, sizeof(*get_ri));
3707         get_ri->root_id = sv_id;
3708
3709         if (sv_id == BTRFS_FS_TREE_OBJECTID)
3710                 ret = btrfs_get_toplevel_subvol(mntfd, get_ri);
3711         else
3712                 ret = btrfs_get_subvol(mntfd, get_ri);
3713         if (ret)
3714                 error("can't find '%s': %d", svpath, ret);
3715
3716 out:
3717         close_file_or_dir(mntfd, dirstream2);
3718         close_file_or_dir(fd, dirstream1);
3719         free(mnt);
3720
3721         return ret;
3722 }
3723
3724 void init_rand_seed(u64 seed)
3725 {
3726         int i;
3727
3728         /* only use the last 48 bits */
3729         for (i = 0; i < 3; i++) {
3730                 rand_seed[i] = (unsigned short)(seed ^ (unsigned short)(-1));
3731                 seed >>= 16;
3732         }
3733         rand_seed_initlized = 1;
3734 }
3735
3736 static void __init_seed(void)
3737 {
3738         struct timeval tv;
3739         int ret;
3740         int fd;
3741
3742         if(rand_seed_initlized)
3743                 return;
3744         /* Use urandom as primary seed source. */
3745         fd = open("/dev/urandom", O_RDONLY);
3746         if (fd >= 0) {
3747                 ret = read(fd, rand_seed, sizeof(rand_seed));
3748                 close(fd);
3749                 if (ret < sizeof(rand_seed))
3750                         goto fallback;
3751         } else {
3752 fallback:
3753                 /* Use time and pid as fallback seed */
3754                 warning("failed to read /dev/urandom, use time and pid as random seed");
3755                 gettimeofday(&tv, 0);
3756                 rand_seed[0] = getpid() ^ (tv.tv_sec & 0xFFFF);
3757                 rand_seed[1] = getppid() ^ (tv.tv_usec & 0xFFFF);
3758                 rand_seed[2] = (tv.tv_sec ^ tv.tv_usec) >> 16;
3759         }
3760         rand_seed_initlized = 1;
3761 }
3762
3763 u32 rand_u32(void)
3764 {
3765         __init_seed();
3766         /*
3767          * Don't use nrand48, its range is [0,2^31) The highest bit will alwasy
3768          * be 0.  Use jrand48 to include the highest bit.
3769          */
3770         return (u32)jrand48(rand_seed);
3771 }
3772
3773 unsigned int rand_range(unsigned int upper)
3774 {
3775         __init_seed();
3776         /*
3777          * Use the full 48bits to mod, which would be more uniformly
3778          * distributed
3779          */
3780         return (unsigned int)(jrand48(rand_seed) % upper);
3781 }
3782
3783 void btrfs_config_init(void)
3784 {
3785 }