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