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