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