1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "ext4_utils.h"
18#include "uuid.h"
19#include "allocate.h"
20#include "indirect.h"
21#include "extent.h"
22
23#include <sparse/sparse.h>
24
25#include <fcntl.h>
26#include <sys/stat.h>
27#include <sys/types.h>
28#include <stddef.h>
29#include <string.h>
30
31#ifdef USE_MINGW
32#include <winsock2.h>
33#else
34#include <arpa/inet.h>
35#include <sys/ioctl.h>
36#endif
37
38#if defined(__linux__)
39#include <linux/fs.h>
40#elif defined(__APPLE__) && defined(__MACH__)
41#include <sys/disk.h>
42#endif
43
44int force = 0;
45struct fs_info info;
46struct fs_aux_info aux_info;
47struct sparse_file *ext4_sparse_file;
48
49jmp_buf setjmp_env;
50
51/* returns 1 if a is a power of b */
52static int is_power_of(int a, int b)
53{
54	while (a > b) {
55		if (a % b)
56			return 0;
57		a /= b;
58	}
59
60	return (a == b) ? 1 : 0;
61}
62
63/* Returns 1 if the bg contains a backup superblock.  On filesystems with
64   the sparse_super feature, only block groups 0, 1, and powers of 3, 5,
65   and 7 have backup superblocks.  Otherwise, all block groups have backup
66   superblocks */
67int ext4_bg_has_super_block(int bg)
68{
69	/* Without sparse_super, every block group has a superblock */
70	if (!(info.feat_ro_compat & EXT4_FEATURE_RO_COMPAT_SPARSE_SUPER))
71		return 1;
72
73	if (bg == 0 || bg == 1)
74		return 1;
75
76	if (is_power_of(bg, 3) || is_power_of(bg, 5) || is_power_of(bg, 7))
77		return 1;
78
79	return 0;
80}
81
82/* Write the filesystem image to a file */
83void write_ext4_image(int fd, int gz, int sparse, int crc)
84{
85	sparse_file_write(ext4_sparse_file, fd, gz, sparse, crc);
86}
87
88/* Compute the rest of the parameters of the filesystem from the basic info */
89void ext4_create_fs_aux_info()
90{
91	aux_info.first_data_block = (info.block_size > 1024) ? 0 : 1;
92	aux_info.len_blocks = info.len / info.block_size;
93	aux_info.inode_table_blocks = DIV_ROUND_UP(info.inodes_per_group * info.inode_size,
94		info.block_size);
95	aux_info.groups = DIV_ROUND_UP(aux_info.len_blocks - aux_info.first_data_block,
96		info.blocks_per_group);
97	aux_info.blocks_per_ind = info.block_size / sizeof(u32);
98	aux_info.blocks_per_dind = aux_info.blocks_per_ind * aux_info.blocks_per_ind;
99	aux_info.blocks_per_tind = aux_info.blocks_per_dind * aux_info.blocks_per_dind;
100
101	aux_info.bg_desc_blocks =
102		DIV_ROUND_UP(aux_info.groups * sizeof(struct ext2_group_desc),
103			info.block_size);
104
105	aux_info.default_i_flags = EXT4_NOATIME_FL;
106
107	u32 last_group_size = aux_info.len_blocks % info.blocks_per_group;
108	u32 last_header_size = 2 + aux_info.inode_table_blocks;
109	if (ext4_bg_has_super_block(aux_info.groups - 1))
110		last_header_size += 1 + aux_info.bg_desc_blocks +
111			info.bg_desc_reserve_blocks;
112	if (last_group_size > 0 && last_group_size < last_header_size) {
113		aux_info.groups--;
114		aux_info.len_blocks -= last_group_size;
115	}
116
117	aux_info.sb = calloc(info.block_size, 1);
118	/* Alloc an array to hold the pointers to the backup superblocks */
119	aux_info.backup_sb = calloc(aux_info.groups, sizeof(char *));
120
121	if (!aux_info.sb)
122		critical_error_errno("calloc");
123
124	aux_info.bg_desc = calloc(info.block_size, aux_info.bg_desc_blocks);
125	if (!aux_info.bg_desc)
126		critical_error_errno("calloc");
127	aux_info.xattrs = NULL;
128}
129
130void ext4_free_fs_aux_info()
131{
132	unsigned int i;
133
134	for (i=0; i<aux_info.groups; i++) {
135		if (aux_info.backup_sb[i])
136			free(aux_info.backup_sb[i]);
137	}
138	free(aux_info.sb);
139	free(aux_info.bg_desc);
140}
141
142/* Fill in the superblock memory buffer based on the filesystem parameters */
143void ext4_fill_in_sb()
144{
145	unsigned int i;
146	struct ext4_super_block *sb = aux_info.sb;
147
148	sb->s_inodes_count = info.inodes_per_group * aux_info.groups;
149	sb->s_blocks_count_lo = aux_info.len_blocks;
150	sb->s_r_blocks_count_lo = 0;
151	sb->s_free_blocks_count_lo = 0;
152	sb->s_free_inodes_count = 0;
153	sb->s_first_data_block = aux_info.first_data_block;
154	sb->s_log_block_size = log_2(info.block_size / 1024);
155	sb->s_obso_log_frag_size = log_2(info.block_size / 1024);
156	sb->s_blocks_per_group = info.blocks_per_group;
157	sb->s_obso_frags_per_group = info.blocks_per_group;
158	sb->s_inodes_per_group = info.inodes_per_group;
159	sb->s_mtime = 0;
160	sb->s_wtime = 0;
161	sb->s_mnt_count = 0;
162	sb->s_max_mnt_count = 0xFFFF;
163	sb->s_magic = EXT4_SUPER_MAGIC;
164	sb->s_state = EXT4_VALID_FS;
165	sb->s_errors = EXT4_ERRORS_RO;
166	sb->s_minor_rev_level = 0;
167	sb->s_lastcheck = 0;
168	sb->s_checkinterval = 0;
169	sb->s_creator_os = EXT4_OS_LINUX;
170	sb->s_rev_level = EXT4_DYNAMIC_REV;
171	sb->s_def_resuid = EXT4_DEF_RESUID;
172	sb->s_def_resgid = EXT4_DEF_RESGID;
173
174	sb->s_first_ino = EXT4_GOOD_OLD_FIRST_INO;
175	sb->s_inode_size = info.inode_size;
176	sb->s_block_group_nr = 0;
177	sb->s_feature_compat = info.feat_compat;
178	sb->s_feature_incompat = info.feat_incompat;
179	sb->s_feature_ro_compat = info.feat_ro_compat;
180	generate_uuid("extandroid/make_ext4fs", info.label, sb->s_uuid);
181	memset(sb->s_volume_name, 0, sizeof(sb->s_volume_name));
182	strncpy(sb->s_volume_name, info.label, sizeof(sb->s_volume_name));
183	memset(sb->s_last_mounted, 0, sizeof(sb->s_last_mounted));
184	sb->s_algorithm_usage_bitmap = 0;
185
186	sb->s_reserved_gdt_blocks = info.bg_desc_reserve_blocks;
187	sb->s_prealloc_blocks = 0;
188	sb->s_prealloc_dir_blocks = 0;
189
190	//memcpy(sb->s_journal_uuid, sb->s_uuid, sizeof(sb->s_journal_uuid));
191	if (info.feat_compat & EXT4_FEATURE_COMPAT_HAS_JOURNAL)
192		sb->s_journal_inum = EXT4_JOURNAL_INO;
193	sb->s_journal_dev = 0;
194	sb->s_last_orphan = 0;
195	sb->s_hash_seed[0] = 0; /* FIXME */
196	sb->s_def_hash_version = DX_HASH_TEA;
197	sb->s_reserved_char_pad = EXT4_JNL_BACKUP_BLOCKS;
198	sb->s_desc_size = sizeof(struct ext2_group_desc);
199	sb->s_default_mount_opts = 0; /* FIXME */
200	sb->s_first_meta_bg = 0;
201	sb->s_mkfs_time = 0;
202	//sb->s_jnl_blocks[17]; /* FIXME */
203
204	sb->s_blocks_count_hi = aux_info.len_blocks >> 32;
205	sb->s_r_blocks_count_hi = 0;
206	sb->s_free_blocks_count_hi = 0;
207	sb->s_min_extra_isize = sizeof(struct ext4_inode) -
208		EXT4_GOOD_OLD_INODE_SIZE;
209	sb->s_want_extra_isize = sizeof(struct ext4_inode) -
210		EXT4_GOOD_OLD_INODE_SIZE;
211	sb->s_flags = 2;
212	sb->s_raid_stride = 0;
213	sb->s_mmp_interval = 0;
214	sb->s_mmp_block = 0;
215	sb->s_raid_stripe_width = 0;
216	sb->s_log_groups_per_flex = 0;
217	sb->s_kbytes_written = 0;
218
219	for (i = 0; i < aux_info.groups; i++) {
220		u64 group_start_block = aux_info.first_data_block + i *
221			info.blocks_per_group;
222		u32 header_size = 0;
223		if (ext4_bg_has_super_block(i)) {
224			if (i != 0) {
225				aux_info.backup_sb[i] = calloc(info.block_size, 1);
226				memcpy(aux_info.backup_sb[i], sb, info.block_size);
227				/* Update the block group nr of this backup superblock */
228				aux_info.backup_sb[i]->s_block_group_nr = i;
229				sparse_file_add_data(ext4_sparse_file, aux_info.backup_sb[i],
230						info.block_size, group_start_block);
231			}
232			sparse_file_add_data(ext4_sparse_file, aux_info.bg_desc,
233				aux_info.bg_desc_blocks * info.block_size,
234				group_start_block + 1);
235			header_size = 1 + aux_info.bg_desc_blocks + info.bg_desc_reserve_blocks;
236		}
237
238		aux_info.bg_desc[i].bg_block_bitmap = group_start_block + header_size;
239		aux_info.bg_desc[i].bg_inode_bitmap = group_start_block + header_size + 1;
240		aux_info.bg_desc[i].bg_inode_table = group_start_block + header_size + 2;
241
242		aux_info.bg_desc[i].bg_free_blocks_count = sb->s_blocks_per_group;
243		aux_info.bg_desc[i].bg_free_inodes_count = sb->s_inodes_per_group;
244		aux_info.bg_desc[i].bg_used_dirs_count = 0;
245	}
246}
247
248void ext4_queue_sb(void)
249{
250	/* The write_data* functions expect only block aligned calls.
251	 * This is not an issue, except when we write out the super
252	 * block on a system with a block size > 1K.  So, we need to
253	 * deal with that here.
254	 */
255	if (info.block_size > 1024) {
256		u8 *buf = calloc(info.block_size, 1);
257		memcpy(buf + 1024, (u8*)aux_info.sb, 1024);
258		sparse_file_add_data(ext4_sparse_file, buf, info.block_size, 0);
259	} else {
260		sparse_file_add_data(ext4_sparse_file, aux_info.sb, 1024, 1);
261	}
262}
263
264void ext4_parse_sb_info(struct ext4_super_block *sb)
265{
266	if (sb->s_magic != EXT4_SUPER_MAGIC)
267		error("superblock magic incorrect");
268
269	if ((sb->s_state & EXT4_VALID_FS) != EXT4_VALID_FS)
270		error("filesystem state not valid");
271
272	ext4_parse_sb(sb, &info);
273
274	ext4_create_fs_aux_info();
275
276	memcpy(aux_info.sb, sb, sizeof(*sb));
277
278	if (aux_info.first_data_block != sb->s_first_data_block)
279		critical_error("first data block does not match");
280}
281
282void ext4_create_resize_inode()
283{
284	struct block_allocation *reserve_inode_alloc = create_allocation();
285	u32 reserve_inode_len = 0;
286	unsigned int i;
287
288	struct ext4_inode *inode = get_inode(EXT4_RESIZE_INO);
289	if (inode == NULL) {
290		error("failed to get resize inode");
291		return;
292	}
293
294	for (i = 0; i < aux_info.groups; i++) {
295		if (ext4_bg_has_super_block(i)) {
296			u64 group_start_block = aux_info.first_data_block + i *
297				info.blocks_per_group;
298			u32 reserved_block_start = group_start_block + 1 +
299				aux_info.bg_desc_blocks;
300			u32 reserved_block_len = info.bg_desc_reserve_blocks;
301			append_region(reserve_inode_alloc, reserved_block_start,
302				reserved_block_len, i);
303			reserve_inode_len += reserved_block_len;
304		}
305	}
306
307	inode_attach_resize(inode, reserve_inode_alloc);
308
309	inode->i_mode = S_IFREG | S_IRUSR | S_IWUSR;
310	inode->i_links_count = 1;
311
312	free_alloc(reserve_inode_alloc);
313}
314
315/* Allocate the blocks to hold a journal inode and connect them to the
316   reserved journal inode */
317void ext4_create_journal_inode()
318{
319	struct ext4_inode *inode = get_inode(EXT4_JOURNAL_INO);
320	if (inode == NULL) {
321		error("failed to get journal inode");
322		return;
323	}
324
325	u8 *journal_data = inode_allocate_data_extents(inode,
326			info.journal_blocks * info.block_size,
327			info.journal_blocks * info.block_size);
328	if (!journal_data) {
329		error("failed to allocate extents for journal data");
330		return;
331	}
332
333	inode->i_mode = S_IFREG | S_IRUSR | S_IWUSR;
334	inode->i_links_count = 1;
335
336	journal_superblock_t *jsb = (journal_superblock_t *)journal_data;
337	jsb->s_header.h_magic = htonl(JBD2_MAGIC_NUMBER);
338	jsb->s_header.h_blocktype = htonl(JBD2_SUPERBLOCK_V2);
339	jsb->s_blocksize = htonl(info.block_size);
340	jsb->s_maxlen = htonl(info.journal_blocks);
341	jsb->s_nr_users = htonl(1);
342	jsb->s_first = htonl(1);
343	jsb->s_sequence = htonl(1);
344
345	memcpy(aux_info.sb->s_jnl_blocks, &inode->i_block, sizeof(inode->i_block));
346}
347
348/* Update the number of free blocks and inodes in the filesystem and in each
349   block group */
350void ext4_update_free()
351{
352	u32 i;
353
354	for (i = 0; i < aux_info.groups; i++) {
355		u32 bg_free_blocks = get_free_blocks(i);
356		u32 bg_free_inodes = get_free_inodes(i);
357		u16 crc;
358
359		aux_info.bg_desc[i].bg_free_blocks_count = bg_free_blocks;
360		aux_info.sb->s_free_blocks_count_lo += bg_free_blocks;
361
362		aux_info.bg_desc[i].bg_free_inodes_count = bg_free_inodes;
363		aux_info.sb->s_free_inodes_count += bg_free_inodes;
364
365		aux_info.bg_desc[i].bg_used_dirs_count += get_directories(i);
366
367		aux_info.bg_desc[i].bg_flags = get_bg_flags(i);
368
369		crc = ext4_crc16(~0, aux_info.sb->s_uuid, sizeof(aux_info.sb->s_uuid));
370		crc = ext4_crc16(crc, &i, sizeof(i));
371		crc = ext4_crc16(crc, &aux_info.bg_desc[i], offsetof(struct ext2_group_desc, bg_checksum));
372		aux_info.bg_desc[i].bg_checksum = crc;
373	}
374}
375
376u64 get_block_device_size(int fd)
377{
378	u64 size = 0;
379	int ret;
380
381#if defined(__linux__)
382	ret = ioctl(fd, BLKGETSIZE64, &size);
383#elif defined(__APPLE__) && defined(__MACH__)
384	ret = ioctl(fd, DKIOCGETBLOCKCOUNT, &size);
385#else
386	close(fd);
387	return 0;
388#endif
389
390	if (ret)
391		return 0;
392
393	return size;
394}
395
396int is_block_device_fd(int fd)
397{
398#ifdef USE_MINGW
399	return 0;
400#else
401	struct stat st;
402	int ret = fstat(fd, &st);
403	if (ret < 0)
404		return 0;
405
406	return S_ISBLK(st.st_mode);
407#endif
408}
409
410u64 get_file_size(int fd)
411{
412	struct stat buf;
413	int ret;
414	u64 reserve_len = 0;
415	s64 computed_size;
416
417	ret = fstat(fd, &buf);
418	if (ret)
419		return 0;
420
421	if (info.len < 0)
422		reserve_len = -info.len;
423
424	if (S_ISREG(buf.st_mode))
425		computed_size = buf.st_size - reserve_len;
426	else if (S_ISBLK(buf.st_mode))
427		computed_size = get_block_device_size(fd) - reserve_len;
428	else
429		computed_size = 0;
430
431	if (computed_size < 0) {
432		warn("Computed filesystem size less than 0");
433		computed_size = 0;
434	}
435
436	return computed_size;
437}
438
439u64 parse_num(const char *arg)
440{
441	char *endptr;
442	u64 num = strtoull(arg, &endptr, 10);
443	if (*endptr == 'k' || *endptr == 'K')
444		num *= 1024LL;
445	else if (*endptr == 'm' || *endptr == 'M')
446		num *= 1024LL * 1024LL;
447	else if (*endptr == 'g' || *endptr == 'G')
448		num *= 1024LL * 1024LL * 1024LL;
449
450	return num;
451}
452