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