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