Btrfs-progs: make btrfs-image restore with a valid chunk tree V2
[platform/upstream/btrfs-progs.git] / utils.c
1 /*
2  * Copyright (C) 2007 Oracle.  All rights reserved.
3  * Copyright (C) 2008 Morey Roof.  All rights reserved.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public
7  * License v2 as published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public
15  * License along with this program; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 021110-1307, USA.
18  */
19
20 #define _XOPEN_SOURCE 700
21 #define __USE_XOPEN2K8
22 #define __XOPEN2K8 /* due to an error in dirent.h, to get dirfd() */
23 #define _GNU_SOURCE     /* O_NOATIME */
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #ifndef __CHECKER__
28 #include <sys/ioctl.h>
29 #include <sys/mount.h>
30 #endif
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 #include <uuid/uuid.h>
34 #include <dirent.h>
35 #include <fcntl.h>
36 #include <unistd.h>
37 #include <mntent.h>
38 #include <ctype.h>
39 #include <linux/loop.h>
40 #include <linux/major.h>
41 #include <linux/kdev_t.h>
42 #include <limits.h>
43 #include "kerncompat.h"
44 #include "radix-tree.h"
45 #include "ctree.h"
46 #include "disk-io.h"
47 #include "transaction.h"
48 #include "crc32c.h"
49 #include "utils.h"
50 #include "volumes.h"
51 #include "ioctl.h"
52
53 #ifdef __CHECKER__
54 #define BLKGETSIZE64 0
55 static inline int ioctl(int fd, int define, u64 *size) { return 0; }
56 #endif
57
58 #ifndef BLKDISCARD
59 #define BLKDISCARD      _IO(0x12,119)
60 #endif
61
62 static int
63 discard_blocks(int fd, u64 start, u64 len)
64 {
65         u64 range[2] = { start, len };
66
67         if (ioctl(fd, BLKDISCARD, &range) < 0)
68                 return errno;
69         return 0;
70 }
71
72 static u64 reference_root_table[] = {
73         [1] =   BTRFS_ROOT_TREE_OBJECTID,
74         [2] =   BTRFS_EXTENT_TREE_OBJECTID,
75         [3] =   BTRFS_CHUNK_TREE_OBJECTID,
76         [4] =   BTRFS_DEV_TREE_OBJECTID,
77         [5] =   BTRFS_FS_TREE_OBJECTID,
78         [6] =   BTRFS_CSUM_TREE_OBJECTID,
79 };
80
81 int make_btrfs(int fd, const char *device, const char *label,
82                u64 blocks[7], u64 num_bytes, u32 nodesize,
83                u32 leafsize, u32 sectorsize, u32 stripesize)
84 {
85         struct btrfs_super_block super;
86         struct extent_buffer *buf;
87         struct btrfs_root_item root_item;
88         struct btrfs_disk_key disk_key;
89         struct btrfs_extent_item *extent_item;
90         struct btrfs_inode_item *inode_item;
91         struct btrfs_chunk *chunk;
92         struct btrfs_dev_item *dev_item;
93         struct btrfs_dev_extent *dev_extent;
94         u8 chunk_tree_uuid[BTRFS_UUID_SIZE];
95         u8 *ptr;
96         int i;
97         int ret;
98         u32 itemoff;
99         u32 nritems = 0;
100         u64 first_free;
101         u64 ref_root;
102         u32 array_size;
103         u32 item_size;
104
105         first_free = BTRFS_SUPER_INFO_OFFSET + sectorsize * 2 - 1;
106         first_free &= ~((u64)sectorsize - 1);
107
108         memset(&super, 0, sizeof(super));
109
110         num_bytes = (num_bytes / sectorsize) * sectorsize;
111         uuid_generate(super.fsid);
112         uuid_generate(super.dev_item.uuid);
113         uuid_generate(chunk_tree_uuid);
114
115         btrfs_set_super_bytenr(&super, blocks[0]);
116         btrfs_set_super_num_devices(&super, 1);
117         super.magic = cpu_to_le64(BTRFS_MAGIC);
118         btrfs_set_super_generation(&super, 1);
119         btrfs_set_super_root(&super, blocks[1]);
120         btrfs_set_super_chunk_root(&super, blocks[3]);
121         btrfs_set_super_total_bytes(&super, num_bytes);
122         btrfs_set_super_bytes_used(&super, 6 * leafsize);
123         btrfs_set_super_sectorsize(&super, sectorsize);
124         btrfs_set_super_leafsize(&super, leafsize);
125         btrfs_set_super_nodesize(&super, nodesize);
126         btrfs_set_super_stripesize(&super, stripesize);
127         btrfs_set_super_csum_type(&super, BTRFS_CSUM_TYPE_CRC32);
128         btrfs_set_super_chunk_root_generation(&super, 1);
129         btrfs_set_super_cache_generation(&super, -1);
130         if (label)
131                 strncpy(super.label, label, BTRFS_LABEL_SIZE - 1);
132
133         buf = malloc(sizeof(*buf) + max(sectorsize, leafsize));
134
135         /* create the tree of root objects */
136         memset(buf->data, 0, leafsize);
137         buf->len = leafsize;
138         btrfs_set_header_bytenr(buf, blocks[1]);
139         btrfs_set_header_nritems(buf, 4);
140         btrfs_set_header_generation(buf, 1);
141         btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
142         btrfs_set_header_owner(buf, BTRFS_ROOT_TREE_OBJECTID);
143         write_extent_buffer(buf, super.fsid, (unsigned long)
144                             btrfs_header_fsid(buf), BTRFS_FSID_SIZE);
145
146         write_extent_buffer(buf, chunk_tree_uuid, (unsigned long)
147                             btrfs_header_chunk_tree_uuid(buf),
148                             BTRFS_UUID_SIZE);
149
150         /* create the items for the root tree */
151         memset(&root_item, 0, sizeof(root_item));
152         inode_item = &root_item.inode;
153         btrfs_set_stack_inode_generation(inode_item, 1);
154         btrfs_set_stack_inode_size(inode_item, 3);
155         btrfs_set_stack_inode_nlink(inode_item, 1);
156         btrfs_set_stack_inode_nbytes(inode_item, leafsize);
157         btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
158         btrfs_set_root_refs(&root_item, 1);
159         btrfs_set_root_used(&root_item, leafsize);
160         btrfs_set_root_generation(&root_item, 1);
161
162         memset(&disk_key, 0, sizeof(disk_key));
163         btrfs_set_disk_key_type(&disk_key, BTRFS_ROOT_ITEM_KEY);
164         btrfs_set_disk_key_offset(&disk_key, 0);
165         nritems = 0;
166
167         itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize) - sizeof(root_item);
168         btrfs_set_root_bytenr(&root_item, blocks[2]);
169         btrfs_set_disk_key_objectid(&disk_key, BTRFS_EXTENT_TREE_OBJECTID);
170         btrfs_set_item_key(buf, &disk_key, nritems);
171         btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems), itemoff);
172         btrfs_set_item_size(buf, btrfs_item_nr(buf, nritems),
173                             sizeof(root_item));
174         write_extent_buffer(buf, &root_item, btrfs_item_ptr_offset(buf,
175                             nritems), sizeof(root_item));
176         nritems++;
177
178         itemoff = itemoff - sizeof(root_item);
179         btrfs_set_root_bytenr(&root_item, blocks[4]);
180         btrfs_set_disk_key_objectid(&disk_key, BTRFS_DEV_TREE_OBJECTID);
181         btrfs_set_item_key(buf, &disk_key, nritems);
182         btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems), itemoff);
183         btrfs_set_item_size(buf, btrfs_item_nr(buf, nritems),
184                             sizeof(root_item));
185         write_extent_buffer(buf, &root_item,
186                             btrfs_item_ptr_offset(buf, nritems),
187                             sizeof(root_item));
188         nritems++;
189
190         itemoff = itemoff - sizeof(root_item);
191         btrfs_set_root_bytenr(&root_item, blocks[5]);
192         btrfs_set_disk_key_objectid(&disk_key, BTRFS_FS_TREE_OBJECTID);
193         btrfs_set_item_key(buf, &disk_key, nritems);
194         btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems), itemoff);
195         btrfs_set_item_size(buf, btrfs_item_nr(buf, nritems),
196                             sizeof(root_item));
197         write_extent_buffer(buf, &root_item,
198                             btrfs_item_ptr_offset(buf, nritems),
199                             sizeof(root_item));
200         nritems++;
201
202         itemoff = itemoff - sizeof(root_item);
203         btrfs_set_root_bytenr(&root_item, blocks[6]);
204         btrfs_set_disk_key_objectid(&disk_key, BTRFS_CSUM_TREE_OBJECTID);
205         btrfs_set_item_key(buf, &disk_key, nritems);
206         btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems), itemoff);
207         btrfs_set_item_size(buf, btrfs_item_nr(buf, nritems),
208                             sizeof(root_item));
209         write_extent_buffer(buf, &root_item,
210                             btrfs_item_ptr_offset(buf, nritems),
211                             sizeof(root_item));
212         nritems++;
213
214
215         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
216         ret = pwrite(fd, buf->data, leafsize, blocks[1]);
217         BUG_ON(ret != leafsize);
218
219         /* create the items for the extent tree */
220         memset(buf->data+sizeof(struct btrfs_header), 0,
221                 leafsize-sizeof(struct btrfs_header));
222         nritems = 0;
223         itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize);
224         for (i = 1; i < 7; i++) {
225                 BUG_ON(blocks[i] < first_free);
226                 BUG_ON(blocks[i] < blocks[i - 1]);
227
228                 /* create extent item */
229                 itemoff -= sizeof(struct btrfs_extent_item) +
230                            sizeof(struct btrfs_tree_block_info);
231                 btrfs_set_disk_key_objectid(&disk_key, blocks[i]);
232                 btrfs_set_disk_key_offset(&disk_key, leafsize);
233                 btrfs_set_disk_key_type(&disk_key, BTRFS_EXTENT_ITEM_KEY);
234                 btrfs_set_item_key(buf, &disk_key, nritems);
235                 btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems),
236                                       itemoff);
237                 btrfs_set_item_size(buf, btrfs_item_nr(buf, nritems),
238                                     sizeof(struct btrfs_extent_item) +
239                                     sizeof(struct btrfs_tree_block_info));
240                 extent_item = btrfs_item_ptr(buf, nritems,
241                                              struct btrfs_extent_item);
242                 btrfs_set_extent_refs(buf, extent_item, 1);
243                 btrfs_set_extent_generation(buf, extent_item, 1);
244                 btrfs_set_extent_flags(buf, extent_item,
245                                        BTRFS_EXTENT_FLAG_TREE_BLOCK);
246                 nritems++;
247
248                 /* create extent ref */
249                 ref_root = reference_root_table[i];
250                 btrfs_set_disk_key_objectid(&disk_key, blocks[i]);
251                 btrfs_set_disk_key_offset(&disk_key, ref_root);
252                 btrfs_set_disk_key_type(&disk_key, BTRFS_TREE_BLOCK_REF_KEY);
253                 btrfs_set_item_key(buf, &disk_key, nritems);
254                 btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems),
255                                       itemoff);
256                 btrfs_set_item_size(buf, btrfs_item_nr(buf, nritems), 0);
257                 nritems++;
258         }
259         btrfs_set_header_bytenr(buf, blocks[2]);
260         btrfs_set_header_owner(buf, BTRFS_EXTENT_TREE_OBJECTID);
261         btrfs_set_header_nritems(buf, nritems);
262         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
263         ret = pwrite(fd, buf->data, leafsize, blocks[2]);
264         BUG_ON(ret != leafsize);
265
266         /* create the chunk tree */
267         memset(buf->data+sizeof(struct btrfs_header), 0,
268                 leafsize-sizeof(struct btrfs_header));
269         nritems = 0;
270         item_size = sizeof(*dev_item);
271         itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize) - item_size;
272
273         /* first device 1 (there is no device 0) */
274         btrfs_set_disk_key_objectid(&disk_key, BTRFS_DEV_ITEMS_OBJECTID);
275         btrfs_set_disk_key_offset(&disk_key, 1);
276         btrfs_set_disk_key_type(&disk_key, BTRFS_DEV_ITEM_KEY);
277         btrfs_set_item_key(buf, &disk_key, nritems);
278         btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems), itemoff);
279         btrfs_set_item_size(buf, btrfs_item_nr(buf, nritems), item_size);
280
281         dev_item = btrfs_item_ptr(buf, nritems, struct btrfs_dev_item);
282         btrfs_set_device_id(buf, dev_item, 1);
283         btrfs_set_device_generation(buf, dev_item, 0);
284         btrfs_set_device_total_bytes(buf, dev_item, num_bytes);
285         btrfs_set_device_bytes_used(buf, dev_item,
286                                     BTRFS_MKFS_SYSTEM_GROUP_SIZE);
287         btrfs_set_device_io_align(buf, dev_item, sectorsize);
288         btrfs_set_device_io_width(buf, dev_item, sectorsize);
289         btrfs_set_device_sector_size(buf, dev_item, sectorsize);
290         btrfs_set_device_type(buf, dev_item, 0);
291
292         write_extent_buffer(buf, super.dev_item.uuid,
293                             (unsigned long)btrfs_device_uuid(dev_item),
294                             BTRFS_UUID_SIZE);
295         write_extent_buffer(buf, super.fsid,
296                             (unsigned long)btrfs_device_fsid(dev_item),
297                             BTRFS_UUID_SIZE);
298         read_extent_buffer(buf, &super.dev_item, (unsigned long)dev_item,
299                            sizeof(*dev_item));
300
301         nritems++;
302         item_size = btrfs_chunk_item_size(1);
303         itemoff = itemoff - item_size;
304
305         /* then we have chunk 0 */
306         btrfs_set_disk_key_objectid(&disk_key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
307         btrfs_set_disk_key_offset(&disk_key, 0);
308         btrfs_set_disk_key_type(&disk_key, BTRFS_CHUNK_ITEM_KEY);
309         btrfs_set_item_key(buf, &disk_key, nritems);
310         btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems), itemoff);
311         btrfs_set_item_size(buf, btrfs_item_nr(buf,  nritems), item_size);
312
313         chunk = btrfs_item_ptr(buf, nritems, struct btrfs_chunk);
314         btrfs_set_chunk_length(buf, chunk, BTRFS_MKFS_SYSTEM_GROUP_SIZE);
315         btrfs_set_chunk_owner(buf, chunk, BTRFS_EXTENT_TREE_OBJECTID);
316         btrfs_set_chunk_stripe_len(buf, chunk, 64 * 1024);
317         btrfs_set_chunk_type(buf, chunk, BTRFS_BLOCK_GROUP_SYSTEM);
318         btrfs_set_chunk_io_align(buf, chunk, sectorsize);
319         btrfs_set_chunk_io_width(buf, chunk, sectorsize);
320         btrfs_set_chunk_sector_size(buf, chunk, sectorsize);
321         btrfs_set_chunk_num_stripes(buf, chunk, 1);
322         btrfs_set_stripe_devid_nr(buf, chunk, 0, 1);
323         btrfs_set_stripe_offset_nr(buf, chunk, 0, 0);
324         nritems++;
325
326         write_extent_buffer(buf, super.dev_item.uuid,
327                             (unsigned long)btrfs_stripe_dev_uuid(&chunk->stripe),
328                             BTRFS_UUID_SIZE);
329
330         /* copy the key for the chunk to the system array */
331         ptr = super.sys_chunk_array;
332         array_size = sizeof(disk_key);
333
334         memcpy(ptr, &disk_key, sizeof(disk_key));
335         ptr += sizeof(disk_key);
336
337         /* copy the chunk to the system array */
338         read_extent_buffer(buf, ptr, (unsigned long)chunk, item_size);
339         array_size += item_size;
340         ptr += item_size;
341         btrfs_set_super_sys_array_size(&super, array_size);
342
343         btrfs_set_header_bytenr(buf, blocks[3]);
344         btrfs_set_header_owner(buf, BTRFS_CHUNK_TREE_OBJECTID);
345         btrfs_set_header_nritems(buf, nritems);
346         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
347         ret = pwrite(fd, buf->data, leafsize, blocks[3]);
348
349         /* create the device tree */
350         memset(buf->data+sizeof(struct btrfs_header), 0,
351                 leafsize-sizeof(struct btrfs_header));
352         nritems = 0;
353         itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize) -
354                 sizeof(struct btrfs_dev_extent);
355
356         btrfs_set_disk_key_objectid(&disk_key, 1);
357         btrfs_set_disk_key_offset(&disk_key, 0);
358         btrfs_set_disk_key_type(&disk_key, BTRFS_DEV_EXTENT_KEY);
359         btrfs_set_item_key(buf, &disk_key, nritems);
360         btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems), itemoff);
361         btrfs_set_item_size(buf, btrfs_item_nr(buf,  nritems),
362                             sizeof(struct btrfs_dev_extent));
363         dev_extent = btrfs_item_ptr(buf, nritems, struct btrfs_dev_extent);
364         btrfs_set_dev_extent_chunk_tree(buf, dev_extent,
365                                         BTRFS_CHUNK_TREE_OBJECTID);
366         btrfs_set_dev_extent_chunk_objectid(buf, dev_extent,
367                                         BTRFS_FIRST_CHUNK_TREE_OBJECTID);
368         btrfs_set_dev_extent_chunk_offset(buf, dev_extent, 0);
369
370         write_extent_buffer(buf, chunk_tree_uuid,
371                     (unsigned long)btrfs_dev_extent_chunk_tree_uuid(dev_extent),
372                     BTRFS_UUID_SIZE);
373
374         btrfs_set_dev_extent_length(buf, dev_extent,
375                                     BTRFS_MKFS_SYSTEM_GROUP_SIZE);
376         nritems++;
377
378         btrfs_set_header_bytenr(buf, blocks[4]);
379         btrfs_set_header_owner(buf, BTRFS_DEV_TREE_OBJECTID);
380         btrfs_set_header_nritems(buf, nritems);
381         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
382         ret = pwrite(fd, buf->data, leafsize, blocks[4]);
383
384         /* create the FS root */
385         memset(buf->data+sizeof(struct btrfs_header), 0,
386                 leafsize-sizeof(struct btrfs_header));
387         btrfs_set_header_bytenr(buf, blocks[5]);
388         btrfs_set_header_owner(buf, BTRFS_FS_TREE_OBJECTID);
389         btrfs_set_header_nritems(buf, 0);
390         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
391         ret = pwrite(fd, buf->data, leafsize, blocks[5]);
392         BUG_ON(ret != leafsize);
393
394         /* finally create the csum root */
395         memset(buf->data+sizeof(struct btrfs_header), 0,
396                 leafsize-sizeof(struct btrfs_header));
397         btrfs_set_header_bytenr(buf, blocks[6]);
398         btrfs_set_header_owner(buf, BTRFS_CSUM_TREE_OBJECTID);
399         btrfs_set_header_nritems(buf, 0);
400         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
401         ret = pwrite(fd, buf->data, leafsize, blocks[6]);
402         BUG_ON(ret != leafsize);
403
404         /* and write out the super block */
405         BUG_ON(sizeof(super) > sectorsize);
406         memset(buf->data, 0, sectorsize);
407         memcpy(buf->data, &super, sizeof(super));
408         buf->len = sectorsize;
409         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
410         ret = pwrite(fd, buf->data, sectorsize, blocks[0]);
411         BUG_ON(ret != sectorsize);
412
413
414         free(buf);
415         return 0;
416 }
417
418 u64 btrfs_device_size(int fd, struct stat *st)
419 {
420         u64 size;
421         if (S_ISREG(st->st_mode)) {
422                 return st->st_size;
423         }
424         if (!S_ISBLK(st->st_mode)) {
425                 return 0;
426         }
427         if (ioctl(fd, BLKGETSIZE64, &size) >= 0) {
428                 return size;
429         }
430         return 0;
431 }
432
433 static int zero_blocks(int fd, off_t start, size_t len)
434 {
435         char *buf = malloc(len);
436         int ret = 0;
437         ssize_t written;
438
439         if (!buf)
440                 return -ENOMEM;
441         memset(buf, 0, len);
442         written = pwrite(fd, buf, len, start);
443         if (written != len)
444                 ret = -EIO;
445         free(buf);
446         return ret;
447 }
448
449 static int zero_dev_start(int fd)
450 {
451         off_t start = 0;
452         size_t len = 2 * 1024 * 1024;
453
454 #ifdef __sparc__
455         /* don't overwrite the disk labels on sparc */
456         start = 1024;
457         len -= 1024;
458 #endif
459         return zero_blocks(fd, start, len);
460 }
461
462 static int zero_dev_end(int fd, u64 dev_size)
463 {
464         size_t len = 2 * 1024 * 1024;
465         off_t start = dev_size - len;
466
467         return zero_blocks(fd, start, len);
468 }
469
470 int btrfs_add_to_fsid(struct btrfs_trans_handle *trans,
471                       struct btrfs_root *root, int fd, char *path,
472                       u64 block_count, u32 io_width, u32 io_align,
473                       u32 sectorsize)
474 {
475         struct btrfs_super_block *disk_super;
476         struct btrfs_super_block *super = root->fs_info->super_copy;
477         struct btrfs_device *device;
478         struct btrfs_dev_item *dev_item;
479         char *buf;
480         u64 total_bytes;
481         u64 num_devs;
482         int ret;
483
484         device = kmalloc(sizeof(*device), GFP_NOFS);
485         if (!device)
486                 return -ENOMEM;
487         buf = kmalloc(sectorsize, GFP_NOFS);
488         if (!buf) {
489                 kfree(device);
490                 return -ENOMEM;
491         }
492         BUG_ON(sizeof(*disk_super) > sectorsize);
493         memset(buf, 0, sectorsize);
494
495         disk_super = (struct btrfs_super_block *)buf;
496         dev_item = &disk_super->dev_item;
497
498         uuid_generate(device->uuid);
499         device->devid = 0;
500         device->type = 0;
501         device->io_width = io_width;
502         device->io_align = io_align;
503         device->sector_size = sectorsize;
504         device->fd = fd;
505         device->writeable = 1;
506         device->total_bytes = block_count;
507         device->bytes_used = 0;
508         device->total_ios = 0;
509         device->dev_root = root->fs_info->dev_root;
510
511         ret = btrfs_add_device(trans, root, device);
512         BUG_ON(ret);
513
514         total_bytes = btrfs_super_total_bytes(super) + block_count;
515         btrfs_set_super_total_bytes(super, total_bytes);
516
517         num_devs = btrfs_super_num_devices(super) + 1;
518         btrfs_set_super_num_devices(super, num_devs);
519
520         memcpy(disk_super, super, sizeof(*disk_super));
521
522         printf("adding device %s id %llu\n", path,
523                (unsigned long long)device->devid);
524
525         btrfs_set_super_bytenr(disk_super, BTRFS_SUPER_INFO_OFFSET);
526         btrfs_set_stack_device_id(dev_item, device->devid);
527         btrfs_set_stack_device_type(dev_item, device->type);
528         btrfs_set_stack_device_io_align(dev_item, device->io_align);
529         btrfs_set_stack_device_io_width(dev_item, device->io_width);
530         btrfs_set_stack_device_sector_size(dev_item, device->sector_size);
531         btrfs_set_stack_device_total_bytes(dev_item, device->total_bytes);
532         btrfs_set_stack_device_bytes_used(dev_item, device->bytes_used);
533         memcpy(&dev_item->uuid, device->uuid, BTRFS_UUID_SIZE);
534
535         ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
536         BUG_ON(ret != sectorsize);
537
538         kfree(buf);
539         list_add(&device->dev_list, &root->fs_info->fs_devices->devices);
540         device->fs_devices = root->fs_info->fs_devices;
541         return 0;
542 }
543
544 int btrfs_prepare_device(int fd, char *file, int zero_end, u64 *block_count_ret,
545                            u64 max_block_count, int *mixed, int nodiscard)
546 {
547         u64 block_count;
548         u64 bytenr;
549         struct stat st;
550         int i, ret;
551
552         ret = fstat(fd, &st);
553         if (ret < 0) {
554                 fprintf(stderr, "unable to stat %s\n", file);
555                 exit(1);
556         }
557
558         block_count = btrfs_device_size(fd, &st);
559         if (block_count == 0) {
560                 fprintf(stderr, "unable to find %s size\n", file);
561                 exit(1);
562         }
563         if (max_block_count)
564                 block_count = min(block_count, max_block_count);
565         zero_end = 1;
566
567         if (block_count < 1024 * 1024 * 1024 && !(*mixed)) {
568                 printf("SMALL VOLUME: forcing mixed metadata/data groups\n");
569                 *mixed = 1;
570         }
571
572         if (!nodiscard) {
573                 /*
574                  * We intentionally ignore errors from the discard ioctl.  It is
575                  * not necessary for the mkfs functionality but just an optimization.
576                  */
577                 discard_blocks(fd, 0, block_count);
578         }
579
580         ret = zero_dev_start(fd);
581         if (ret) {
582                 fprintf(stderr, "failed to zero device start %d\n", ret);
583                 exit(1);
584         }
585
586         for (i = 0 ; i < BTRFS_SUPER_MIRROR_MAX; i++) {
587                 bytenr = btrfs_sb_offset(i);
588                 if (bytenr >= block_count)
589                         break;
590                 zero_blocks(fd, bytenr, BTRFS_SUPER_INFO_SIZE);
591         }
592
593         if (zero_end) {
594                 ret = zero_dev_end(fd, block_count);
595                 if (ret) {
596                         fprintf(stderr, "failed to zero device end %d\n", ret);
597                         exit(1);
598                 }
599         }
600         *block_count_ret = block_count;
601         return 0;
602 }
603
604 int btrfs_make_root_dir(struct btrfs_trans_handle *trans,
605                         struct btrfs_root *root, u64 objectid)
606 {
607         int ret;
608         struct btrfs_inode_item inode_item;
609         time_t now = time(NULL);
610
611         memset(&inode_item, 0, sizeof(inode_item));
612         btrfs_set_stack_inode_generation(&inode_item, trans->transid);
613         btrfs_set_stack_inode_size(&inode_item, 0);
614         btrfs_set_stack_inode_nlink(&inode_item, 1);
615         btrfs_set_stack_inode_nbytes(&inode_item, root->leafsize);
616         btrfs_set_stack_inode_mode(&inode_item, S_IFDIR | 0755);
617         btrfs_set_stack_timespec_sec(&inode_item.atime, now);
618         btrfs_set_stack_timespec_nsec(&inode_item.atime, 0);
619         btrfs_set_stack_timespec_sec(&inode_item.ctime, now);
620         btrfs_set_stack_timespec_nsec(&inode_item.ctime, 0);
621         btrfs_set_stack_timespec_sec(&inode_item.mtime, now);
622         btrfs_set_stack_timespec_nsec(&inode_item.mtime, 0);
623         btrfs_set_stack_timespec_sec(&inode_item.otime, 0);
624         btrfs_set_stack_timespec_nsec(&inode_item.otime, 0);
625
626         if (root->fs_info->tree_root == root)
627                 btrfs_set_super_root_dir(root->fs_info->super_copy, objectid);
628
629         ret = btrfs_insert_inode(trans, root, objectid, &inode_item);
630         if (ret)
631                 goto error;
632
633         ret = btrfs_insert_inode_ref(trans, root, "..", 2, objectid, objectid, 0);
634         if (ret)
635                 goto error;
636
637         btrfs_set_root_dirid(&root->root_item, objectid);
638         ret = 0;
639 error:
640         return ret;
641 }
642
643 /*
644  * checks if a path is a block device node
645  * Returns negative errno on failure, otherwise
646  * returns 1 for blockdev, 0 for not-blockdev
647  */
648 int is_block_device(const char *path) {
649         struct stat statbuf;
650
651         if (stat(path, &statbuf) < 0)
652                 return -errno;
653
654         return S_ISBLK(statbuf.st_mode);
655 }
656
657 /*
658  * Find the mount point for a mounted device.
659  * On success, returns 0 with mountpoint in *mp.
660  * On failure, returns -errno (not mounted yields -EINVAL)
661  * Is noisy on failures, expects to be given a mounted device.
662  */
663 int get_btrfs_mount(const char *dev, char *mp, size_t mp_size) {
664         int ret;
665         int fd = -1;
666
667         ret = is_block_device(dev);
668         if (ret <= 0) {
669                 if (!ret) {
670                         fprintf(stderr, "%s is not a block device\n", dev);
671                         ret = -EINVAL;
672                 } else {
673                         fprintf(stderr, "Could not check %s: %s\n",
674                                 dev, strerror(-ret));
675                 }
676                 goto out;
677         }
678
679         fd = open(dev, O_RDONLY);
680         if (fd < 0) {
681                 ret = -errno;
682                 fprintf(stderr, "Could not open %s: %s\n", dev, strerror(errno));
683                 goto out;
684         }
685
686         ret = check_mounted_where(fd, dev, mp, mp_size, NULL);
687         if (!ret) {
688                 fprintf(stderr, "%s is not a mounted btrfs device\n", dev);
689                 ret = -EINVAL;
690         } else { /* mounted, all good */
691                 ret = 0;
692         }
693 out:
694         if (fd != -1)
695                 close(fd);
696         if (ret)
697                 fprintf(stderr, "Could not get mountpoint for %s\n", dev);
698         return ret;
699 }
700
701 /*
702  * Given a pathname, return a filehandle to:
703  *      the original pathname or,
704  *      if the pathname is a mounted btrfs device, to its mountpoint.
705  *
706  * On error, return -1, errno should be set.
707  */
708 int open_path_or_dev_mnt(const char *path)
709 {
710         char mp[BTRFS_PATH_NAME_MAX + 1];
711         int fdmnt;
712
713         if (is_block_device(path)) {
714                 int ret;
715
716                 ret = get_btrfs_mount(path, mp, sizeof(mp));
717                 if (ret < 0) {
718                         /* not a mounted btrfs dev */
719                         errno = EINVAL;
720                         return -1;
721                 }
722                 fdmnt = open_file_or_dir(mp);
723         } else {
724                 fdmnt = open_file_or_dir(path);
725         }
726
727         return fdmnt;
728 }
729
730 /* checks if a device is a loop device */
731 int is_loop_device (const char* device) {
732         struct stat statbuf;
733
734         if(stat(device, &statbuf) < 0)
735                 return -errno;
736
737         return (S_ISBLK(statbuf.st_mode) &&
738                 MAJOR(statbuf.st_rdev) == LOOP_MAJOR);
739 }
740
741
742 /* Takes a loop device path (e.g. /dev/loop0) and returns
743  * the associated file (e.g. /images/my_btrfs.img) */
744 int resolve_loop_device(const char* loop_dev, char* loop_file, int max_len)
745 {
746         int ret;
747         FILE *f;
748         char fmt[20];
749         char p[PATH_MAX];
750         char real_loop_dev[PATH_MAX];
751
752         if (!realpath(loop_dev, real_loop_dev))
753                 return -errno;
754         snprintf(p, PATH_MAX, "/sys/block/%s/loop/backing_file", strrchr(real_loop_dev, '/'));
755         if (!(f = fopen(p, "r")))
756                 return -errno;
757
758         snprintf(fmt, 20, "%%%i[^\n]", max_len-1);
759         ret = fscanf(f, fmt, loop_file);
760         fclose(f);
761         if (ret == EOF)
762                 return -errno;
763
764         return 0;
765 }
766
767 /* Checks whether a and b are identical or device
768  * files associated with the same block device
769  */
770 int is_same_blk_file(const char* a, const char* b)
771 {
772         struct stat st_buf_a, st_buf_b;
773         char real_a[PATH_MAX];
774         char real_b[PATH_MAX];
775
776         if(!realpath(a, real_a) ||
777            !realpath(b, real_b))
778         {
779                 return -errno;
780         }
781
782         /* Identical path? */
783         if(strcmp(real_a, real_b) == 0)
784                 return 1;
785
786         if(stat(a, &st_buf_a) < 0 ||
787            stat(b, &st_buf_b) < 0)
788         {
789                 if (errno == ENOENT)
790                         return 0;
791                 return -errno;
792         }
793
794         /* Same blockdevice? */
795         if(S_ISBLK(st_buf_a.st_mode) &&
796            S_ISBLK(st_buf_b.st_mode) &&
797            st_buf_a.st_rdev == st_buf_b.st_rdev)
798         {
799                 return 1;
800         }
801
802         /* Hardlink? */
803         if (st_buf_a.st_dev == st_buf_b.st_dev &&
804             st_buf_a.st_ino == st_buf_b.st_ino)
805         {
806                 return 1;
807         }
808
809         return 0;
810 }
811
812 /* checks if a and b are identical or device
813  * files associated with the same block device or
814  * if one file is a loop device that uses the other
815  * file.
816  */
817 int is_same_loop_file(const char* a, const char* b)
818 {
819         char res_a[PATH_MAX];
820         char res_b[PATH_MAX];
821         const char* final_a;
822         const char* final_b;
823         int ret;
824
825         /* Resolve a if it is a loop device */
826         if((ret = is_loop_device(a)) < 0) {
827                 if (ret == -ENOENT)
828                         return 0;
829                 return ret;
830         } else if (ret) {
831                 if ((ret = resolve_loop_device(a, res_a, sizeof(res_a))) < 0)
832                         return ret;
833
834                 final_a = res_a;
835         } else {
836                 final_a = a;
837         }
838
839         /* Resolve b if it is a loop device */
840         if ((ret = is_loop_device(b)) < 0) {
841                 if (ret == -ENOENT)
842                         return 0;
843                 return ret;
844         } else if (ret) {
845                 if((ret = resolve_loop_device(b, res_b, sizeof(res_b))) < 0)
846                         return ret;
847
848                 final_b = res_b;
849         } else {
850                 final_b = b;
851         }
852
853         return is_same_blk_file(final_a, final_b);
854 }
855
856 /* Checks if a file exists and is a block or regular file*/
857 int is_existing_blk_or_reg_file(const char* filename)
858 {
859         struct stat st_buf;
860
861         if(stat(filename, &st_buf) < 0) {
862                 if(errno == ENOENT)
863                         return 0;
864                 else
865                         return -errno;
866         }
867
868         return (S_ISBLK(st_buf.st_mode) || S_ISREG(st_buf.st_mode));
869 }
870
871 /* Checks if a file is used (directly or indirectly via a loop device)
872  * by a device in fs_devices
873  */
874 int blk_file_in_dev_list(struct btrfs_fs_devices* fs_devices, const char* file)
875 {
876         int ret;
877         struct list_head *head;
878         struct list_head *cur;
879         struct btrfs_device *device;
880
881         head = &fs_devices->devices;
882         list_for_each(cur, head) {
883                 device = list_entry(cur, struct btrfs_device, dev_list);
884
885                 if((ret = is_same_loop_file(device->name, file)))
886                         return ret;
887         }
888
889         return 0;
890 }
891
892 /*
893  * returns 1 if the device was mounted, < 0 on error or 0 if everything
894  * is safe to continue.
895  */
896 int check_mounted(const char* file)
897 {
898         int fd;
899         int ret;
900
901         fd = open(file, O_RDONLY);
902         if (fd < 0) {
903                 fprintf (stderr, "check_mounted(): Could not open %s\n", file);
904                 return -errno;
905         }
906
907         ret =  check_mounted_where(fd, file, NULL, 0, NULL);
908         close(fd);
909
910         return ret;
911 }
912
913 int check_mounted_where(int fd, const char *file, char *where, int size,
914                         struct btrfs_fs_devices **fs_dev_ret)
915 {
916         int ret;
917         u64 total_devs = 1;
918         int is_btrfs;
919         struct btrfs_fs_devices *fs_devices_mnt = NULL;
920         FILE *f;
921         struct mntent *mnt;
922
923         /* scan the initial device */
924         ret = btrfs_scan_one_device(fd, file, &fs_devices_mnt,
925                                     &total_devs, BTRFS_SUPER_INFO_OFFSET);
926         is_btrfs = (ret >= 0);
927
928         /* scan other devices */
929         if (is_btrfs && total_devs > 1) {
930                 if((ret = btrfs_scan_for_fsid(fs_devices_mnt, total_devs, 1)))
931                         return ret;
932         }
933
934         /* iterate over the list of currently mountes filesystems */
935         if ((f = setmntent ("/proc/mounts", "r")) == NULL)
936                 return -errno;
937
938         while ((mnt = getmntent (f)) != NULL) {
939                 if(is_btrfs) {
940                         if(strcmp(mnt->mnt_type, "btrfs") != 0)
941                                 continue;
942
943                         ret = blk_file_in_dev_list(fs_devices_mnt, mnt->mnt_fsname);
944                 } else {
945                         /* ignore entries in the mount table that are not
946                            associated with a file*/
947                         if((ret = is_existing_blk_or_reg_file(mnt->mnt_fsname)) < 0)
948                                 goto out_mntloop_err;
949                         else if(!ret)
950                                 continue;
951
952                         ret = is_same_loop_file(file, mnt->mnt_fsname);
953                 }
954
955                 if(ret < 0)
956                         goto out_mntloop_err;
957                 else if(ret)
958                         break;
959         }
960
961         /* Did we find an entry in mnt table? */
962         if (mnt && size && where) {
963                 strncpy(where, mnt->mnt_dir, size);
964                 where[size-1] = 0;
965         }
966         if (fs_dev_ret)
967                 *fs_dev_ret = fs_devices_mnt;
968
969         ret = (mnt != NULL);
970
971 out_mntloop_err:
972         endmntent (f);
973
974         return ret;
975 }
976
977 /* Gets the mount point of btrfs filesystem that is using the specified device.
978  * Returns 0 is everything is good, <0 if we have an error.
979  * TODO: Fix this fucntion and check_mounted to work with multiple drive BTRFS
980  * setups.
981  */
982 int get_mountpt(char *dev, char *mntpt, size_t size)
983 {
984        struct mntent *mnt;
985        FILE *f;
986        int ret = 0;
987
988        f = setmntent("/proc/mounts", "r");
989        if (f == NULL)
990                return -errno;
991
992        while ((mnt = getmntent(f)) != NULL )
993        {
994                if (strcmp(dev, mnt->mnt_fsname) == 0)
995                {
996                        strncpy(mntpt, mnt->mnt_dir, size);
997                        if (size)
998                                 mntpt[size-1] = 0;
999                        break;
1000                }
1001        }
1002
1003        if (mnt == NULL)
1004        {
1005                /* We didn't find an entry so lets report an error */
1006                ret = -1;
1007        }
1008
1009        return ret;
1010 }
1011
1012 struct pending_dir {
1013         struct list_head list;
1014         char name[PATH_MAX];
1015 };
1016
1017 void btrfs_register_one_device(char *fname)
1018 {
1019         struct btrfs_ioctl_vol_args args;
1020         int fd;
1021         int ret;
1022         int e;
1023
1024         fd = open("/dev/btrfs-control", O_RDONLY);
1025         if (fd < 0) {
1026                 fprintf(stderr, "failed to open /dev/btrfs-control "
1027                         "skipping device registration: %s\n",
1028                         strerror(errno));
1029                 return;
1030         }
1031         strncpy(args.name, fname, BTRFS_PATH_NAME_MAX);
1032         args.name[BTRFS_PATH_NAME_MAX-1] = 0;
1033         ret = ioctl(fd, BTRFS_IOC_SCAN_DEV, &args);
1034         e = errno;
1035         if(ret<0){
1036                 fprintf(stderr, "ERROR: device scan failed '%s' - %s\n",
1037                         fname, strerror(e));
1038         }
1039         close(fd);
1040 }
1041
1042 int btrfs_scan_one_dir(char *dirname, int run_ioctl)
1043 {
1044         DIR *dirp = NULL;
1045         struct dirent *dirent;
1046         struct pending_dir *pending;
1047         struct stat st;
1048         int ret;
1049         int fd;
1050         int dirname_len;
1051         char *fullpath;
1052         struct list_head pending_list;
1053         struct btrfs_fs_devices *tmp_devices;
1054         u64 num_devices;
1055
1056         INIT_LIST_HEAD(&pending_list);
1057
1058         pending = malloc(sizeof(*pending));
1059         if (!pending)
1060                 return -ENOMEM;
1061         strcpy(pending->name, dirname);
1062
1063 again:
1064         dirname_len = strlen(pending->name);
1065         fullpath = malloc(PATH_MAX);
1066         dirname = pending->name;
1067
1068         if (!fullpath) {
1069                 ret = -ENOMEM;
1070                 goto fail;
1071         }
1072         dirp = opendir(dirname);
1073         if (!dirp) {
1074                 fprintf(stderr, "Unable to open %s for scanning\n", dirname);
1075                 free(fullpath);
1076                 return -ENOENT;
1077         }
1078         while(1) {
1079                 dirent = readdir(dirp);
1080                 if (!dirent)
1081                         break;
1082                 if (dirent->d_name[0] == '.')
1083                         continue;
1084                 if (dirname_len + strlen(dirent->d_name) + 2 > PATH_MAX) {
1085                         ret = -EFAULT;
1086                         goto fail;
1087                 }
1088                 snprintf(fullpath, PATH_MAX, "%s/%s", dirname, dirent->d_name);
1089                 ret = lstat(fullpath, &st);
1090                 if (ret < 0) {
1091                         fprintf(stderr, "failed to stat %s\n", fullpath);
1092                         continue;
1093                 }
1094                 if (S_ISLNK(st.st_mode))
1095                         continue;
1096                 if (S_ISDIR(st.st_mode)) {
1097                         struct pending_dir *next = malloc(sizeof(*next));
1098                         if (!next) {
1099                                 ret = -ENOMEM;
1100                                 goto fail;
1101                         }
1102                         strcpy(next->name, fullpath);
1103                         list_add_tail(&next->list, &pending_list);
1104                 }
1105                 if (!S_ISBLK(st.st_mode)) {
1106                         continue;
1107                 }
1108                 fd = open(fullpath, O_RDONLY);
1109                 if (fd < 0) {
1110                         /* ignore the following errors:
1111                                 ENXIO (device don't exists) 
1112                                 ENOMEDIUM (No medium found -> 
1113                                         like a cd tray empty)
1114                         */
1115                         if(errno != ENXIO && errno != ENOMEDIUM) 
1116                                 fprintf(stderr, "failed to read %s: %s\n", 
1117                                         fullpath, strerror(errno));
1118                         continue;
1119                 }
1120                 ret = btrfs_scan_one_device(fd, fullpath, &tmp_devices,
1121                                             &num_devices,
1122                                             BTRFS_SUPER_INFO_OFFSET);
1123                 if (ret == 0 && run_ioctl > 0) {
1124                         btrfs_register_one_device(fullpath);
1125                 }
1126                 close(fd);
1127         }
1128         if (!list_empty(&pending_list)) {
1129                 free(pending);
1130                 pending = list_entry(pending_list.next, struct pending_dir,
1131                                      list);
1132                 free(fullpath);
1133                 list_del(&pending->list);
1134                 closedir(dirp);
1135                 dirp = NULL;
1136                 goto again;
1137         }
1138         ret = 0;
1139 fail:
1140         free(pending);
1141         free(fullpath);
1142         if (dirp)
1143                 closedir(dirp);
1144         return ret;
1145 }
1146
1147 int btrfs_scan_for_fsid(struct btrfs_fs_devices *fs_devices, u64 total_devs,
1148                         int run_ioctls)
1149 {
1150         int ret;
1151
1152         ret = btrfs_scan_block_devices(run_ioctls);
1153         if (ret)
1154                 ret = btrfs_scan_one_dir("/dev", run_ioctls);
1155         return ret;
1156 }
1157
1158 int btrfs_device_already_in_root(struct btrfs_root *root, int fd,
1159                                  int super_offset)
1160 {
1161         struct btrfs_super_block *disk_super;
1162         char *buf;
1163         int ret = 0;
1164
1165         buf = malloc(BTRFS_SUPER_INFO_SIZE);
1166         if (!buf) {
1167                 ret = -ENOMEM;
1168                 goto out;
1169         }
1170         ret = pread(fd, buf, BTRFS_SUPER_INFO_SIZE, super_offset);
1171         if (ret != BTRFS_SUPER_INFO_SIZE)
1172                 goto brelse;
1173
1174         ret = 0;
1175         disk_super = (struct btrfs_super_block *)buf;
1176         if (disk_super->magic != cpu_to_le64(BTRFS_MAGIC))
1177                 goto brelse;
1178
1179         if (!memcmp(disk_super->fsid, root->fs_info->super_copy->fsid,
1180                     BTRFS_FSID_SIZE))
1181                 ret = 1;
1182 brelse:
1183         free(buf);
1184 out:
1185         return ret;
1186 }
1187
1188 static char *size_strs[] = { "", "KB", "MB", "GB", "TB",
1189                             "PB", "EB", "ZB", "YB"};
1190 char *pretty_sizes(u64 size)
1191 {
1192         int num_divs = 0;
1193         int pretty_len = 16;
1194         float fraction;
1195         char *pretty;
1196
1197         if( size < 1024 ){
1198                 fraction = size;
1199                 num_divs = 0;
1200         } else {
1201                 u64 last_size = size;
1202                 num_divs = 0;
1203                 while(size >= 1024){
1204                         last_size = size;
1205                         size /= 1024;
1206                         num_divs ++;
1207                 }
1208
1209                 if (num_divs >= ARRAY_SIZE(size_strs))
1210                         return NULL;
1211                 fraction = (float)last_size / 1024;
1212         }
1213         pretty = malloc(pretty_len);
1214         snprintf(pretty, pretty_len, "%.2f%s", fraction, size_strs[num_divs]);
1215         return pretty;
1216 }
1217
1218 /*
1219  * __strncpy__null - strncpy with null termination
1220  * @dest:       the target array
1221  * @src:        the source string
1222  * @n:          maximum bytes to copy (size of *dest)
1223  *
1224  * Like strncpy, but ensures destination is null-terminated.
1225  *
1226  * Copies the string pointed to by src, including the terminating null
1227  * byte ('\0'), to the buffer pointed to by dest, up to a maximum
1228  * of n bytes.  Then ensure that dest is null-terminated.
1229  */
1230 char *__strncpy__null(char *dest, const char *src, size_t n)
1231 {
1232         strncpy(dest, src, n);
1233         if (n > 0)
1234                 dest[n - 1] = '\0';
1235         return dest;
1236 }
1237
1238 /*
1239  * Checks to make sure that the label matches our requirements.
1240  * Returns:
1241        0    if everything is safe and usable
1242       -1    if the label is too long
1243  */
1244 static int check_label(const char *input)
1245 {
1246        int len = strlen(input);
1247
1248        if (len > BTRFS_LABEL_SIZE - 1) {
1249                 fprintf(stderr, "ERROR: Label %s is too long (max %d)\n",
1250                         input, BTRFS_LABEL_SIZE - 1);
1251                return -1;
1252        }
1253
1254        return 0;
1255 }
1256
1257 static int set_label_unmounted(const char *dev, const char *label)
1258 {
1259         struct btrfs_trans_handle *trans;
1260         struct btrfs_root *root;
1261         int ret;
1262
1263         ret = check_mounted(dev);
1264         if (ret < 0) {
1265                fprintf(stderr, "FATAL: error checking %s mount status\n", dev);
1266                return -1;
1267         }
1268         if (ret > 0) {
1269                 fprintf(stderr, "ERROR: dev %s is mounted, use mount point\n",
1270                         dev);
1271                 return -1;
1272         }
1273
1274         /* Open the super_block at the default location
1275          * and as read-write.
1276          */
1277         root = open_ctree(dev, 0, 1);
1278         if (!root) /* errors are printed by open_ctree() */
1279                 return -1;
1280
1281         trans = btrfs_start_transaction(root, 1);
1282         snprintf(root->fs_info->super_copy->label, BTRFS_LABEL_SIZE, "%s",
1283                  label);
1284         btrfs_commit_transaction(trans, root);
1285
1286         /* Now we close it since we are done. */
1287         close_ctree(root);
1288         return 0;
1289 }
1290
1291 static int set_label_mounted(const char *mount_path, const char *label)
1292 {
1293         int fd;
1294
1295         fd = open(mount_path, O_RDONLY | O_NOATIME);
1296         if (fd < 0) {
1297                 fprintf(stderr, "ERROR: unable access to '%s'\n", mount_path);
1298                 return -1;
1299         }
1300
1301         if (ioctl(fd, BTRFS_IOC_SET_FSLABEL, label) < 0) {
1302                 fprintf(stderr, "ERROR: unable to set label %s\n",
1303                         strerror(errno));
1304                 close(fd);
1305                 return -1;
1306         }
1307
1308         close(fd);
1309         return 0;
1310 }
1311
1312 static int get_label_unmounted(const char *dev)
1313 {
1314         struct btrfs_root *root;
1315         int ret;
1316
1317         ret = check_mounted(dev);
1318         if (ret < 0) {
1319                fprintf(stderr, "FATAL: error checking %s mount status\n", dev);
1320                return -1;
1321         }
1322         if (ret > 0) {
1323                 fprintf(stderr, "ERROR: dev %s is mounted, use mount point\n",
1324                         dev);
1325                 return -1;
1326         }
1327
1328         /* Open the super_block at the default location
1329          * and as read-only.
1330          */
1331         root = open_ctree(dev, 0, 0);
1332         if(!root)
1333                 return -1;
1334
1335         fprintf(stdout, "%s\n", root->fs_info->super_copy->label);
1336
1337         /* Now we close it since we are done. */
1338         close_ctree(root);
1339         return 0;
1340 }
1341
1342 /*
1343  * If a partition is mounted, try to get the filesystem label via its
1344  * mounted path rather than device.  Return the corresponding error
1345  * the user specified the device path.
1346  */
1347 static int get_label_mounted(const char *mount_path)
1348 {
1349         char label[BTRFS_LABEL_SIZE];
1350         int fd;
1351
1352         fd = open(mount_path, O_RDONLY | O_NOATIME);
1353         if (fd < 0) {
1354                 fprintf(stderr, "ERROR: unable access to '%s'\n", mount_path);
1355                 return -1;
1356         }
1357
1358         memset(label, '\0', sizeof(label));
1359         if (ioctl(fd, BTRFS_IOC_GET_FSLABEL, label) < 0) {
1360                 fprintf(stderr, "ERROR: unable get label %s\n", strerror(errno));
1361                 close(fd);
1362                 return -1;
1363         }
1364
1365         fprintf(stdout, "%s\n", label);
1366         close(fd);
1367         return 0;
1368 }
1369
1370 int get_label(const char *btrfs_dev)
1371 {
1372         return is_existing_blk_or_reg_file(btrfs_dev) ?
1373                 get_label_unmounted(btrfs_dev) :
1374                 get_label_mounted(btrfs_dev);
1375 }
1376
1377 int set_label(const char *btrfs_dev, const char *label)
1378 {
1379         if (check_label(label))
1380                 return -1;
1381
1382         return is_existing_blk_or_reg_file(btrfs_dev) ?
1383                 set_label_unmounted(btrfs_dev, label) :
1384                 set_label_mounted(btrfs_dev, label);
1385 }
1386
1387 int btrfs_scan_block_devices(int run_ioctl)
1388 {
1389
1390         struct stat st;
1391         int ret;
1392         int fd;
1393         struct btrfs_fs_devices *tmp_devices;
1394         u64 num_devices;
1395         FILE *proc_partitions;
1396         int i;
1397         char buf[1024];
1398         char fullpath[110];
1399         int scans = 0;
1400         int special;
1401
1402 scan_again:
1403         proc_partitions = fopen("/proc/partitions","r");
1404         if (!proc_partitions) {
1405                 fprintf(stderr, "Unable to open '/proc/partitions' for scanning\n");
1406                 return -ENOENT;
1407         }
1408         /* skip the header */
1409         for (i = 0; i < 2; i++)
1410                 if (!fgets(buf, 1023, proc_partitions)) {
1411                         fprintf(stderr,
1412                                 "Unable to read '/proc/partitions' for scanning\n");
1413                         fclose(proc_partitions);
1414                         return -ENOENT;
1415                 }
1416
1417         strcpy(fullpath,"/dev/");
1418         while(fgets(buf, 1023, proc_partitions)) {
1419                 i = sscanf(buf," %*d %*d %*d %99s", fullpath+5);
1420
1421                 /*
1422                  * multipath and MD devices may register as a btrfs filesystem
1423                  * both through the original block device and through
1424                  * the special (/dev/mapper or /dev/mdX) entry.
1425                  * This scans the special entries last
1426                  */
1427                 special = strncmp(fullpath, "/dev/dm-", strlen("/dev/dm-")) == 0;
1428                 if (!special)
1429                         special = strncmp(fullpath, "/dev/md", strlen("/dev/md")) == 0;
1430
1431                 if (scans == 0 && special)
1432                         continue;
1433                 if (scans > 0 && !special)
1434                         continue;
1435
1436                 ret = lstat(fullpath, &st);
1437                 if (ret < 0) {
1438                         fprintf(stderr, "failed to stat %s\n", fullpath);
1439                         continue;
1440                 }
1441                 if (!S_ISBLK(st.st_mode)) {
1442                         continue;
1443                 }
1444
1445                 fd = open(fullpath, O_RDONLY);
1446                 if (fd < 0) {
1447                         fprintf(stderr, "failed to open %s: %s\n",
1448                                 fullpath, strerror(errno));
1449                         continue;
1450                 }
1451                 ret = btrfs_scan_one_device(fd, fullpath, &tmp_devices,
1452                                             &num_devices,
1453                                             BTRFS_SUPER_INFO_OFFSET);
1454                 if (ret == 0 && run_ioctl > 0) {
1455                         btrfs_register_one_device(fullpath);
1456                 }
1457                 close(fd);
1458         }
1459
1460         fclose(proc_partitions);
1461
1462         if (scans == 0) {
1463                 scans++;
1464                 goto scan_again;
1465         }
1466         return 0;
1467 }
1468
1469 u64 parse_size(char *s)
1470 {
1471         int i;
1472         char c;
1473         u64 mult = 1;
1474
1475         for (i = 0; s && s[i] && isdigit(s[i]); i++) ;
1476         if (!i) {
1477                 fprintf(stderr, "ERROR: size value is empty\n");
1478                 exit(50);
1479         }
1480
1481         if (s[i]) {
1482                 c = tolower(s[i]);
1483                 switch (c) {
1484                 case 'e':
1485                         mult *= 1024;
1486                 case 'p':
1487                         mult *= 1024;
1488                 case 't':
1489                         mult *= 1024;
1490                 case 'g':
1491                         mult *= 1024;
1492                 case 'm':
1493                         mult *= 1024;
1494                 case 'k':
1495                         mult *= 1024;
1496                 case 'b':
1497                         break;
1498                 default:
1499                         fprintf(stderr, "ERROR: Unknown size descriptor "
1500                                 "'%c'\n", c);
1501                         exit(1);
1502                 }
1503         }
1504         if (s[i] && s[i+1]) {
1505                 fprintf(stderr, "ERROR: Illegal suffix contains "
1506                         "character '%c' in wrong position\n",
1507                         s[i+1]);
1508                 exit(51);
1509         }
1510         return strtoull(s, NULL, 10) * mult;
1511 }
1512
1513 int open_file_or_dir(const char *fname)
1514 {
1515         int ret;
1516         struct stat st;
1517         DIR *dirstream;
1518         int fd;
1519
1520         ret = stat(fname, &st);
1521         if (ret < 0) {
1522                 return -1;
1523         }
1524         if (S_ISDIR(st.st_mode)) {
1525                 dirstream = opendir(fname);
1526                 if (!dirstream) {
1527                         return -2;
1528                 }
1529                 fd = dirfd(dirstream);
1530         } else {
1531                 fd = open(fname, O_RDWR);
1532         }
1533         if (fd < 0) {
1534                 return -3;
1535         }
1536         return fd;
1537 }
1538
1539 int get_device_info(int fd, u64 devid,
1540                     struct btrfs_ioctl_dev_info_args *di_args)
1541 {
1542         int ret;
1543
1544         di_args->devid = devid;
1545         memset(&di_args->uuid, '\0', sizeof(di_args->uuid));
1546
1547         ret = ioctl(fd, BTRFS_IOC_DEV_INFO, di_args);
1548         return ret ? -errno : 0;
1549 }
1550
1551 /*
1552  * For a given path, fill in the ioctl fs_ and info_ args.
1553  * If the path is a btrfs mountpoint, fill info for all devices.
1554  * If the path is a btrfs device, fill in only that device.
1555  *
1556  * The path provided must be either on a mounted btrfs fs,
1557  * or be a mounted btrfs device.
1558  *
1559  * Returns 0 on success, or a negative errno.
1560  */
1561 int get_fs_info(char *path, struct btrfs_ioctl_fs_info_args *fi_args,
1562                 struct btrfs_ioctl_dev_info_args **di_ret)
1563 {
1564         int fd = -1;
1565         int ret = 0;
1566         int ndevs = 0;
1567         int i = 1;
1568         struct btrfs_fs_devices *fs_devices_mnt = NULL;
1569         struct btrfs_ioctl_dev_info_args *di_args;
1570         char mp[BTRFS_PATH_NAME_MAX + 1];
1571
1572         memset(fi_args, 0, sizeof(*fi_args));
1573
1574         if (is_block_device(path)) {
1575                 /* Ensure it's mounted, then set path to the mountpoint */
1576                 fd = open(path, O_RDONLY);
1577                 if (fd < 0) {
1578                         ret = -errno;
1579                         fprintf(stderr, "Couldn't open %s: %s\n",
1580                                 path, strerror(errno));
1581                         goto out;
1582                 }
1583                 ret = check_mounted_where(fd, path, mp, sizeof(mp),
1584                                           &fs_devices_mnt);
1585                 if (!ret) {
1586                         ret = -EINVAL;
1587                         goto out;
1588                 }
1589                 if (ret < 0)
1590                         goto out;
1591                 path = mp;
1592                 /* Only fill in this one device */
1593                 fi_args->num_devices = 1;
1594                 fi_args->max_id = fs_devices_mnt->latest_devid;
1595                 i = fs_devices_mnt->latest_devid;
1596                 memcpy(fi_args->fsid, fs_devices_mnt->fsid, BTRFS_FSID_SIZE);
1597                 close(fd);
1598         }
1599
1600         /* at this point path must not be for a block device */
1601         fd = open_file_or_dir(path);
1602         if (fd < 0) {
1603                 ret = -errno;
1604                 goto out;
1605         }
1606
1607         /* fill in fi_args if not just a single device */
1608         if (fi_args->num_devices != 1) {
1609                 ret = ioctl(fd, BTRFS_IOC_FS_INFO, fi_args);
1610                 if (ret < 0) {
1611                         ret = -errno;
1612                         goto out;
1613                 }
1614         }
1615
1616         if (!fi_args->num_devices)
1617                 goto out;
1618
1619         di_args = *di_ret = malloc(fi_args->num_devices * sizeof(*di_args));
1620         if (!di_args) {
1621                 ret = -errno;
1622                 goto out;
1623         }
1624
1625         for (; i <= fi_args->max_id; ++i) {
1626                 BUG_ON(ndevs >= fi_args->num_devices);
1627                 ret = get_device_info(fd, i, &di_args[ndevs]);
1628                 if (ret == -ENODEV)
1629                         continue;
1630                 if (ret)
1631                         goto out;
1632                 ndevs++;
1633         }
1634
1635         BUG_ON(ndevs == 0);
1636         ret = 0;
1637 out:
1638         if (fd != -1)
1639                 close(fd);
1640         return ret;
1641 }
1642
1643 #define isoctal(c)      (((c) & ~7) == '0')
1644
1645 static inline void translate(char *f, char *t)
1646 {
1647         while (*f != '\0') {
1648                 if (*f == '\\' &&
1649                     isoctal(f[1]) && isoctal(f[2]) && isoctal(f[3])) {
1650                         *t++ = 64*(f[1] & 7) + 8*(f[2] & 7) + (f[3] & 7);
1651                         f += 4;
1652                 } else
1653                         *t++ = *f++;
1654         }
1655         *t = '\0';
1656         return;
1657 }
1658
1659 /*
1660  * Checks if the swap device.
1661  * Returns 1 if swap device, < 0 on error or 0 if not swap device.
1662  */
1663 int is_swap_device(const char *file)
1664 {
1665         FILE    *f;
1666         struct stat     st_buf;
1667         dev_t   dev;
1668         ino_t   ino = 0;
1669         char    tmp[PATH_MAX];
1670         char    buf[PATH_MAX];
1671         char    *cp;
1672         int     ret = 0;
1673
1674         if (stat(file, &st_buf) < 0)
1675                 return -errno;
1676         if (S_ISBLK(st_buf.st_mode))
1677                 dev = st_buf.st_rdev;
1678         else if (S_ISREG(st_buf.st_mode)) {
1679                 dev = st_buf.st_dev;
1680                 ino = st_buf.st_ino;
1681         } else
1682                 return 0;
1683
1684         if ((f = fopen("/proc/swaps", "r")) == NULL)
1685                 return 0;
1686
1687         /* skip the first line */
1688         if (fgets(tmp, sizeof(tmp), f) == NULL)
1689                 goto out;
1690
1691         while (fgets(tmp, sizeof(tmp), f) != NULL) {
1692                 if ((cp = strchr(tmp, ' ')) != NULL)
1693                         *cp = '\0';
1694                 if ((cp = strchr(tmp, '\t')) != NULL)
1695                         *cp = '\0';
1696                 translate(tmp, buf);
1697                 if (stat(buf, &st_buf) != 0)
1698                         continue;
1699                 if (S_ISBLK(st_buf.st_mode)) {
1700                         if (dev == st_buf.st_rdev) {
1701                                 ret = 1;
1702                                 break;
1703                         }
1704                 } else if (S_ISREG(st_buf.st_mode)) {
1705                         if (dev == st_buf.st_dev && ino == st_buf.st_ino) {
1706                                 ret = 1;
1707                                 break;
1708                         }
1709                 }
1710         }
1711
1712 out:
1713         fclose(f);
1714
1715         return ret;
1716 }