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