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