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