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