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