parse_size(): replace atoll() with strtoull()
[platform/upstream/btrfs-progs.git] / utils.c
1 /*
2  * Copyright (C) 2007 Oracle.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18
19 #define _XOPEN_SOURCE 600
20 #define __USE_XOPEN2K
21 #include <stdio.h>
22 #include <stdlib.h>
23 #ifndef __CHECKER__
24 #include <sys/ioctl.h>
25 #include <sys/mount.h>
26 #endif
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <uuid/uuid.h>
30 #include <dirent.h>
31 #include <fcntl.h>
32 #include <unistd.h>
33 #include <mntent.h>
34 #include <ctype.h>
35 #include <linux/loop.h>
36 #include <linux/major.h>
37 #include <linux/kdev_t.h>
38 #include <limits.h>
39 #include "kerncompat.h"
40 #include "radix-tree.h"
41 #include "ctree.h"
42 #include "disk-io.h"
43 #include "transaction.h"
44 #include "crc32c.h"
45 #include "utils.h"
46 #include "volumes.h"
47 #include "ioctl.h"
48
49 #ifdef __CHECKER__
50 #define BLKGETSIZE64 0
51 static inline int ioctl(int fd, int define, u64 *size) { return 0; }
52 #endif
53
54 #ifndef BLKDISCARD
55 #define BLKDISCARD      _IO(0x12,119)
56 #endif
57
58 static int
59 discard_blocks(int fd, u64 start, u64 len)
60 {
61         u64 range[2] = { start, len };
62
63         if (ioctl(fd, BLKDISCARD, &range) < 0)
64                 return errno;
65         return 0;
66 }
67
68 static u64 reference_root_table[] = {
69         [1] =   BTRFS_ROOT_TREE_OBJECTID,
70         [2] =   BTRFS_EXTENT_TREE_OBJECTID,
71         [3] =   BTRFS_CHUNK_TREE_OBJECTID,
72         [4] =   BTRFS_DEV_TREE_OBJECTID,
73         [5] =   BTRFS_FS_TREE_OBJECTID,
74         [6] =   BTRFS_CSUM_TREE_OBJECTID,
75 };
76
77 int make_btrfs(int fd, const char *device, const char *label,
78                u64 blocks[7], u64 num_bytes, u32 nodesize,
79                u32 leafsize, u32 sectorsize, u32 stripesize)
80 {
81         struct btrfs_super_block super;
82         struct extent_buffer *buf;
83         struct btrfs_root_item root_item;
84         struct btrfs_disk_key disk_key;
85         struct btrfs_extent_item *extent_item;
86         struct btrfs_inode_item *inode_item;
87         struct btrfs_chunk *chunk;
88         struct btrfs_dev_item *dev_item;
89         struct btrfs_dev_extent *dev_extent;
90         u8 chunk_tree_uuid[BTRFS_UUID_SIZE];
91         u8 *ptr;
92         int i;
93         int ret;
94         u32 itemoff;
95         u32 nritems = 0;
96         u64 first_free;
97         u64 ref_root;
98         u32 array_size;
99         u32 item_size;
100
101         first_free = BTRFS_SUPER_INFO_OFFSET + sectorsize * 2 - 1;
102         first_free &= ~((u64)sectorsize - 1);
103
104         memset(&super, 0, sizeof(super));
105
106         num_bytes = (num_bytes / sectorsize) * sectorsize;
107         uuid_generate(super.fsid);
108         uuid_generate(super.dev_item.uuid);
109         uuid_generate(chunk_tree_uuid);
110
111         btrfs_set_super_bytenr(&super, blocks[0]);
112         btrfs_set_super_num_devices(&super, 1);
113         strncpy((char *)&super.magic, BTRFS_MAGIC, sizeof(super.magic));
114         btrfs_set_super_generation(&super, 1);
115         btrfs_set_super_root(&super, blocks[1]);
116         btrfs_set_super_chunk_root(&super, blocks[3]);
117         btrfs_set_super_total_bytes(&super, num_bytes);
118         btrfs_set_super_bytes_used(&super, 6 * leafsize);
119         btrfs_set_super_sectorsize(&super, sectorsize);
120         btrfs_set_super_leafsize(&super, leafsize);
121         btrfs_set_super_nodesize(&super, nodesize);
122         btrfs_set_super_stripesize(&super, stripesize);
123         btrfs_set_super_csum_type(&super, BTRFS_CSUM_TYPE_CRC32);
124         btrfs_set_super_chunk_root_generation(&super, 1);
125         btrfs_set_super_cache_generation(&super, -1);
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         BUG_ON(ret != leafsize);
214
215         /* create the items for the extent tree */
216         memset(buf->data+sizeof(struct btrfs_header), 0,
217                 leafsize-sizeof(struct btrfs_header));
218         nritems = 0;
219         itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize);
220         for (i = 1; i < 7; i++) {
221                 BUG_ON(blocks[i] < first_free);
222                 BUG_ON(blocks[i] < blocks[i - 1]);
223
224                 /* create extent item */
225                 itemoff -= sizeof(struct btrfs_extent_item) +
226                            sizeof(struct btrfs_tree_block_info);
227                 btrfs_set_disk_key_objectid(&disk_key, blocks[i]);
228                 btrfs_set_disk_key_offset(&disk_key, leafsize);
229                 btrfs_set_disk_key_type(&disk_key, BTRFS_EXTENT_ITEM_KEY);
230                 btrfs_set_item_key(buf, &disk_key, nritems);
231                 btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems),
232                                       itemoff);
233                 btrfs_set_item_size(buf, btrfs_item_nr(buf, nritems),
234                                     sizeof(struct btrfs_extent_item) +
235                                     sizeof(struct btrfs_tree_block_info));
236                 extent_item = btrfs_item_ptr(buf, nritems,
237                                              struct btrfs_extent_item);
238                 btrfs_set_extent_refs(buf, extent_item, 1);
239                 btrfs_set_extent_generation(buf, extent_item, 1);
240                 btrfs_set_extent_flags(buf, extent_item,
241                                        BTRFS_EXTENT_FLAG_TREE_BLOCK);
242                 nritems++;
243
244                 /* create extent ref */
245                 ref_root = reference_root_table[i];
246                 btrfs_set_disk_key_objectid(&disk_key, blocks[i]);
247                 btrfs_set_disk_key_offset(&disk_key, ref_root);
248                 btrfs_set_disk_key_type(&disk_key, BTRFS_TREE_BLOCK_REF_KEY);
249                 btrfs_set_item_key(buf, &disk_key, nritems);
250                 btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems),
251                                       itemoff);
252                 btrfs_set_item_size(buf, btrfs_item_nr(buf, nritems), 0);
253                 nritems++;
254         }
255         btrfs_set_header_bytenr(buf, blocks[2]);
256         btrfs_set_header_owner(buf, BTRFS_EXTENT_TREE_OBJECTID);
257         btrfs_set_header_nritems(buf, nritems);
258         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
259         ret = pwrite(fd, buf->data, leafsize, blocks[2]);
260         BUG_ON(ret != leafsize);
261
262         /* create the chunk tree */
263         memset(buf->data+sizeof(struct btrfs_header), 0,
264                 leafsize-sizeof(struct btrfs_header));
265         nritems = 0;
266         item_size = sizeof(*dev_item);
267         itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize) - item_size;
268
269         /* first device 1 (there is no device 0) */
270         btrfs_set_disk_key_objectid(&disk_key, BTRFS_DEV_ITEMS_OBJECTID);
271         btrfs_set_disk_key_offset(&disk_key, 1);
272         btrfs_set_disk_key_type(&disk_key, BTRFS_DEV_ITEM_KEY);
273         btrfs_set_item_key(buf, &disk_key, nritems);
274         btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems), itemoff);
275         btrfs_set_item_size(buf, btrfs_item_nr(buf, nritems), item_size);
276
277         dev_item = btrfs_item_ptr(buf, nritems, struct btrfs_dev_item);
278         btrfs_set_device_id(buf, dev_item, 1);
279         btrfs_set_device_generation(buf, dev_item, 0);
280         btrfs_set_device_total_bytes(buf, dev_item, num_bytes);
281         btrfs_set_device_bytes_used(buf, dev_item,
282                                     BTRFS_MKFS_SYSTEM_GROUP_SIZE);
283         btrfs_set_device_io_align(buf, dev_item, sectorsize);
284         btrfs_set_device_io_width(buf, dev_item, sectorsize);
285         btrfs_set_device_sector_size(buf, dev_item, sectorsize);
286         btrfs_set_device_type(buf, dev_item, 0);
287
288         write_extent_buffer(buf, super.dev_item.uuid,
289                             (unsigned long)btrfs_device_uuid(dev_item),
290                             BTRFS_UUID_SIZE);
291         write_extent_buffer(buf, super.fsid,
292                             (unsigned long)btrfs_device_fsid(dev_item),
293                             BTRFS_UUID_SIZE);
294         read_extent_buffer(buf, &super.dev_item, (unsigned long)dev_item,
295                            sizeof(*dev_item));
296
297         nritems++;
298         item_size = btrfs_chunk_item_size(1);
299         itemoff = itemoff - item_size;
300
301         /* then we have chunk 0 */
302         btrfs_set_disk_key_objectid(&disk_key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
303         btrfs_set_disk_key_offset(&disk_key, 0);
304         btrfs_set_disk_key_type(&disk_key, BTRFS_CHUNK_ITEM_KEY);
305         btrfs_set_item_key(buf, &disk_key, nritems);
306         btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems), itemoff);
307         btrfs_set_item_size(buf, btrfs_item_nr(buf,  nritems), item_size);
308
309         chunk = btrfs_item_ptr(buf, nritems, struct btrfs_chunk);
310         btrfs_set_chunk_length(buf, chunk, BTRFS_MKFS_SYSTEM_GROUP_SIZE);
311         btrfs_set_chunk_owner(buf, chunk, BTRFS_EXTENT_TREE_OBJECTID);
312         btrfs_set_chunk_stripe_len(buf, chunk, 64 * 1024);
313         btrfs_set_chunk_type(buf, chunk, BTRFS_BLOCK_GROUP_SYSTEM);
314         btrfs_set_chunk_io_align(buf, chunk, sectorsize);
315         btrfs_set_chunk_io_width(buf, chunk, sectorsize);
316         btrfs_set_chunk_sector_size(buf, chunk, sectorsize);
317         btrfs_set_chunk_num_stripes(buf, chunk, 1);
318         btrfs_set_stripe_devid_nr(buf, chunk, 0, 1);
319         btrfs_set_stripe_offset_nr(buf, chunk, 0, 0);
320         nritems++;
321
322         write_extent_buffer(buf, super.dev_item.uuid,
323                             (unsigned long)btrfs_stripe_dev_uuid(&chunk->stripe),
324                             BTRFS_UUID_SIZE);
325
326         /* copy the key for the chunk to the system array */
327         ptr = super.sys_chunk_array;
328         array_size = sizeof(disk_key);
329
330         memcpy(ptr, &disk_key, sizeof(disk_key));
331         ptr += sizeof(disk_key);
332
333         /* copy the chunk to the system array */
334         read_extent_buffer(buf, ptr, (unsigned long)chunk, item_size);
335         array_size += item_size;
336         ptr += item_size;
337         btrfs_set_super_sys_array_size(&super, array_size);
338
339         btrfs_set_header_bytenr(buf, blocks[3]);
340         btrfs_set_header_owner(buf, BTRFS_CHUNK_TREE_OBJECTID);
341         btrfs_set_header_nritems(buf, nritems);
342         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
343         ret = pwrite(fd, buf->data, leafsize, blocks[3]);
344
345         /* create the device tree */
346         memset(buf->data+sizeof(struct btrfs_header), 0,
347                 leafsize-sizeof(struct btrfs_header));
348         nritems = 0;
349         itemoff = __BTRFS_LEAF_DATA_SIZE(leafsize) -
350                 sizeof(struct btrfs_dev_extent);
351
352         btrfs_set_disk_key_objectid(&disk_key, 1);
353         btrfs_set_disk_key_offset(&disk_key, 0);
354         btrfs_set_disk_key_type(&disk_key, BTRFS_DEV_EXTENT_KEY);
355         btrfs_set_item_key(buf, &disk_key, nritems);
356         btrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems), itemoff);
357         btrfs_set_item_size(buf, btrfs_item_nr(buf,  nritems),
358                             sizeof(struct btrfs_dev_extent));
359         dev_extent = btrfs_item_ptr(buf, nritems, struct btrfs_dev_extent);
360         btrfs_set_dev_extent_chunk_tree(buf, dev_extent,
361                                         BTRFS_CHUNK_TREE_OBJECTID);
362         btrfs_set_dev_extent_chunk_objectid(buf, dev_extent,
363                                         BTRFS_FIRST_CHUNK_TREE_OBJECTID);
364         btrfs_set_dev_extent_chunk_offset(buf, dev_extent, 0);
365
366         write_extent_buffer(buf, chunk_tree_uuid,
367                     (unsigned long)btrfs_dev_extent_chunk_tree_uuid(dev_extent),
368                     BTRFS_UUID_SIZE);
369
370         btrfs_set_dev_extent_length(buf, dev_extent,
371                                     BTRFS_MKFS_SYSTEM_GROUP_SIZE);
372         nritems++;
373
374         btrfs_set_header_bytenr(buf, blocks[4]);
375         btrfs_set_header_owner(buf, BTRFS_DEV_TREE_OBJECTID);
376         btrfs_set_header_nritems(buf, nritems);
377         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
378         ret = pwrite(fd, buf->data, leafsize, blocks[4]);
379
380         /* create the FS root */
381         memset(buf->data+sizeof(struct btrfs_header), 0,
382                 leafsize-sizeof(struct btrfs_header));
383         btrfs_set_header_bytenr(buf, blocks[5]);
384         btrfs_set_header_owner(buf, BTRFS_FS_TREE_OBJECTID);
385         btrfs_set_header_nritems(buf, 0);
386         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
387         ret = pwrite(fd, buf->data, leafsize, blocks[5]);
388         BUG_ON(ret != leafsize);
389
390         /* finally create the csum root */
391         memset(buf->data+sizeof(struct btrfs_header), 0,
392                 leafsize-sizeof(struct btrfs_header));
393         btrfs_set_header_bytenr(buf, blocks[6]);
394         btrfs_set_header_owner(buf, BTRFS_CSUM_TREE_OBJECTID);
395         btrfs_set_header_nritems(buf, 0);
396         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
397         ret = pwrite(fd, buf->data, leafsize, blocks[6]);
398         BUG_ON(ret != leafsize);
399
400         /* and write out the super block */
401         BUG_ON(sizeof(super) > sectorsize);
402         memset(buf->data, 0, sectorsize);
403         memcpy(buf->data, &super, sizeof(super));
404         buf->len = sectorsize;
405         csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
406         ret = pwrite(fd, buf->data, sectorsize, blocks[0]);
407         BUG_ON(ret != sectorsize);
408
409
410         free(buf);
411         return 0;
412 }
413
414 static u64 device_size(int fd, struct stat *st)
415 {
416         u64 size;
417         if (S_ISREG(st->st_mode)) {
418                 return st->st_size;
419         }
420         if (!S_ISBLK(st->st_mode)) {
421                 return 0;
422         }
423         if (ioctl(fd, BLKGETSIZE64, &size) >= 0) {
424                 return size;
425         }
426         return 0;
427 }
428
429 static int zero_blocks(int fd, off_t start, size_t len)
430 {
431         char *buf = malloc(len);
432         int ret = 0;
433         ssize_t written;
434
435         if (!buf)
436                 return -ENOMEM;
437         memset(buf, 0, len);
438         written = pwrite(fd, buf, len, start);
439         if (written != len)
440                 ret = -EIO;
441         free(buf);
442         return ret;
443 }
444
445 static int zero_dev_start(int fd)
446 {
447         off_t start = 0;
448         size_t len = 2 * 1024 * 1024;
449
450 #ifdef __sparc__
451         /* don't overwrite the disk labels on sparc */
452         start = 1024;
453         len -= 1024;
454 #endif
455         return zero_blocks(fd, start, len);
456 }
457
458 static int zero_dev_end(int fd, u64 dev_size)
459 {
460         size_t len = 2 * 1024 * 1024;
461         off_t start = dev_size - len;
462
463         return zero_blocks(fd, start, len);
464 }
465
466 int btrfs_add_to_fsid(struct btrfs_trans_handle *trans,
467                       struct btrfs_root *root, int fd, char *path,
468                       u64 block_count, u32 io_width, u32 io_align,
469                       u32 sectorsize)
470 {
471         struct btrfs_super_block *disk_super;
472         struct btrfs_super_block *super = &root->fs_info->super_copy;
473         struct btrfs_device *device;
474         struct btrfs_dev_item *dev_item;
475         char *buf;
476         u64 total_bytes;
477         u64 num_devs;
478         int ret;
479
480         device = kmalloc(sizeof(*device), GFP_NOFS);
481         if (!device)
482                 return -ENOMEM;
483         buf = kmalloc(sectorsize, GFP_NOFS);
484         if (!buf) {
485                 kfree(device);
486                 return -ENOMEM;
487         }
488         BUG_ON(sizeof(*disk_super) > sectorsize);
489         memset(buf, 0, sectorsize);
490
491         disk_super = (struct btrfs_super_block *)buf;
492         dev_item = &disk_super->dev_item;
493
494         uuid_generate(device->uuid);
495         device->devid = 0;
496         device->type = 0;
497         device->io_width = io_width;
498         device->io_align = io_align;
499         device->sector_size = sectorsize;
500         device->fd = fd;
501         device->writeable = 1;
502         device->total_bytes = block_count;
503         device->bytes_used = 0;
504         device->total_ios = 0;
505         device->dev_root = root->fs_info->dev_root;
506
507         ret = btrfs_add_device(trans, root, device);
508         BUG_ON(ret);
509
510         total_bytes = btrfs_super_total_bytes(super) + block_count;
511         btrfs_set_super_total_bytes(super, total_bytes);
512
513         num_devs = btrfs_super_num_devices(super) + 1;
514         btrfs_set_super_num_devices(super, num_devs);
515
516         memcpy(disk_super, super, sizeof(*disk_super));
517
518         printf("adding device %s id %llu\n", path,
519                (unsigned long long)device->devid);
520
521         btrfs_set_super_bytenr(disk_super, BTRFS_SUPER_INFO_OFFSET);
522         btrfs_set_stack_device_id(dev_item, device->devid);
523         btrfs_set_stack_device_type(dev_item, device->type);
524         btrfs_set_stack_device_io_align(dev_item, device->io_align);
525         btrfs_set_stack_device_io_width(dev_item, device->io_width);
526         btrfs_set_stack_device_sector_size(dev_item, device->sector_size);
527         btrfs_set_stack_device_total_bytes(dev_item, device->total_bytes);
528         btrfs_set_stack_device_bytes_used(dev_item, device->bytes_used);
529         memcpy(&dev_item->uuid, device->uuid, BTRFS_UUID_SIZE);
530
531         ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
532         BUG_ON(ret != sectorsize);
533
534         kfree(buf);
535         list_add(&device->dev_list, &root->fs_info->fs_devices->devices);
536         device->fs_devices = root->fs_info->fs_devices;
537         return 0;
538 }
539
540 int btrfs_prepare_device(int fd, char *file, int zero_end, u64 *block_count_ret,
541                            u64 max_block_count, int *mixed, int nodiscard)
542 {
543         u64 block_count;
544         u64 bytenr;
545         struct stat st;
546         int i, ret;
547
548         ret = fstat(fd, &st);
549         if (ret < 0) {
550                 fprintf(stderr, "unable to stat %s\n", file);
551                 exit(1);
552         }
553
554         block_count = device_size(fd, &st);
555         if (block_count == 0) {
556                 fprintf(stderr, "unable to find %s size\n", file);
557                 exit(1);
558         }
559         if (max_block_count)
560                 block_count = min(block_count, max_block_count);
561         zero_end = 1;
562
563         if (block_count < 1024 * 1024 * 1024 && !(*mixed)) {
564                 printf("SMALL VOLUME: forcing mixed metadata/data groups\n");
565                 *mixed = 1;
566         }
567
568         if (!nodiscard) {
569                 /*
570                  * We intentionally ignore errors from the discard ioctl.  It is
571                  * not necessary for the mkfs functionality but just an optimization.
572                  */
573                 discard_blocks(fd, 0, block_count);
574         }
575
576         ret = zero_dev_start(fd);
577         if (ret) {
578                 fprintf(stderr, "failed to zero device start %d\n", ret);
579                 exit(1);
580         }
581
582         for (i = 0 ; i < BTRFS_SUPER_MIRROR_MAX; i++) {
583                 bytenr = btrfs_sb_offset(i);
584                 if (bytenr >= block_count)
585                         break;
586                 zero_blocks(fd, bytenr, BTRFS_SUPER_INFO_SIZE);
587         }
588
589         if (zero_end) {
590                 ret = zero_dev_end(fd, block_count);
591                 if (ret) {
592                         fprintf(stderr, "failed to zero device end %d\n", ret);
593                         exit(1);
594                 }
595         }
596         *block_count_ret = block_count;
597         return 0;
598 }
599
600 int btrfs_make_root_dir(struct btrfs_trans_handle *trans,
601                         struct btrfs_root *root, u64 objectid)
602 {
603         int ret;
604         struct btrfs_inode_item inode_item;
605         time_t now = time(NULL);
606
607         memset(&inode_item, 0, sizeof(inode_item));
608         btrfs_set_stack_inode_generation(&inode_item, trans->transid);
609         btrfs_set_stack_inode_size(&inode_item, 0);
610         btrfs_set_stack_inode_nlink(&inode_item, 1);
611         btrfs_set_stack_inode_nbytes(&inode_item, root->leafsize);
612         btrfs_set_stack_inode_mode(&inode_item, S_IFDIR | 0755);
613         btrfs_set_stack_timespec_sec(&inode_item.atime, now);
614         btrfs_set_stack_timespec_nsec(&inode_item.atime, 0);
615         btrfs_set_stack_timespec_sec(&inode_item.ctime, now);
616         btrfs_set_stack_timespec_nsec(&inode_item.ctime, 0);
617         btrfs_set_stack_timespec_sec(&inode_item.mtime, now);
618         btrfs_set_stack_timespec_nsec(&inode_item.mtime, 0);
619         btrfs_set_stack_timespec_sec(&inode_item.otime, 0);
620         btrfs_set_stack_timespec_nsec(&inode_item.otime, 0);
621
622         if (root->fs_info->tree_root == root)
623                 btrfs_set_super_root_dir(&root->fs_info->super_copy, objectid);
624
625         ret = btrfs_insert_inode(trans, root, objectid, &inode_item);
626         if (ret)
627                 goto error;
628
629         ret = btrfs_insert_inode_ref(trans, root, "..", 2, objectid, objectid, 0);
630         if (ret)
631                 goto error;
632
633         btrfs_set_root_dirid(&root->root_item, objectid);
634         ret = 0;
635 error:
636         return ret;
637 }
638
639 /* checks if a device is a loop device */
640 int is_loop_device (const char* device) {
641         struct stat statbuf;
642
643         if(stat(device, &statbuf) < 0)
644                 return -errno;
645
646         return (S_ISBLK(statbuf.st_mode) &&
647                 MAJOR(statbuf.st_rdev) == LOOP_MAJOR);
648 }
649
650
651 /* Takes a loop device path (e.g. /dev/loop0) and returns
652  * the associated file (e.g. /images/my_btrfs.img) */
653 int resolve_loop_device(const char* loop_dev, char* loop_file, int max_len)
654 {
655         int loop_fd;
656         int ret_ioctl;
657         struct loop_info loopinfo;
658
659         if ((loop_fd = open(loop_dev, O_RDONLY)) < 0)
660                 return -errno;
661
662         ret_ioctl = ioctl(loop_fd, LOOP_GET_STATUS, &loopinfo);
663         close(loop_fd);
664
665         if (ret_ioctl == 0) {
666                 strncpy(loop_file, loopinfo.lo_name, max_len);
667                 if (max_len > 0)
668                         loop_file[max_len-1] = 0;
669         } else
670                 return -errno;
671
672         return 0;
673 }
674
675 /* Checks whether a and b are identical or device
676  * files associated with the same block device
677  */
678 int is_same_blk_file(const char* a, const char* b)
679 {
680         struct stat st_buf_a, st_buf_b;
681         char real_a[PATH_MAX];
682         char real_b[PATH_MAX];
683
684         if(!realpath(a, real_a) ||
685            !realpath(b, real_b))
686         {
687                 return -errno;
688         }
689
690         /* Identical path? */
691         if(strcmp(real_a, real_b) == 0)
692                 return 1;
693
694         if(stat(a, &st_buf_a) < 0 ||
695            stat(b, &st_buf_b) < 0)
696         {
697                 if (errno == ENOENT)
698                         return 0;
699                 return -errno;
700         }
701
702         /* Same blockdevice? */
703         if(S_ISBLK(st_buf_a.st_mode) &&
704            S_ISBLK(st_buf_b.st_mode) &&
705            st_buf_a.st_rdev == st_buf_b.st_rdev)
706         {
707                 return 1;
708         }
709
710         /* Hardlink? */
711         if (st_buf_a.st_dev == st_buf_b.st_dev &&
712             st_buf_a.st_ino == st_buf_b.st_ino)
713         {
714                 return 1;
715         }
716
717         return 0;
718 }
719
720 /* checks if a and b are identical or device
721  * files associated with the same block device or
722  * if one file is a loop device that uses the other
723  * file.
724  */
725 int is_same_loop_file(const char* a, const char* b)
726 {
727         char res_a[PATH_MAX];
728         char res_b[PATH_MAX];
729         const char* final_a;
730         const char* final_b;
731         int ret;
732
733         /* Resolve a if it is a loop device */
734         if((ret = is_loop_device(a)) < 0) {
735                 if (ret == -ENOENT)
736                         return 0;
737                 return ret;
738         } else if (ret) {
739                 if ((ret = resolve_loop_device(a, res_a, sizeof(res_a))) < 0)
740                         return ret;
741
742                 final_a = res_a;
743         } else {
744                 final_a = a;
745         }
746
747         /* Resolve b if it is a loop device */
748         if ((ret = is_loop_device(b)) < 0) {
749                 if (ret == -ENOENT)
750                         return 0;
751                 return ret;
752         } else if (ret) {
753                 if((ret = resolve_loop_device(b, res_b, sizeof(res_b))) < 0)
754                         return ret;
755
756                 final_b = res_b;
757         } else {
758                 final_b = b;
759         }
760
761         return is_same_blk_file(final_a, final_b);
762 }
763
764 /* Checks if a file exists and is a block or regular file*/
765 int is_existing_blk_or_reg_file(const char* filename)
766 {
767         struct stat st_buf;
768
769         if(stat(filename, &st_buf) < 0) {
770                 if(errno == ENOENT)
771                         return 0;
772                 else
773                         return -errno;
774         }
775
776         return (S_ISBLK(st_buf.st_mode) || S_ISREG(st_buf.st_mode));
777 }
778
779 /* Checks if a file is used (directly or indirectly via a loop device)
780  * by a device in fs_devices
781  */
782 int blk_file_in_dev_list(struct btrfs_fs_devices* fs_devices, const char* file)
783 {
784         int ret;
785         struct list_head *head;
786         struct list_head *cur;
787         struct btrfs_device *device;
788
789         head = &fs_devices->devices;
790         list_for_each(cur, head) {
791                 device = list_entry(cur, struct btrfs_device, dev_list);
792
793                 if((ret = is_same_loop_file(device->name, file)))
794                         return ret;
795         }
796
797         return 0;
798 }
799
800 /*
801  * returns 1 if the device was mounted, < 0 on error or 0 if everything
802  * is safe to continue.
803  */
804 int check_mounted(const char* file)
805 {
806         int fd;
807         int ret;
808
809         fd = open(file, O_RDONLY);
810         if (fd < 0) {
811                 fprintf (stderr, "check_mounted(): Could not open %s\n", file);
812                 return -errno;
813         }
814
815         ret =  check_mounted_where(fd, file, NULL, 0, NULL);
816         close(fd);
817
818         return ret;
819 }
820
821 int check_mounted_where(int fd, const char *file, char *where, int size,
822                         struct btrfs_fs_devices **fs_dev_ret)
823 {
824         int ret;
825         u64 total_devs = 1;
826         int is_btrfs;
827         struct btrfs_fs_devices *fs_devices_mnt = NULL;
828         FILE *f;
829         struct mntent *mnt;
830
831         /* scan the initial device */
832         ret = btrfs_scan_one_device(fd, file, &fs_devices_mnt,
833                                     &total_devs, BTRFS_SUPER_INFO_OFFSET);
834         is_btrfs = (ret >= 0);
835
836         /* scan other devices */
837         if (is_btrfs && total_devs > 1) {
838                 if((ret = btrfs_scan_for_fsid(fs_devices_mnt, total_devs, 1)))
839                         return ret;
840         }
841
842         /* iterate over the list of currently mountes filesystems */
843         if ((f = setmntent ("/proc/mounts", "r")) == NULL)
844                 return -errno;
845
846         while ((mnt = getmntent (f)) != NULL) {
847                 if(is_btrfs) {
848                         if(strcmp(mnt->mnt_type, "btrfs") != 0)
849                                 continue;
850
851                         ret = blk_file_in_dev_list(fs_devices_mnt, mnt->mnt_fsname);
852                 } else {
853                         /* ignore entries in the mount table that are not
854                            associated with a file*/
855                         if((ret = is_existing_blk_or_reg_file(mnt->mnt_fsname)) < 0)
856                                 goto out_mntloop_err;
857                         else if(!ret)
858                                 continue;
859
860                         ret = is_same_loop_file(file, mnt->mnt_fsname);
861                 }
862
863                 if(ret < 0)
864                         goto out_mntloop_err;
865                 else if(ret)
866                         break;
867         }
868
869         /* Did we find an entry in mnt table? */
870         if (mnt && size && where) {
871                 strncpy(where, mnt->mnt_dir, size);
872                 where[size-1] = 0;
873         }
874         if (fs_dev_ret)
875                 *fs_dev_ret = fs_devices_mnt;
876
877         ret = (mnt != NULL);
878
879 out_mntloop_err:
880         endmntent (f);
881
882         return ret;
883 }
884
885 /* Gets the mount point of btrfs filesystem that is using the specified device.
886  * Returns 0 is everything is good, <0 if we have an error.
887  * TODO: Fix this fucntion and check_mounted to work with multiple drive BTRFS
888  * setups.
889  */
890 int get_mountpt(char *dev, char *mntpt, size_t size)
891 {
892        struct mntent *mnt;
893        FILE *f;
894        int ret = 0;
895
896        f = setmntent("/proc/mounts", "r");
897        if (f == NULL)
898                return -errno;
899
900        while ((mnt = getmntent(f)) != NULL )
901        {
902                if (strcmp(dev, mnt->mnt_fsname) == 0)
903                {
904                        strncpy(mntpt, mnt->mnt_dir, size);
905                        if (size)
906                                 mntpt[size-1] = 0;
907                        break;
908                }
909        }
910
911        if (mnt == NULL)
912        {
913                /* We didn't find an entry so lets report an error */
914                ret = -1;
915        }
916
917        return ret;
918 }
919
920 struct pending_dir {
921         struct list_head list;
922         char name[256];
923 };
924
925 void btrfs_register_one_device(char *fname)
926 {
927         struct btrfs_ioctl_vol_args args;
928         int fd;
929         int ret;
930         int e;
931
932         fd = open("/dev/btrfs-control", O_RDONLY);
933         if (fd < 0) {
934                 fprintf(stderr, "failed to open /dev/btrfs-control "
935                         "skipping device registration\n");
936                 return;
937         }
938         strncpy(args.name, fname, BTRFS_PATH_NAME_MAX);
939         args.name[BTRFS_PATH_NAME_MAX-1] = 0;
940         ret = ioctl(fd, BTRFS_IOC_SCAN_DEV, &args);
941         e = errno;
942         if(ret<0){
943                 fprintf(stderr, "ERROR: unable to scan the device '%s' - %s\n",
944                         fname, strerror(e));
945         }
946         close(fd);
947 }
948
949 int btrfs_scan_one_dir(char *dirname, int run_ioctl)
950 {
951         DIR *dirp = NULL;
952         struct dirent *dirent;
953         struct pending_dir *pending;
954         struct stat st;
955         int ret;
956         int fd;
957         int dirname_len;
958         int pathlen;
959         char *fullpath;
960         struct list_head pending_list;
961         struct btrfs_fs_devices *tmp_devices;
962         u64 num_devices;
963
964         INIT_LIST_HEAD(&pending_list);
965
966         pending = malloc(sizeof(*pending));
967         if (!pending)
968                 return -ENOMEM;
969         strcpy(pending->name, dirname);
970
971 again:
972         dirname_len = strlen(pending->name);
973         pathlen = 1024;
974         fullpath = malloc(pathlen);
975         dirname = pending->name;
976
977         if (!fullpath) {
978                 ret = -ENOMEM;
979                 goto fail;
980         }
981         dirp = opendir(dirname);
982         if (!dirp) {
983                 fprintf(stderr, "Unable to open %s for scanning\n", dirname);
984                 return -ENOENT;
985         }
986         while(1) {
987                 dirent = readdir(dirp);
988                 if (!dirent)
989                         break;
990                 if (dirent->d_name[0] == '.')
991                         continue;
992                 if (dirname_len + strlen(dirent->d_name) + 2 > pathlen) {
993                         ret = -EFAULT;
994                         goto fail;
995                 }
996                 snprintf(fullpath, pathlen, "%s/%s", dirname, dirent->d_name);
997                 ret = lstat(fullpath, &st);
998                 if (ret < 0) {
999                         fprintf(stderr, "failed to stat %s\n", fullpath);
1000                         continue;
1001                 }
1002                 if (S_ISLNK(st.st_mode))
1003                         continue;
1004                 if (S_ISDIR(st.st_mode)) {
1005                         struct pending_dir *next = malloc(sizeof(*next));
1006                         if (!next) {
1007                                 ret = -ENOMEM;
1008                                 goto fail;
1009                         }
1010                         strcpy(next->name, fullpath);
1011                         list_add_tail(&next->list, &pending_list);
1012                 }
1013                 if (!S_ISBLK(st.st_mode)) {
1014                         continue;
1015                 }
1016                 fd = open(fullpath, O_RDONLY);
1017                 if (fd < 0) {
1018                         fprintf(stderr, "failed to read %s: %s\n", fullpath,
1019                                         strerror(errno));
1020                         continue;
1021                 }
1022                 ret = btrfs_scan_one_device(fd, fullpath, &tmp_devices,
1023                                             &num_devices,
1024                                             BTRFS_SUPER_INFO_OFFSET);
1025                 if (ret == 0 && run_ioctl > 0) {
1026                         btrfs_register_one_device(fullpath);
1027                 }
1028                 close(fd);
1029         }
1030         if (!list_empty(&pending_list)) {
1031                 free(pending);
1032                 pending = list_entry(pending_list.next, struct pending_dir,
1033                                      list);
1034                 list_del(&pending->list);
1035                 closedir(dirp);
1036                 dirp = NULL;
1037                 goto again;
1038         }
1039         ret = 0;
1040 fail:
1041         free(pending);
1042         if (dirp)
1043                 closedir(dirp);
1044         return ret;
1045 }
1046
1047 int btrfs_scan_for_fsid(struct btrfs_fs_devices *fs_devices, u64 total_devs,
1048                         int run_ioctls)
1049 {
1050         int ret;
1051
1052         ret = btrfs_scan_block_devices(run_ioctls);
1053         if (ret)
1054                 ret = btrfs_scan_one_dir("/dev", run_ioctls);
1055         return ret;
1056 }
1057
1058 int btrfs_device_already_in_root(struct btrfs_root *root, int fd,
1059                                  int super_offset)
1060 {
1061         struct btrfs_super_block *disk_super;
1062         char *buf;
1063         int ret = 0;
1064
1065         buf = malloc(BTRFS_SUPER_INFO_SIZE);
1066         if (!buf) {
1067                 ret = -ENOMEM;
1068                 goto out;
1069         }
1070         ret = pread(fd, buf, BTRFS_SUPER_INFO_SIZE, super_offset);
1071         if (ret != BTRFS_SUPER_INFO_SIZE)
1072                 goto brelse;
1073
1074         ret = 0;
1075         disk_super = (struct btrfs_super_block *)buf;
1076         if (strncmp((char *)(&disk_super->magic), BTRFS_MAGIC,
1077             sizeof(disk_super->magic)))
1078                 goto brelse;
1079
1080         if (!memcmp(disk_super->fsid, root->fs_info->super_copy.fsid,
1081                     BTRFS_FSID_SIZE))
1082                 ret = 1;
1083 brelse:
1084         free(buf);
1085 out:
1086         return ret;
1087 }
1088
1089 static char *size_strs[] = { "", "KB", "MB", "GB", "TB",
1090                             "PB", "EB", "ZB", "YB"};
1091 char *pretty_sizes(u64 size)
1092 {
1093         int num_divs = 0;
1094         int pretty_len = 16;
1095         float fraction;
1096         char *pretty;
1097
1098         if( size < 1024 ){
1099                 fraction = size;
1100                 num_divs = 0;
1101         } else {
1102                 u64 last_size = size;
1103                 num_divs = 0;
1104                 while(size >= 1024){
1105                         last_size = size;
1106                         size /= 1024;
1107                         num_divs ++;
1108                 }
1109
1110                 if (num_divs > ARRAY_SIZE(size_strs))
1111                         return NULL;
1112                 fraction = (float)last_size / 1024;
1113         }
1114         pretty = malloc(pretty_len);
1115         snprintf(pretty, pretty_len, "%.2f%s", fraction, size_strs[num_divs]);
1116         return pretty;
1117 }
1118
1119 /*
1120  * Checks to make sure that the label matches our requirements.
1121  * Returns:
1122        0    if everything is safe and usable
1123       -1    if the label is too long
1124       -2    if the label contains an invalid character
1125  */
1126 int check_label(char *input)
1127 {
1128        int i;
1129        int len = strlen(input);
1130
1131        if (len > BTRFS_LABEL_SIZE) {
1132                return -1;
1133        }
1134
1135        for (i = 0; i < len; i++) {
1136                if (input[i] == '/' || input[i] == '\\') {
1137                        return -2;
1138                }
1139        }
1140
1141        return 0;
1142 }
1143
1144 int btrfs_scan_block_devices(int run_ioctl)
1145 {
1146
1147         struct stat st;
1148         int ret;
1149         int fd;
1150         struct btrfs_fs_devices *tmp_devices;
1151         u64 num_devices;
1152         FILE *proc_partitions;
1153         int i;
1154         char buf[1024];
1155         char fullpath[110];
1156         int scans = 0;
1157         int special;
1158
1159 scan_again:
1160         proc_partitions = fopen("/proc/partitions","r");
1161         if (!proc_partitions) {
1162                 fprintf(stderr, "Unable to open '/proc/partitions' for scanning\n");
1163                 return -ENOENT;
1164         }
1165         /* skip the header */
1166         for(i=0; i < 2 ; i++)
1167                 if(!fgets(buf, 1023, proc_partitions)){
1168                 fprintf(stderr, "Unable to read '/proc/partitions' for scanning\n");
1169                 fclose(proc_partitions);
1170                 return -ENOENT;
1171         }
1172
1173         strcpy(fullpath,"/dev/");
1174         while(fgets(buf, 1023, proc_partitions)) {
1175                 i = sscanf(buf," %*d %*d %*d %99s", fullpath+5);
1176
1177                 /*
1178                  * multipath and MD devices may register as a btrfs filesystem
1179                  * both through the original block device and through
1180                  * the special (/dev/mapper or /dev/mdX) entry.
1181                  * This scans the special entries last
1182                  */
1183                 special = strncmp(fullpath, "/dev/dm-", strlen("/dev/dm-")) == 0;
1184                 if (!special)
1185                         special = strncmp(fullpath, "/dev/md", strlen("/dev/md")) == 0;
1186
1187                 if (scans == 0 && special)
1188                         continue;
1189                 if (scans > 0 && !special)
1190                         continue;
1191
1192                 ret = lstat(fullpath, &st);
1193                 if (ret < 0) {
1194                         fprintf(stderr, "failed to stat %s\n", fullpath);
1195                         continue;
1196                 }
1197                 if (!S_ISBLK(st.st_mode)) {
1198                         continue;
1199                 }
1200
1201                 fd = open(fullpath, O_RDONLY);
1202                 if (fd < 0) {
1203                         fprintf(stderr, "failed to read %s\n", fullpath);
1204                         continue;
1205                 }
1206                 ret = btrfs_scan_one_device(fd, fullpath, &tmp_devices,
1207                                             &num_devices,
1208                                             BTRFS_SUPER_INFO_OFFSET);
1209                 if (ret == 0 && run_ioctl > 0) {
1210                         btrfs_register_one_device(fullpath);
1211                 }
1212                 close(fd);
1213         }
1214
1215         fclose(proc_partitions);
1216
1217         if (scans == 0) {
1218                 scans++;
1219                 goto scan_again;
1220         }
1221         return 0;
1222 }
1223
1224 u64 parse_size(char *s)
1225 {
1226         int i;
1227         char c;
1228         u64 mult = 1;
1229
1230         for (i=0 ; s[i] && isdigit(s[i]) ; i++) ;
1231         if (!i) {
1232                 fprintf(stderr, "ERROR: size value is empty\n");
1233                 exit(50);
1234         }
1235
1236         if (s[i]) {
1237                 c = tolower(s[i]);
1238                 switch (c) {
1239                 case 'g':
1240                         mult *= 1024;
1241                 case 'm':
1242                         mult *= 1024;
1243                 case 'k':
1244                         mult *= 1024;
1245                 case 'b':
1246                         break;
1247                 default:
1248                         fprintf(stderr, "ERROR: Unknown size descriptor "
1249                                 "'%c'\n", c);
1250                         exit(1);
1251                 }
1252         }
1253         if (s[i] && s[i+1]) {
1254                 fprintf(stderr, "ERROR: Illegal suffix contains "
1255                         "character '%c' in wrong position\n",
1256                         s[i+1]);
1257                 exit(51);
1258         }
1259         return strtoull(s, NULL, 10) * mult;
1260 }
1261