btrfs-progs: add nodiscard option to device add
[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, (unsigned long)
140                             btrfs_header_fsid(buf), 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(buf, nritems), itemoff);
168         btrfs_set_item_size(buf, btrfs_item_nr(buf, 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(buf, nritems), itemoff);
179         btrfs_set_item_size(buf, btrfs_item_nr(buf, 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(buf, nritems), itemoff);
191         btrfs_set_item_size(buf, btrfs_item_nr(buf, 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(buf, nritems), itemoff);
203         btrfs_set_item_size(buf, btrfs_item_nr(buf, 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(buf, nritems),
245                                       itemoff);
246                 btrfs_set_item_size(buf, btrfs_item_nr(buf, 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(buf, nritems),
263                                       itemoff);
264                 btrfs_set_item_size(buf, btrfs_item_nr(buf, 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(buf, nritems), itemoff);
290         btrfs_set_item_size(buf, btrfs_item_nr(buf, 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(buf, nritems), itemoff);
322         btrfs_set_item_size(buf, btrfs_item_nr(buf,  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(buf, nritems), itemoff);
376         btrfs_set_item_size(buf, btrfs_item_nr(buf,  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                 fprintf(stderr, "Performing full device TRIM (%s) ...\n",
601                                 pretty_size(block_count));
602                 /*
603                  * We intentionally ignore errors from the discard ioctl.  It is
604                  * not necessary for the mkfs functionality but just an optimization.
605                  */
606                 discard_blocks(fd, 0, block_count);
607         }
608
609         ret = zero_dev_start(fd);
610         if (ret) {
611                 fprintf(stderr, "failed to zero device start %d\n", ret);
612                 exit(1);
613         }
614
615         for (i = 0 ; i < BTRFS_SUPER_MIRROR_MAX; i++) {
616                 bytenr = btrfs_sb_offset(i);
617                 if (bytenr >= block_count)
618                         break;
619                 zero_blocks(fd, bytenr, BTRFS_SUPER_INFO_SIZE);
620         }
621
622         if (zero_end) {
623                 ret = zero_dev_end(fd, block_count);
624                 if (ret) {
625                         fprintf(stderr, "failed to zero device end %d\n", ret);
626                         exit(1);
627                 }
628         }
629         *block_count_ret = block_count;
630         return 0;
631 }
632
633 int btrfs_make_root_dir(struct btrfs_trans_handle *trans,
634                         struct btrfs_root *root, u64 objectid)
635 {
636         int ret;
637         struct btrfs_inode_item inode_item;
638         time_t now = time(NULL);
639
640         memset(&inode_item, 0, sizeof(inode_item));
641         btrfs_set_stack_inode_generation(&inode_item, trans->transid);
642         btrfs_set_stack_inode_size(&inode_item, 0);
643         btrfs_set_stack_inode_nlink(&inode_item, 1);
644         btrfs_set_stack_inode_nbytes(&inode_item, root->leafsize);
645         btrfs_set_stack_inode_mode(&inode_item, S_IFDIR | 0755);
646         btrfs_set_stack_timespec_sec(&inode_item.atime, now);
647         btrfs_set_stack_timespec_nsec(&inode_item.atime, 0);
648         btrfs_set_stack_timespec_sec(&inode_item.ctime, now);
649         btrfs_set_stack_timespec_nsec(&inode_item.ctime, 0);
650         btrfs_set_stack_timespec_sec(&inode_item.mtime, now);
651         btrfs_set_stack_timespec_nsec(&inode_item.mtime, 0);
652         btrfs_set_stack_timespec_sec(&inode_item.otime, 0);
653         btrfs_set_stack_timespec_nsec(&inode_item.otime, 0);
654
655         if (root->fs_info->tree_root == root)
656                 btrfs_set_super_root_dir(root->fs_info->super_copy, objectid);
657
658         ret = btrfs_insert_inode(trans, root, objectid, &inode_item);
659         if (ret)
660                 goto error;
661
662         ret = btrfs_insert_inode_ref(trans, root, "..", 2, objectid, objectid, 0);
663         if (ret)
664                 goto error;
665
666         btrfs_set_root_dirid(&root->root_item, objectid);
667         ret = 0;
668 error:
669         return ret;
670 }
671
672 /*
673  * checks if a path is a block device node
674  * Returns negative errno on failure, otherwise
675  * returns 1 for blockdev, 0 for not-blockdev
676  */
677 int is_block_device(const char *path) {
678         struct stat statbuf;
679
680         if (stat(path, &statbuf) < 0)
681                 return -errno;
682
683         return S_ISBLK(statbuf.st_mode);
684 }
685
686 /*
687  * Find the mount point for a mounted device.
688  * On success, returns 0 with mountpoint in *mp.
689  * On failure, returns -errno (not mounted yields -EINVAL)
690  * Is noisy on failures, expects to be given a mounted device.
691  */
692 static int get_btrfs_mount(const char *dev, char *mp, size_t mp_size) {
693         int ret;
694         int fd = -1;
695
696         ret = is_block_device(dev);
697         if (ret <= 0) {
698                 if (!ret) {
699                         fprintf(stderr, "%s is not a block device\n", dev);
700                         ret = -EINVAL;
701                 } else {
702                         fprintf(stderr, "Could not check %s: %s\n",
703                                 dev, strerror(-ret));
704                 }
705                 goto out;
706         }
707
708         fd = open(dev, O_RDONLY);
709         if (fd < 0) {
710                 ret = -errno;
711                 fprintf(stderr, "Could not open %s: %s\n", dev, strerror(errno));
712                 goto out;
713         }
714
715         ret = check_mounted_where(fd, dev, mp, mp_size, NULL);
716         if (!ret) {
717                 fprintf(stderr, "%s is not a mounted btrfs device\n", dev);
718                 ret = -EINVAL;
719         } else { /* mounted, all good */
720                 ret = 0;
721         }
722 out:
723         if (fd != -1)
724                 close(fd);
725         if (ret)
726                 fprintf(stderr, "Could not get mountpoint for %s\n", dev);
727         return ret;
728 }
729
730 /*
731  * Given a pathname, return a filehandle to:
732  *      the original pathname or,
733  *      if the pathname is a mounted btrfs device, to its mountpoint.
734  *
735  * On error, return -1, errno should be set.
736  */
737 int open_path_or_dev_mnt(const char *path, DIR **dirstream)
738 {
739         char mp[BTRFS_PATH_NAME_MAX + 1];
740         int fdmnt;
741
742         if (is_block_device(path)) {
743                 int ret;
744
745                 ret = get_btrfs_mount(path, mp, sizeof(mp));
746                 if (ret < 0) {
747                         /* not a mounted btrfs dev */
748                         errno = EINVAL;
749                         return -1;
750                 }
751                 fdmnt = open_file_or_dir(mp, dirstream);
752         } else {
753                 fdmnt = open_file_or_dir(path, dirstream);
754         }
755
756         return fdmnt;
757 }
758
759 /* checks if a device is a loop device */
760 static int is_loop_device (const char* device) {
761         struct stat statbuf;
762
763         if(stat(device, &statbuf) < 0)
764                 return -errno;
765
766         return (S_ISBLK(statbuf.st_mode) &&
767                 MAJOR(statbuf.st_rdev) == LOOP_MAJOR);
768 }
769
770
771 /* Takes a loop device path (e.g. /dev/loop0) and returns
772  * the associated file (e.g. /images/my_btrfs.img) */
773 static int resolve_loop_device(const char* loop_dev, char* loop_file,
774                 int max_len)
775 {
776         int ret;
777         FILE *f;
778         char fmt[20];
779         char p[PATH_MAX];
780         char real_loop_dev[PATH_MAX];
781
782         if (!realpath(loop_dev, real_loop_dev))
783                 return -errno;
784         snprintf(p, PATH_MAX, "/sys/block/%s/loop/backing_file", strrchr(real_loop_dev, '/'));
785         if (!(f = fopen(p, "r")))
786                 return -errno;
787
788         snprintf(fmt, 20, "%%%i[^\n]", max_len-1);
789         ret = fscanf(f, fmt, loop_file);
790         fclose(f);
791         if (ret == EOF)
792                 return -errno;
793
794         return 0;
795 }
796
797 /* Checks whether a and b are identical or device
798  * files associated with the same block device
799  */
800 static int is_same_blk_file(const char* a, const char* b)
801 {
802         struct stat st_buf_a, st_buf_b;
803         char real_a[PATH_MAX];
804         char real_b[PATH_MAX];
805
806         if(!realpath(a, real_a) ||
807            !realpath(b, real_b))
808         {
809                 return -errno;
810         }
811
812         /* Identical path? */
813         if(strcmp(real_a, real_b) == 0)
814                 return 1;
815
816         if(stat(a, &st_buf_a) < 0 ||
817            stat(b, &st_buf_b) < 0)
818         {
819                 if (errno == ENOENT)
820                         return 0;
821                 return -errno;
822         }
823
824         /* Same blockdevice? */
825         if(S_ISBLK(st_buf_a.st_mode) &&
826            S_ISBLK(st_buf_b.st_mode) &&
827            st_buf_a.st_rdev == st_buf_b.st_rdev)
828         {
829                 return 1;
830         }
831
832         /* Hardlink? */
833         if (st_buf_a.st_dev == st_buf_b.st_dev &&
834             st_buf_a.st_ino == st_buf_b.st_ino)
835         {
836                 return 1;
837         }
838
839         return 0;
840 }
841
842 /* checks if a and b are identical or device
843  * files associated with the same block device or
844  * if one file is a loop device that uses the other
845  * file.
846  */
847 static int is_same_loop_file(const char* a, const char* b)
848 {
849         char res_a[PATH_MAX];
850         char res_b[PATH_MAX];
851         const char* final_a;
852         const char* final_b;
853         int ret;
854
855         /* Resolve a if it is a loop device */
856         if((ret = is_loop_device(a)) < 0) {
857                 if (ret == -ENOENT)
858                         return 0;
859                 return ret;
860         } else if (ret) {
861                 if ((ret = resolve_loop_device(a, res_a, sizeof(res_a))) < 0)
862                         return ret;
863
864                 final_a = res_a;
865         } else {
866                 final_a = a;
867         }
868
869         /* Resolve b if it is a loop device */
870         if ((ret = is_loop_device(b)) < 0) {
871                 if (ret == -ENOENT)
872                         return 0;
873                 return ret;
874         } else if (ret) {
875                 if((ret = resolve_loop_device(b, res_b, sizeof(res_b))) < 0)
876                         return ret;
877
878                 final_b = res_b;
879         } else {
880                 final_b = b;
881         }
882
883         return is_same_blk_file(final_a, final_b);
884 }
885
886 /* Checks if a file exists and is a block or regular file*/
887 static int is_existing_blk_or_reg_file(const char* filename)
888 {
889         struct stat st_buf;
890
891         if(stat(filename, &st_buf) < 0) {
892                 if(errno == ENOENT)
893                         return 0;
894                 else
895                         return -errno;
896         }
897
898         return (S_ISBLK(st_buf.st_mode) || S_ISREG(st_buf.st_mode));
899 }
900
901 /* Checks if a file is used (directly or indirectly via a loop device)
902  * by a device in fs_devices
903  */
904 static int blk_file_in_dev_list(struct btrfs_fs_devices* fs_devices,
905                 const char* file)
906 {
907         int ret;
908         struct list_head *head;
909         struct list_head *cur;
910         struct btrfs_device *device;
911
912         head = &fs_devices->devices;
913         list_for_each(cur, head) {
914                 device = list_entry(cur, struct btrfs_device, dev_list);
915
916                 if((ret = is_same_loop_file(device->name, file)))
917                         return ret;
918         }
919
920         return 0;
921 }
922
923 /*
924  * returns 1 if the device was mounted, < 0 on error or 0 if everything
925  * is safe to continue.
926  */
927 int check_mounted(const char* file)
928 {
929         int fd;
930         int ret;
931
932         fd = open(file, O_RDONLY);
933         if (fd < 0) {
934                 fprintf (stderr, "check_mounted(): Could not open %s\n", file);
935                 return -errno;
936         }
937
938         ret =  check_mounted_where(fd, file, NULL, 0, NULL);
939         close(fd);
940
941         return ret;
942 }
943
944 int check_mounted_where(int fd, const char *file, char *where, int size,
945                         struct btrfs_fs_devices **fs_dev_ret)
946 {
947         int ret;
948         u64 total_devs = 1;
949         int is_btrfs;
950         struct btrfs_fs_devices *fs_devices_mnt = NULL;
951         FILE *f;
952         struct mntent *mnt;
953
954         /* scan the initial device */
955         ret = btrfs_scan_one_device(fd, file, &fs_devices_mnt,
956                                     &total_devs, BTRFS_SUPER_INFO_OFFSET);
957         is_btrfs = (ret >= 0);
958
959         /* scan other devices */
960         if (is_btrfs && total_devs > 1) {
961                 if((ret = btrfs_scan_for_fsid(1)))
962                         return ret;
963         }
964
965         /* iterate over the list of currently mountes filesystems */
966         if ((f = setmntent ("/proc/mounts", "r")) == NULL)
967                 return -errno;
968
969         while ((mnt = getmntent (f)) != NULL) {
970                 if(is_btrfs) {
971                         if(strcmp(mnt->mnt_type, "btrfs") != 0)
972                                 continue;
973
974                         ret = blk_file_in_dev_list(fs_devices_mnt, mnt->mnt_fsname);
975                 } else {
976                         /* ignore entries in the mount table that are not
977                            associated with a file*/
978                         if((ret = is_existing_blk_or_reg_file(mnt->mnt_fsname)) < 0)
979                                 goto out_mntloop_err;
980                         else if(!ret)
981                                 continue;
982
983                         ret = is_same_loop_file(file, mnt->mnt_fsname);
984                 }
985
986                 if(ret < 0)
987                         goto out_mntloop_err;
988                 else if(ret)
989                         break;
990         }
991
992         /* Did we find an entry in mnt table? */
993         if (mnt && size && where) {
994                 strncpy(where, mnt->mnt_dir, size);
995                 where[size-1] = 0;
996         }
997         if (fs_dev_ret)
998                 *fs_dev_ret = fs_devices_mnt;
999
1000         ret = (mnt != NULL);
1001
1002 out_mntloop_err:
1003         endmntent (f);
1004
1005         return ret;
1006 }
1007
1008 struct pending_dir {
1009         struct list_head list;
1010         char name[PATH_MAX];
1011 };
1012
1013 void btrfs_register_one_device(char *fname)
1014 {
1015         struct btrfs_ioctl_vol_args args;
1016         int fd;
1017         int ret;
1018         int e;
1019
1020         fd = open("/dev/btrfs-control", O_RDONLY);
1021         if (fd < 0) {
1022                 fprintf(stderr, "failed to open /dev/btrfs-control "
1023                         "skipping device registration: %s\n",
1024                         strerror(errno));
1025                 return;
1026         }
1027         strncpy(args.name, fname, BTRFS_PATH_NAME_MAX);
1028         args.name[BTRFS_PATH_NAME_MAX-1] = 0;
1029         ret = ioctl(fd, BTRFS_IOC_SCAN_DEV, &args);
1030         e = errno;
1031         if(ret<0){
1032                 fprintf(stderr, "ERROR: device scan failed '%s' - %s\n",
1033                         fname, strerror(e));
1034         }
1035         close(fd);
1036 }
1037
1038 int btrfs_scan_one_dir(char *dirname, int run_ioctl)
1039 {
1040         DIR *dirp = NULL;
1041         struct dirent *dirent;
1042         struct pending_dir *pending;
1043         struct stat st;
1044         int ret;
1045         int fd;
1046         int dirname_len;
1047         char *fullpath;
1048         struct list_head pending_list;
1049         struct btrfs_fs_devices *tmp_devices;
1050         u64 num_devices;
1051
1052         INIT_LIST_HEAD(&pending_list);
1053
1054         pending = malloc(sizeof(*pending));
1055         if (!pending)
1056                 return -ENOMEM;
1057         strcpy(pending->name, dirname);
1058
1059 again:
1060         dirname_len = strlen(pending->name);
1061         fullpath = malloc(PATH_MAX);
1062         dirname = pending->name;
1063
1064         if (!fullpath) {
1065                 ret = -ENOMEM;
1066                 goto fail;
1067         }
1068         dirp = opendir(dirname);
1069         if (!dirp) {
1070                 fprintf(stderr, "Unable to open %s for scanning\n", dirname);
1071                 ret = -ENOENT;
1072                 goto fail;
1073         }
1074         while(1) {
1075                 dirent = readdir(dirp);
1076                 if (!dirent)
1077                         break;
1078                 if (dirent->d_name[0] == '.')
1079                         continue;
1080                 if (dirname_len + strlen(dirent->d_name) + 2 > PATH_MAX) {
1081                         ret = -EFAULT;
1082                         goto fail;
1083                 }
1084                 snprintf(fullpath, PATH_MAX, "%s/%s", dirname, dirent->d_name);
1085                 ret = lstat(fullpath, &st);
1086                 if (ret < 0) {
1087                         fprintf(stderr, "failed to stat %s\n", fullpath);
1088                         continue;
1089                 }
1090                 if (S_ISLNK(st.st_mode))
1091                         continue;
1092                 if (S_ISDIR(st.st_mode)) {
1093                         struct pending_dir *next = malloc(sizeof(*next));
1094                         if (!next) {
1095                                 ret = -ENOMEM;
1096                                 goto fail;
1097                         }
1098                         strcpy(next->name, fullpath);
1099                         list_add_tail(&next->list, &pending_list);
1100                 }
1101                 if (!S_ISBLK(st.st_mode)) {
1102                         continue;
1103                 }
1104                 fd = open(fullpath, O_RDONLY);
1105                 if (fd < 0) {
1106                         /* ignore the following errors:
1107                                 ENXIO (device don't exists) 
1108                                 ENOMEDIUM (No medium found -> 
1109                                         like a cd tray empty)
1110                         */
1111                         if(errno != ENXIO && errno != ENOMEDIUM) 
1112                                 fprintf(stderr, "failed to read %s: %s\n", 
1113                                         fullpath, strerror(errno));
1114                         continue;
1115                 }
1116                 ret = btrfs_scan_one_device(fd, fullpath, &tmp_devices,
1117                                             &num_devices,
1118                                             BTRFS_SUPER_INFO_OFFSET);
1119                 if (ret == 0 && run_ioctl > 0) {
1120                         btrfs_register_one_device(fullpath);
1121                 }
1122                 close(fd);
1123         }
1124         if (!list_empty(&pending_list)) {
1125                 free(pending);
1126                 pending = list_entry(pending_list.next, struct pending_dir,
1127                                      list);
1128                 free(fullpath);
1129                 list_del(&pending->list);
1130                 closedir(dirp);
1131                 dirp = NULL;
1132                 goto again;
1133         }
1134         ret = 0;
1135 fail:
1136         free(pending);
1137         free(fullpath);
1138         while (!list_empty(&pending_list)) {
1139                 pending = list_entry(pending_list.next, struct pending_dir,
1140                                      list);
1141                 list_del(&pending->list);
1142                 free(pending);
1143         }
1144         if (dirp)
1145                 closedir(dirp);
1146         return ret;
1147 }
1148
1149 int btrfs_scan_for_fsid(int run_ioctls)
1150 {
1151         int ret;
1152
1153         ret = scan_for_btrfs(BTRFS_SCAN_PROC, run_ioctls);
1154         if (ret)
1155                 ret = scan_for_btrfs(BTRFS_SCAN_DEV, run_ioctls);
1156         return ret;
1157 }
1158
1159 int btrfs_device_already_in_root(struct btrfs_root *root, int fd,
1160                                  int super_offset)
1161 {
1162         struct btrfs_super_block *disk_super;
1163         char *buf;
1164         int ret = 0;
1165
1166         buf = malloc(BTRFS_SUPER_INFO_SIZE);
1167         if (!buf) {
1168                 ret = -ENOMEM;
1169                 goto out;
1170         }
1171         ret = pread(fd, buf, BTRFS_SUPER_INFO_SIZE, super_offset);
1172         if (ret != BTRFS_SUPER_INFO_SIZE)
1173                 goto brelse;
1174
1175         ret = 0;
1176         disk_super = (struct btrfs_super_block *)buf;
1177         if (btrfs_super_magic(disk_super) != BTRFS_MAGIC)
1178                 goto brelse;
1179
1180         if (!memcmp(disk_super->fsid, root->fs_info->super_copy->fsid,
1181                     BTRFS_FSID_SIZE))
1182                 ret = 1;
1183 brelse:
1184         free(buf);
1185 out:
1186         return ret;
1187 }
1188
1189 static char *size_strs[] = { "", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"};
1190 void pretty_size_snprintf(u64 size, char *str, size_t str_bytes)
1191 {
1192         int num_divs = 0;
1193         float fraction;
1194
1195         if (str_bytes == 0)
1196                 return;
1197
1198         if( size < 1024 ){
1199                 fraction = size;
1200                 num_divs = 0;
1201         } else {
1202                 u64 last_size = size;
1203                 num_divs = 0;
1204                 while(size >= 1024){
1205                         last_size = size;
1206                         size /= 1024;
1207                         num_divs ++;
1208                 }
1209
1210                 if (num_divs >= ARRAY_SIZE(size_strs)) {
1211                         str[0] = '\0';
1212                         return;
1213                 }
1214                 fraction = (float)last_size / 1024;
1215         }
1216         snprintf(str, str_bytes, "%.2f%s", fraction, size_strs[num_divs]);
1217 }
1218
1219 /*
1220  * __strncpy__null - strncpy with null termination
1221  * @dest:       the target array
1222  * @src:        the source string
1223  * @n:          maximum bytes to copy (size of *dest)
1224  *
1225  * Like strncpy, but ensures destination is null-terminated.
1226  *
1227  * Copies the string pointed to by src, including the terminating null
1228  * byte ('\0'), to the buffer pointed to by dest, up to a maximum
1229  * of n bytes.  Then ensure that dest is null-terminated.
1230  */
1231 char *__strncpy__null(char *dest, const char *src, size_t n)
1232 {
1233         strncpy(dest, src, n);
1234         if (n > 0)
1235                 dest[n - 1] = '\0';
1236         return dest;
1237 }
1238
1239 /*
1240  * Checks to make sure that the label matches our requirements.
1241  * Returns:
1242        0    if everything is safe and usable
1243       -1    if the label is too long
1244  */
1245 static int check_label(const char *input)
1246 {
1247        int len = strlen(input);
1248
1249        if (len > BTRFS_LABEL_SIZE - 1) {
1250                 fprintf(stderr, "ERROR: Label %s is too long (max %d)\n",
1251                         input, BTRFS_LABEL_SIZE - 1);
1252                return -1;
1253        }
1254
1255        return 0;
1256 }
1257
1258 static int set_label_unmounted(const char *dev, const char *label)
1259 {
1260         struct btrfs_trans_handle *trans;
1261         struct btrfs_root *root;
1262         int ret;
1263
1264         ret = check_mounted(dev);
1265         if (ret < 0) {
1266                fprintf(stderr, "FATAL: error checking %s mount status\n", dev);
1267                return -1;
1268         }
1269         if (ret > 0) {
1270                 fprintf(stderr, "ERROR: dev %s is mounted, use mount point\n",
1271                         dev);
1272                 return -1;
1273         }
1274
1275         /* Open the super_block at the default location
1276          * and as read-write.
1277          */
1278         root = open_ctree(dev, 0, 1);
1279         if (!root) /* errors are printed by open_ctree() */
1280                 return -1;
1281
1282         trans = btrfs_start_transaction(root, 1);
1283         snprintf(root->fs_info->super_copy->label, BTRFS_LABEL_SIZE, "%s",
1284                  label);
1285         btrfs_commit_transaction(trans, root);
1286
1287         /* Now we close it since we are done. */
1288         close_ctree(root);
1289         return 0;
1290 }
1291
1292 static int set_label_mounted(const char *mount_path, const char *label)
1293 {
1294         int fd;
1295
1296         fd = open(mount_path, O_RDONLY | O_NOATIME);
1297         if (fd < 0) {
1298                 fprintf(stderr, "ERROR: unable access to '%s'\n", mount_path);
1299                 return -1;
1300         }
1301
1302         if (ioctl(fd, BTRFS_IOC_SET_FSLABEL, label) < 0) {
1303                 fprintf(stderr, "ERROR: unable to set label %s\n",
1304                         strerror(errno));
1305                 close(fd);
1306                 return -1;
1307         }
1308
1309         close(fd);
1310         return 0;
1311 }
1312
1313 static int get_label_unmounted(const char *dev)
1314 {
1315         struct btrfs_root *root;
1316         int ret;
1317
1318         ret = check_mounted(dev);
1319         if (ret < 0) {
1320                fprintf(stderr, "FATAL: error checking %s mount status\n", dev);
1321                return -1;
1322         }
1323         if (ret > 0) {
1324                 fprintf(stderr, "ERROR: dev %s is mounted, use mount point\n",
1325                         dev);
1326                 return -1;
1327         }
1328
1329         /* Open the super_block at the default location
1330          * and as read-only.
1331          */
1332         root = open_ctree(dev, 0, 0);
1333         if(!root)
1334                 return -1;
1335
1336         fprintf(stdout, "%s\n", root->fs_info->super_copy->label);
1337
1338         /* Now we close it since we are done. */
1339         close_ctree(root);
1340         return 0;
1341 }
1342
1343 /*
1344  * If a partition is mounted, try to get the filesystem label via its
1345  * mounted path rather than device.  Return the corresponding error
1346  * the user specified the device path.
1347  */
1348 int get_label_mounted(const char *mount_path, char *labelp)
1349 {
1350         char label[BTRFS_LABEL_SIZE];
1351         int fd;
1352
1353         fd = open(mount_path, O_RDONLY | O_NOATIME);
1354         if (fd < 0) {
1355                 fprintf(stderr, "ERROR: unable access to '%s'\n", mount_path);
1356                 return -1;
1357         }
1358
1359         memset(label, '\0', sizeof(label));
1360         if (ioctl(fd, BTRFS_IOC_GET_FSLABEL, label) < 0) {
1361                 fprintf(stderr, "ERROR: unable get label %s\n", strerror(errno));
1362                 close(fd);
1363                 return -1;
1364         }
1365
1366         strncpy(labelp, label, sizeof(label));
1367         close(fd);
1368         return 0;
1369 }
1370
1371 int get_label(const char *btrfs_dev)
1372 {
1373         int ret;
1374         char label[BTRFS_LABEL_SIZE];
1375
1376         if (is_existing_blk_or_reg_file(btrfs_dev))
1377                 ret = get_label_unmounted(btrfs_dev);
1378         else {
1379                 ret = get_label_mounted(btrfs_dev, label);
1380                 if (!ret)
1381                         fprintf(stdout, "%s\n", label);
1382         }
1383         return ret;
1384 }
1385
1386 int set_label(const char *btrfs_dev, const char *label)
1387 {
1388         if (check_label(label))
1389                 return -1;
1390
1391         return is_existing_blk_or_reg_file(btrfs_dev) ?
1392                 set_label_unmounted(btrfs_dev, label) :
1393                 set_label_mounted(btrfs_dev, label);
1394 }
1395
1396 int btrfs_scan_block_devices(int run_ioctl)
1397 {
1398
1399         struct stat st;
1400         int ret;
1401         int fd;
1402         struct btrfs_fs_devices *tmp_devices;
1403         u64 num_devices;
1404         FILE *proc_partitions;
1405         int i;
1406         char buf[1024];
1407         char fullpath[110];
1408         int scans = 0;
1409         int special;
1410
1411 scan_again:
1412         proc_partitions = fopen("/proc/partitions","r");
1413         if (!proc_partitions) {
1414                 fprintf(stderr, "Unable to open '/proc/partitions' for scanning\n");
1415                 return -ENOENT;
1416         }
1417         /* skip the header */
1418         for (i = 0; i < 2; i++)
1419                 if (!fgets(buf, 1023, proc_partitions)) {
1420                         fprintf(stderr,
1421                                 "Unable to read '/proc/partitions' for scanning\n");
1422                         fclose(proc_partitions);
1423                         return -ENOENT;
1424                 }
1425
1426         strcpy(fullpath,"/dev/");
1427         while(fgets(buf, 1023, proc_partitions)) {
1428                 i = sscanf(buf," %*d %*d %*d %99s", fullpath+5);
1429
1430                 /*
1431                  * multipath and MD devices may register as a btrfs filesystem
1432                  * both through the original block device and through
1433                  * the special (/dev/mapper or /dev/mdX) entry.
1434                  * This scans the special entries last
1435                  */
1436                 special = strncmp(fullpath, "/dev/dm-", strlen("/dev/dm-")) == 0;
1437                 if (!special)
1438                         special = strncmp(fullpath, "/dev/md", strlen("/dev/md")) == 0;
1439
1440                 if (scans == 0 && special)
1441                         continue;
1442                 if (scans > 0 && !special)
1443                         continue;
1444
1445                 ret = lstat(fullpath, &st);
1446                 if (ret < 0) {
1447                         fprintf(stderr, "failed to stat %s\n", fullpath);
1448                         continue;
1449                 }
1450                 if (!S_ISBLK(st.st_mode)) {
1451                         continue;
1452                 }
1453
1454                 fd = open(fullpath, O_RDONLY);
1455                 if (fd < 0) {
1456                         if (errno != ENOMEDIUM)
1457                                 fprintf(stderr, "failed to open %s: %s\n",
1458                                         fullpath, strerror(errno));
1459                         continue;
1460                 }
1461                 ret = btrfs_scan_one_device(fd, fullpath, &tmp_devices,
1462                                             &num_devices,
1463                                             BTRFS_SUPER_INFO_OFFSET);
1464                 if (ret == 0 && run_ioctl > 0) {
1465                         btrfs_register_one_device(fullpath);
1466                 }
1467                 close(fd);
1468         }
1469
1470         fclose(proc_partitions);
1471
1472         if (scans == 0) {
1473                 scans++;
1474                 goto scan_again;
1475         }
1476         return 0;
1477 }
1478
1479 u64 parse_size(char *s)
1480 {
1481         int i;
1482         char c;
1483         u64 mult = 1;
1484
1485         for (i = 0; s && s[i] && isdigit(s[i]); i++) ;
1486         if (!i) {
1487                 fprintf(stderr, "ERROR: size value is empty\n");
1488                 exit(50);
1489         }
1490
1491         if (s[i]) {
1492                 c = tolower(s[i]);
1493                 switch (c) {
1494                 case 'e':
1495                         mult *= 1024;
1496                 case 'p':
1497                         mult *= 1024;
1498                 case 't':
1499                         mult *= 1024;
1500                 case 'g':
1501                         mult *= 1024;
1502                 case 'm':
1503                         mult *= 1024;
1504                 case 'k':
1505                         mult *= 1024;
1506                 case 'b':
1507                         break;
1508                 default:
1509                         fprintf(stderr, "ERROR: Unknown size descriptor "
1510                                 "'%c'\n", c);
1511                         exit(1);
1512                 }
1513         }
1514         if (s[i] && s[i+1]) {
1515                 fprintf(stderr, "ERROR: Illegal suffix contains "
1516                         "character '%c' in wrong position\n",
1517                         s[i+1]);
1518                 exit(51);
1519         }
1520         return strtoull(s, NULL, 10) * mult;
1521 }
1522
1523 int open_file_or_dir(const char *fname, DIR **dirstream)
1524 {
1525         int ret;
1526         struct stat st;
1527         int fd;
1528
1529         ret = stat(fname, &st);
1530         if (ret < 0) {
1531                 return -1;
1532         }
1533         if (S_ISDIR(st.st_mode)) {
1534                 *dirstream = opendir(fname);
1535                 if (!*dirstream)
1536                         return -2;
1537                 fd = dirfd(*dirstream);
1538         } else {
1539                 fd = open(fname, O_RDWR);
1540         }
1541         if (fd < 0) {
1542                 fd = -3;
1543                 if (*dirstream)
1544                         closedir(*dirstream);
1545         }
1546         return fd;
1547 }
1548
1549 void close_file_or_dir(int fd, DIR *dirstream)
1550 {
1551         if (dirstream)
1552                 closedir(dirstream);
1553         else if (fd >= 0)
1554                 close(fd);
1555 }
1556
1557 static int get_device_info(int fd, u64 devid,
1558                 struct btrfs_ioctl_dev_info_args *di_args)
1559 {
1560         int ret;
1561
1562         di_args->devid = devid;
1563         memset(&di_args->uuid, '\0', sizeof(di_args->uuid));
1564
1565         ret = ioctl(fd, BTRFS_IOC_DEV_INFO, di_args);
1566         return ret ? -errno : 0;
1567 }
1568
1569 /*
1570  * For a given path, fill in the ioctl fs_ and info_ args.
1571  * If the path is a btrfs mountpoint, fill info for all devices.
1572  * If the path is a btrfs device, fill in only that device.
1573  *
1574  * The path provided must be either on a mounted btrfs fs,
1575  * or be a mounted btrfs device.
1576  *
1577  * Returns 0 on success, or a negative errno.
1578  */
1579 int get_fs_info(char *path, struct btrfs_ioctl_fs_info_args *fi_args,
1580                 struct btrfs_ioctl_dev_info_args **di_ret)
1581 {
1582         int fd = -1;
1583         int ret = 0;
1584         int ndevs = 0;
1585         int i = 1;
1586         struct btrfs_fs_devices *fs_devices_mnt = NULL;
1587         struct btrfs_ioctl_dev_info_args *di_args;
1588         char mp[BTRFS_PATH_NAME_MAX + 1];
1589         DIR *dirstream = NULL;
1590
1591         memset(fi_args, 0, sizeof(*fi_args));
1592
1593         if (is_block_device(path)) {
1594                 /* Ensure it's mounted, then set path to the mountpoint */
1595                 fd = open(path, O_RDONLY);
1596                 if (fd < 0) {
1597                         ret = -errno;
1598                         fprintf(stderr, "Couldn't open %s: %s\n",
1599                                 path, strerror(errno));
1600                         goto out;
1601                 }
1602                 ret = check_mounted_where(fd, path, mp, sizeof(mp),
1603                                           &fs_devices_mnt);
1604                 if (!ret) {
1605                         ret = -EINVAL;
1606                         goto out;
1607                 }
1608                 if (ret < 0)
1609                         goto out;
1610                 path = mp;
1611                 /* Only fill in this one device */
1612                 fi_args->num_devices = 1;
1613                 fi_args->max_id = fs_devices_mnt->latest_devid;
1614                 i = fs_devices_mnt->latest_devid;
1615                 memcpy(fi_args->fsid, fs_devices_mnt->fsid, BTRFS_FSID_SIZE);
1616                 close(fd);
1617         }
1618
1619         /* at this point path must not be for a block device */
1620         fd = open_file_or_dir(path, &dirstream);
1621         if (fd < 0) {
1622                 ret = -errno;
1623                 goto out;
1624         }
1625
1626         /* fill in fi_args if not just a single device */
1627         if (fi_args->num_devices != 1) {
1628                 ret = ioctl(fd, BTRFS_IOC_FS_INFO, fi_args);
1629                 if (ret < 0) {
1630                         ret = -errno;
1631                         goto out;
1632                 }
1633         }
1634
1635         if (!fi_args->num_devices)
1636                 goto out;
1637
1638         di_args = *di_ret = malloc(fi_args->num_devices * sizeof(*di_args));
1639         if (!di_args) {
1640                 ret = -errno;
1641                 goto out;
1642         }
1643
1644         for (; i <= fi_args->max_id; ++i) {
1645                 BUG_ON(ndevs >= fi_args->num_devices);
1646                 ret = get_device_info(fd, i, &di_args[ndevs]);
1647                 if (ret == -ENODEV)
1648                         continue;
1649                 if (ret)
1650                         goto out;
1651                 ndevs++;
1652         }
1653
1654         BUG_ON(ndevs == 0);
1655         ret = 0;
1656 out:
1657         close_file_or_dir(fd, dirstream);
1658         return ret;
1659 }
1660
1661 #define isoctal(c)      (((c) & ~7) == '0')
1662
1663 static inline void translate(char *f, char *t)
1664 {
1665         while (*f != '\0') {
1666                 if (*f == '\\' &&
1667                     isoctal(f[1]) && isoctal(f[2]) && isoctal(f[3])) {
1668                         *t++ = 64*(f[1] & 7) + 8*(f[2] & 7) + (f[3] & 7);
1669                         f += 4;
1670                 } else
1671                         *t++ = *f++;
1672         }
1673         *t = '\0';
1674         return;
1675 }
1676
1677 /*
1678  * Checks if the swap device.
1679  * Returns 1 if swap device, < 0 on error or 0 if not swap device.
1680  */
1681 static int is_swap_device(const char *file)
1682 {
1683         FILE    *f;
1684         struct stat     st_buf;
1685         dev_t   dev;
1686         ino_t   ino = 0;
1687         char    tmp[PATH_MAX];
1688         char    buf[PATH_MAX];
1689         char    *cp;
1690         int     ret = 0;
1691
1692         if (stat(file, &st_buf) < 0)
1693                 return -errno;
1694         if (S_ISBLK(st_buf.st_mode))
1695                 dev = st_buf.st_rdev;
1696         else if (S_ISREG(st_buf.st_mode)) {
1697                 dev = st_buf.st_dev;
1698                 ino = st_buf.st_ino;
1699         } else
1700                 return 0;
1701
1702         if ((f = fopen("/proc/swaps", "r")) == NULL)
1703                 return 0;
1704
1705         /* skip the first line */
1706         if (fgets(tmp, sizeof(tmp), f) == NULL)
1707                 goto out;
1708
1709         while (fgets(tmp, sizeof(tmp), f) != NULL) {
1710                 if ((cp = strchr(tmp, ' ')) != NULL)
1711                         *cp = '\0';
1712                 if ((cp = strchr(tmp, '\t')) != NULL)
1713                         *cp = '\0';
1714                 translate(tmp, buf);
1715                 if (stat(buf, &st_buf) != 0)
1716                         continue;
1717                 if (S_ISBLK(st_buf.st_mode)) {
1718                         if (dev == st_buf.st_rdev) {
1719                                 ret = 1;
1720                                 break;
1721                         }
1722                 } else if (S_ISREG(st_buf.st_mode)) {
1723                         if (dev == st_buf.st_dev && ino == st_buf.st_ino) {
1724                                 ret = 1;
1725                                 break;
1726                         }
1727                 }
1728         }
1729
1730 out:
1731         fclose(f);
1732
1733         return ret;
1734 }
1735
1736 /*
1737  * Check for existing filesystem or partition table on device.
1738  * Returns:
1739  *       1 for existing fs or partition
1740  *       0 for nothing found
1741  *      -1 for internal error
1742  */
1743 static int
1744 check_overwrite(
1745         char            *device)
1746 {
1747         const char      *type;
1748         blkid_probe     pr = NULL;
1749         int             ret;
1750         blkid_loff_t    size;
1751
1752         if (!device || !*device)
1753                 return 0;
1754
1755         ret = -1; /* will reset on success of all setup calls */
1756
1757         pr = blkid_new_probe_from_filename(device);
1758         if (!pr)
1759                 goto out;
1760
1761         size = blkid_probe_get_size(pr);
1762         if (size < 0)
1763                 goto out;
1764
1765         /* nothing to overwrite on a 0-length device */
1766         if (size == 0) {
1767                 ret = 0;
1768                 goto out;
1769         }
1770
1771         ret = blkid_probe_enable_partitions(pr, 1);
1772         if (ret < 0)
1773                 goto out;
1774
1775         ret = blkid_do_fullprobe(pr);
1776         if (ret < 0)
1777                 goto out;
1778
1779         /*
1780          * Blkid returns 1 for nothing found and 0 when it finds a signature,
1781          * but we want the exact opposite, so reverse the return value here.
1782          *
1783          * In addition print some useful diagnostics about what actually is
1784          * on the device.
1785          */
1786         if (ret) {
1787                 ret = 0;
1788                 goto out;
1789         }
1790
1791         if (!blkid_probe_lookup_value(pr, "TYPE", &type, NULL)) {
1792                 fprintf(stderr,
1793                         "%s appears to contain an existing "
1794                         "filesystem (%s).\n", device, type);
1795         } else if (!blkid_probe_lookup_value(pr, "PTTYPE", &type, NULL)) {
1796                 fprintf(stderr,
1797                         "%s appears to contain a partition "
1798                         "table (%s).\n", device, type);
1799         } else {
1800                 fprintf(stderr,
1801                         "%s appears to contain something weird "
1802                         "according to blkid\n", device);
1803         }
1804         ret = 1;
1805
1806 out:
1807         if (pr)
1808                 blkid_free_probe(pr);
1809         if (ret == -1)
1810                 fprintf(stderr,
1811                         "probe of %s failed, cannot detect "
1812                           "existing filesystem.\n", device);
1813         return ret;
1814 }
1815
1816 int test_num_disk_vs_raid(u64 metadata_profile, u64 data_profile,
1817         u64 dev_cnt, int mixed, char *estr)
1818 {
1819         size_t sz = 100;
1820         u64 allowed = 0;
1821
1822         switch (dev_cnt) {
1823         default:
1824         case 4:
1825                 allowed |= BTRFS_BLOCK_GROUP_RAID10;
1826         case 3:
1827                 allowed |= BTRFS_BLOCK_GROUP_RAID6;
1828         case 2:
1829                 allowed |= BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
1830                         BTRFS_BLOCK_GROUP_RAID5;
1831                 break;
1832         case 1:
1833                 allowed |= BTRFS_BLOCK_GROUP_DUP;
1834         }
1835
1836         if (metadata_profile & ~allowed) {
1837                 snprintf(estr, sz, "unable to create FS with metadata "
1838                         "profile %llu (have %llu devices)\n",
1839                         metadata_profile, dev_cnt);
1840                 return 1;
1841         }
1842         if (data_profile & ~allowed) {
1843                 snprintf(estr, sz, "unable to create FS with data "
1844                         "profile %llu (have %llu devices)\n",
1845                         metadata_profile, dev_cnt);
1846                 return 1;
1847         }
1848
1849         if (!mixed && (data_profile & BTRFS_BLOCK_GROUP_DUP)) {
1850                 snprintf(estr, sz,
1851                         "dup for data is allowed only in mixed mode");
1852                 return 1;
1853         }
1854         return 0;
1855 }
1856
1857 /* Check if disk is suitable for btrfs
1858  * returns:
1859  *  1: something is wrong, estr provides the error
1860  *  0: all is fine
1861  */
1862 int test_dev_for_mkfs(char *file, int force_overwrite, char *estr)
1863 {
1864         int ret, fd;
1865         size_t sz = 100;
1866         struct stat st;
1867
1868         ret = is_swap_device(file);
1869         if (ret < 0) {
1870                 snprintf(estr, sz, "error checking %s status: %s\n", file,
1871                         strerror(-ret));
1872                 return 1;
1873         }
1874         if (ret == 1) {
1875                 snprintf(estr, sz, "%s is a swap device\n", file);
1876                 return 1;
1877         }
1878         if (!force_overwrite) {
1879                 if (check_overwrite(file)) {
1880                         snprintf(estr, sz, "Use the -f option to force overwrite.\n");
1881                         return 1;
1882                 }
1883         }
1884         ret = check_mounted(file);
1885         if (ret < 0) {
1886                 snprintf(estr, sz, "error checking %s mount status\n",
1887                         file);
1888                 return 1;
1889         }
1890         if (ret == 1) {
1891                 snprintf(estr, sz, "%s is mounted\n", file);
1892                 return 1;
1893         }
1894         /* check if the device is busy */
1895         fd = open(file, O_RDWR|O_EXCL);
1896         if (fd < 0) {
1897                 snprintf(estr, sz, "unable to open %s: %s\n", file,
1898                         strerror(errno));
1899                 return 1;
1900         }
1901         if (fstat(fd, &st)) {
1902                 snprintf(estr, sz, "unable to stat %s: %s\n", file,
1903                         strerror(errno));
1904                 return 1;
1905         }
1906         if (!S_ISBLK(st.st_mode)) {
1907                 fprintf(stderr, "'%s' is not a block device\n", file);
1908                 return 1;
1909         }
1910         close(fd);
1911         return 0;
1912 }
1913
1914 /*
1915  * scans devs for the btrfs
1916 */
1917 int scan_for_btrfs(int where, int update_kernel)
1918 {
1919         int ret = 0;
1920
1921         switch (where) {
1922         case BTRFS_SCAN_PROC:
1923                 ret = btrfs_scan_block_devices(update_kernel);
1924                 break;
1925         case BTRFS_SCAN_DEV:
1926                 ret = btrfs_scan_one_dir("/dev", update_kernel);
1927                 break;
1928         }
1929         return ret;
1930 }
1931
1932 int is_vol_small(char *file)
1933 {
1934         int fd = -1;
1935         int e;
1936         struct stat st;
1937         u64 size;
1938
1939         fd = open(file, O_RDONLY);
1940         if (fd < 0)
1941                 return -errno;
1942         if (fstat(fd, &st) < 0) {
1943                 e = -errno;
1944                 close(fd);
1945                 return e;
1946         }
1947         size = btrfs_device_size(fd, &st);
1948         if (size == 0) {
1949                 close(fd);
1950                 return -1;
1951         }
1952         if (size < 1024 * 1024 * 1024) {
1953                 close(fd);
1954                 return 1;
1955         } else {
1956                 close(fd);
1957                 return 0;
1958         }
1959 }