1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * (C) Copyright 2011 - 2012 Samsung Electronics
4  * EXT4 filesystem implementation in Uboot by
5  * Uma Shankar <uma.shankar@samsung.com>
6  * Manjunatha C Achar <a.manjunatha@samsung.com>
7  *
8  * ext4ls and ext4load : Based on ext2 ls load support in Uboot.
9  *
10  * (C) Copyright 2004
11  * esd gmbh <www.esd-electronics.com>
12  * Reinhard Arlt <reinhard.arlt@esd-electronics.com>
13  *
14  * based on code from grub2 fs/ext2.c and fs/fshelp.c by
15  * GRUB  --  GRand Unified Bootloader
16  * Copyright (C) 2003, 2004  Free Software Foundation, Inc.
17  *
18  * ext4write : Based on generic ext4 protocol.
19  */
20 
21 #include <blk.h>
22 #include <ext_common.h>
23 #include <ext4fs.h>
24 #include <log.h>
25 #include <malloc.h>
26 #include <memalign.h>
27 #include <part.h>
28 #include <stddef.h>
29 #include <linux/stat.h>
30 #include <linux/time.h>
31 #include <asm/byteorder.h>
32 #include "ext4_common.h"
33 
34 struct ext2_data *ext4fs_root;
35 struct ext2fs_node *ext4fs_file;
36 __le32 *ext4fs_indir1_block;
37 int ext4fs_indir1_size;
38 int ext4fs_indir1_blkno = -1;
39 __le32 *ext4fs_indir2_block;
40 int ext4fs_indir2_size;
41 int ext4fs_indir2_blkno = -1;
42 
43 __le32 *ext4fs_indir3_block;
44 int ext4fs_indir3_size;
45 int ext4fs_indir3_blkno = -1;
46 struct ext2_inode *g_parent_inode;
47 static int symlinknest;
48 
49 #if defined(CONFIG_EXT4_WRITE)
ext4fs_get_group_descriptor(const struct ext_filesystem * fs,uint32_t bg_idx)50 struct ext2_block_group *ext4fs_get_group_descriptor
51 	(const struct ext_filesystem *fs, uint32_t bg_idx)
52 {
53 	return (struct ext2_block_group *)(fs->gdtable + (bg_idx * fs->gdsize));
54 }
55 
ext4fs_sb_free_inodes_dec(struct ext2_sblock * sb)56 static inline void ext4fs_sb_free_inodes_dec(struct ext2_sblock *sb)
57 {
58 	sb->free_inodes = cpu_to_le32(le32_to_cpu(sb->free_inodes) - 1);
59 }
60 
ext4fs_sb_free_blocks_dec(struct ext2_sblock * sb)61 static inline void ext4fs_sb_free_blocks_dec(struct ext2_sblock *sb)
62 {
63 	uint64_t free_blocks = le32_to_cpu(sb->free_blocks);
64 	free_blocks += (uint64_t)le32_to_cpu(sb->free_blocks_high) << 32;
65 	free_blocks--;
66 
67 	sb->free_blocks = cpu_to_le32(free_blocks & 0xffffffff);
68 	sb->free_blocks_high = cpu_to_le16(free_blocks >> 32);
69 }
70 
ext4fs_bg_free_inodes_dec(struct ext2_block_group * bg,const struct ext_filesystem * fs)71 static inline void ext4fs_bg_free_inodes_dec
72 	(struct ext2_block_group *bg, const struct ext_filesystem *fs)
73 {
74 	uint32_t free_inodes = le16_to_cpu(bg->free_inodes);
75 	if (fs->gdsize == 64)
76 		free_inodes += le16_to_cpu(bg->free_inodes_high) << 16;
77 	free_inodes--;
78 
79 	bg->free_inodes = cpu_to_le16(free_inodes & 0xffff);
80 	if (fs->gdsize == 64)
81 		bg->free_inodes_high = cpu_to_le16(free_inodes >> 16);
82 }
83 
ext4fs_bg_free_blocks_dec(struct ext2_block_group * bg,const struct ext_filesystem * fs)84 static inline void ext4fs_bg_free_blocks_dec
85 	(struct ext2_block_group *bg, const struct ext_filesystem *fs)
86 {
87 	uint32_t free_blocks = le16_to_cpu(bg->free_blocks);
88 	if (fs->gdsize == 64)
89 		free_blocks += le16_to_cpu(bg->free_blocks_high) << 16;
90 	free_blocks--;
91 
92 	bg->free_blocks = cpu_to_le16(free_blocks & 0xffff);
93 	if (fs->gdsize == 64)
94 		bg->free_blocks_high = cpu_to_le16(free_blocks >> 16);
95 }
96 
ext4fs_bg_itable_unused_dec(struct ext2_block_group * bg,const struct ext_filesystem * fs)97 static inline void ext4fs_bg_itable_unused_dec
98 	(struct ext2_block_group *bg, const struct ext_filesystem *fs)
99 {
100 	uint32_t free_inodes = le16_to_cpu(bg->bg_itable_unused);
101 	if (fs->gdsize == 64)
102 		free_inodes += le16_to_cpu(bg->bg_itable_unused_high) << 16;
103 	free_inodes--;
104 
105 	bg->bg_itable_unused = cpu_to_le16(free_inodes & 0xffff);
106 	if (fs->gdsize == 64)
107 		bg->bg_itable_unused_high = cpu_to_le16(free_inodes >> 16);
108 }
109 
ext4fs_sb_get_free_blocks(const struct ext2_sblock * sb)110 uint64_t ext4fs_sb_get_free_blocks(const struct ext2_sblock *sb)
111 {
112 	uint64_t free_blocks = le32_to_cpu(sb->free_blocks);
113 	free_blocks += (uint64_t)le32_to_cpu(sb->free_blocks_high) << 32;
114 	return free_blocks;
115 }
116 
ext4fs_sb_set_free_blocks(struct ext2_sblock * sb,uint64_t free_blocks)117 void ext4fs_sb_set_free_blocks(struct ext2_sblock *sb, uint64_t free_blocks)
118 {
119 	sb->free_blocks = cpu_to_le32(free_blocks & 0xffffffff);
120 	sb->free_blocks_high = cpu_to_le16(free_blocks >> 32);
121 }
122 
ext4fs_bg_get_free_blocks(const struct ext2_block_group * bg,const struct ext_filesystem * fs)123 uint32_t ext4fs_bg_get_free_blocks(const struct ext2_block_group *bg,
124 				   const struct ext_filesystem *fs)
125 {
126 	uint32_t free_blocks = le16_to_cpu(bg->free_blocks);
127 	if (fs->gdsize == 64)
128 		free_blocks += le16_to_cpu(bg->free_blocks_high) << 16;
129 	return free_blocks;
130 }
131 
132 static inline
ext4fs_bg_get_free_inodes(const struct ext2_block_group * bg,const struct ext_filesystem * fs)133 uint32_t ext4fs_bg_get_free_inodes(const struct ext2_block_group *bg,
134 				   const struct ext_filesystem *fs)
135 {
136 	uint32_t free_inodes = le16_to_cpu(bg->free_inodes);
137 	if (fs->gdsize == 64)
138 		free_inodes += le16_to_cpu(bg->free_inodes_high) << 16;
139 	return free_inodes;
140 }
141 
ext4fs_bg_get_flags(const struct ext2_block_group * bg)142 static inline uint16_t ext4fs_bg_get_flags(const struct ext2_block_group *bg)
143 {
144 	return le16_to_cpu(bg->bg_flags);
145 }
146 
ext4fs_bg_set_flags(struct ext2_block_group * bg,uint16_t flags)147 static inline void ext4fs_bg_set_flags(struct ext2_block_group *bg,
148 				       uint16_t flags)
149 {
150 	bg->bg_flags = cpu_to_le16(flags);
151 }
152 
153 /* Block number of the block bitmap */
ext4fs_bg_get_block_id(const struct ext2_block_group * bg,const struct ext_filesystem * fs)154 uint64_t ext4fs_bg_get_block_id(const struct ext2_block_group *bg,
155 				const struct ext_filesystem *fs)
156 {
157 	uint64_t block_nr = le32_to_cpu(bg->block_id);
158 	if (fs->gdsize == 64)
159 		block_nr += (uint64_t)le32_to_cpu(bg->block_id_high) << 32;
160 	return block_nr;
161 }
162 
163 /* Block number of the inode bitmap */
ext4fs_bg_get_inode_id(const struct ext2_block_group * bg,const struct ext_filesystem * fs)164 uint64_t ext4fs_bg_get_inode_id(const struct ext2_block_group *bg,
165 				const struct ext_filesystem *fs)
166 {
167 	uint64_t block_nr = le32_to_cpu(bg->inode_id);
168 	if (fs->gdsize == 64)
169 		block_nr += (uint64_t)le32_to_cpu(bg->inode_id_high) << 32;
170 	return block_nr;
171 }
172 #endif
173 
174 /* Block number of the inode table */
ext4fs_bg_get_inode_table_id(const struct ext2_block_group * bg,const struct ext_filesystem * fs)175 uint64_t ext4fs_bg_get_inode_table_id(const struct ext2_block_group *bg,
176 				      const struct ext_filesystem *fs)
177 {
178 	uint64_t block_nr = le32_to_cpu(bg->inode_table_id);
179 	if (fs->gdsize == 64)
180 		block_nr +=
181 			(uint64_t)le32_to_cpu(bg->inode_table_id_high) << 32;
182 	return block_nr;
183 }
184 
185 #if defined(CONFIG_EXT4_WRITE)
ext4fs_div_roundup(uint32_t size,uint32_t n)186 uint32_t ext4fs_div_roundup(uint32_t size, uint32_t n)
187 {
188 	uint32_t res = size / n;
189 	if (res * n != size)
190 		res++;
191 
192 	return res;
193 }
194 
put_ext4(uint64_t off,const void * buf,uint32_t size)195 void put_ext4(uint64_t off, const void *buf, uint32_t size)
196 {
197 	uint64_t startblock;
198 	uint64_t remainder;
199 	unsigned char *temp_ptr = NULL;
200 	struct ext_filesystem *fs = get_fs();
201 	int log2blksz;
202 
203 	if (!fs->dev_desc)
204 		return;
205 
206 	ALLOC_CACHE_ALIGN_BUFFER(unsigned char, sec_buf, fs->dev_desc->blksz);
207 
208 	log2blksz = fs->dev_desc->log2blksz;
209 	startblock = off >> log2blksz;
210 	startblock += part_offset;
211 	remainder = off & (uint64_t)(fs->dev_desc->blksz - 1);
212 
213 	if ((startblock + (size >> log2blksz)) >
214 	    (part_offset + fs->total_sect)) {
215 		printf("part_offset is " LBAFU "\n", part_offset);
216 		printf("total_sector is %llu\n", fs->total_sect);
217 		printf("error: overflow occurs\n");
218 		return;
219 	}
220 
221 	if (remainder) {
222 		blk_dread(fs->dev_desc, startblock, 1, sec_buf);
223 		temp_ptr = sec_buf;
224 		memcpy((temp_ptr + remainder), (unsigned char *)buf, size);
225 		blk_dwrite(fs->dev_desc, startblock, 1, sec_buf);
226 	} else {
227 		if (size >> log2blksz != 0) {
228 			blk_dwrite(fs->dev_desc, startblock, size >> log2blksz,
229 				   (unsigned long *)buf);
230 		} else {
231 			blk_dread(fs->dev_desc, startblock, 1, sec_buf);
232 			temp_ptr = sec_buf;
233 			memcpy(temp_ptr, buf, size);
234 			blk_dwrite(fs->dev_desc, startblock, 1,
235 				   (unsigned long *)sec_buf);
236 		}
237 	}
238 }
239 
_get_new_inode_no(unsigned char * buffer)240 static int _get_new_inode_no(unsigned char *buffer)
241 {
242 	struct ext_filesystem *fs = get_fs();
243 	unsigned char input;
244 	int operand, status;
245 	int count = 1;
246 	int j = 0;
247 
248 	/* get the blocksize of the filesystem */
249 	unsigned char *ptr = buffer;
250 	while (*ptr == 255) {
251 		ptr++;
252 		count += 8;
253 		if (count > le32_to_cpu(ext4fs_root->sblock.inodes_per_group))
254 			return -1;
255 	}
256 
257 	for (j = 0; j < fs->blksz; j++) {
258 		input = *ptr;
259 		int i = 0;
260 		while (i <= 7) {
261 			operand = 1 << i;
262 			status = input & operand;
263 			if (status) {
264 				i++;
265 				count++;
266 			} else {
267 				*ptr |= operand;
268 				return count;
269 			}
270 		}
271 		ptr = ptr + 1;
272 	}
273 
274 	return -1;
275 }
276 
_get_new_blk_no(unsigned char * buffer)277 static int _get_new_blk_no(unsigned char *buffer)
278 {
279 	int operand;
280 	int count = 0;
281 	int i;
282 	unsigned char *ptr = buffer;
283 	struct ext_filesystem *fs = get_fs();
284 
285 	while (*ptr == 255) {
286 		ptr++;
287 		count += 8;
288 		if (count == (fs->blksz * 8))
289 			return -1;
290 	}
291 
292 	if (fs->blksz == 1024)
293 		count += 1;
294 
295 	for (i = 0; i <= 7; i++) {
296 		operand = 1 << i;
297 		if (*ptr & operand) {
298 			count++;
299 		} else {
300 			*ptr |= operand;
301 			return count;
302 		}
303 	}
304 
305 	return -1;
306 }
307 
ext4fs_set_block_bmap(long int blockno,unsigned char * buffer,int index)308 int ext4fs_set_block_bmap(long int blockno, unsigned char *buffer, int index)
309 {
310 	int i, remainder, status;
311 	unsigned char *ptr = buffer;
312 	unsigned char operand;
313 	i = blockno / 8;
314 	remainder = blockno % 8;
315 	int blocksize = EXT2_BLOCK_SIZE(ext4fs_root);
316 
317 	i = i - (index * blocksize);
318 	if (blocksize != 1024) {
319 		ptr = ptr + i;
320 		operand = 1 << remainder;
321 		status = *ptr & operand;
322 		if (status)
323 			return -1;
324 
325 		*ptr = *ptr | operand;
326 		return 0;
327 	} else {
328 		if (remainder == 0) {
329 			ptr = ptr + i - 1;
330 			operand = (1 << 7);
331 		} else {
332 			ptr = ptr + i;
333 			operand = (1 << (remainder - 1));
334 		}
335 		status = *ptr & operand;
336 		if (status)
337 			return -1;
338 
339 		*ptr = *ptr | operand;
340 		return 0;
341 	}
342 }
343 
ext4fs_reset_block_bmap(long int blockno,unsigned char * buffer,int index)344 void ext4fs_reset_block_bmap(long int blockno, unsigned char *buffer, int index)
345 {
346 	int i, remainder, status;
347 	unsigned char *ptr = buffer;
348 	unsigned char operand;
349 	i = blockno / 8;
350 	remainder = blockno % 8;
351 	int blocksize = EXT2_BLOCK_SIZE(ext4fs_root);
352 
353 	i = i - (index * blocksize);
354 	if (blocksize != 1024) {
355 		ptr = ptr + i;
356 		operand = (1 << remainder);
357 		status = *ptr & operand;
358 		if (status)
359 			*ptr = *ptr & ~(operand);
360 	} else {
361 		if (remainder == 0) {
362 			ptr = ptr + i - 1;
363 			operand = (1 << 7);
364 		} else {
365 			ptr = ptr + i;
366 			operand = (1 << (remainder - 1));
367 		}
368 		status = *ptr & operand;
369 		if (status)
370 			*ptr = *ptr & ~(operand);
371 	}
372 }
373 
ext4fs_set_inode_bmap(int inode_no,unsigned char * buffer,int index)374 int ext4fs_set_inode_bmap(int inode_no, unsigned char *buffer, int index)
375 {
376 	int i, remainder, status;
377 	unsigned char *ptr = buffer;
378 	unsigned char operand;
379 
380 	inode_no -= (index * le32_to_cpu(ext4fs_root->sblock.inodes_per_group));
381 	i = inode_no / 8;
382 	remainder = inode_no % 8;
383 	if (remainder == 0) {
384 		ptr = ptr + i - 1;
385 		operand = (1 << 7);
386 	} else {
387 		ptr = ptr + i;
388 		operand = (1 << (remainder - 1));
389 	}
390 	status = *ptr & operand;
391 	if (status)
392 		return -1;
393 
394 	*ptr = *ptr | operand;
395 
396 	return 0;
397 }
398 
ext4fs_reset_inode_bmap(int inode_no,unsigned char * buffer,int index)399 void ext4fs_reset_inode_bmap(int inode_no, unsigned char *buffer, int index)
400 {
401 	int i, remainder, status;
402 	unsigned char *ptr = buffer;
403 	unsigned char operand;
404 
405 	inode_no -= (index * le32_to_cpu(ext4fs_root->sblock.inodes_per_group));
406 	i = inode_no / 8;
407 	remainder = inode_no % 8;
408 	if (remainder == 0) {
409 		ptr = ptr + i - 1;
410 		operand = (1 << 7);
411 	} else {
412 		ptr = ptr + i;
413 		operand = (1 << (remainder - 1));
414 	}
415 	status = *ptr & operand;
416 	if (status)
417 		*ptr = *ptr & ~(operand);
418 }
419 
ext4fs_checksum_update(uint32_t i)420 uint16_t ext4fs_checksum_update(uint32_t i)
421 {
422 	struct ext2_block_group *desc;
423 	struct ext_filesystem *fs = get_fs();
424 	uint16_t crc = 0;
425 	__le32 le32_i = cpu_to_le32(i);
426 
427 	desc = ext4fs_get_group_descriptor(fs, i);
428 	if (le32_to_cpu(fs->sb->feature_ro_compat) & EXT4_FEATURE_RO_COMPAT_GDT_CSUM) {
429 		int offset = offsetof(struct ext2_block_group, bg_checksum);
430 
431 		crc = crc16(~0, (__u8 *)fs->sb->unique_id,
432 				   sizeof(fs->sb->unique_id));
433 		crc = crc16(crc, (__u8 *)&le32_i, sizeof(le32_i));
434 		crc = crc16(crc, (__u8 *)desc, offset);
435 		offset += sizeof(desc->bg_checksum);	/* skip checksum */
436 		assert(offset == sizeof(*desc));
437 		if (offset < fs->gdsize) {
438 			crc = crc16(crc, (__u8 *)desc + offset,
439 					   fs->gdsize - offset);
440 		}
441 	}
442 
443 	return crc;
444 }
445 
check_void_in_dentry(struct ext2_dirent * dir,char * filename)446 static int check_void_in_dentry(struct ext2_dirent *dir, char *filename)
447 {
448 	int dentry_length;
449 	int sizeof_void_space;
450 	int new_entry_byte_reqd;
451 	short padding_factor = 0;
452 
453 	if (dir->namelen % 4 != 0)
454 		padding_factor = 4 - (dir->namelen % 4);
455 
456 	dentry_length = sizeof(struct ext2_dirent) +
457 			dir->namelen + padding_factor;
458 	sizeof_void_space = le16_to_cpu(dir->direntlen) - dentry_length;
459 	if (sizeof_void_space == 0)
460 		return 0;
461 
462 	padding_factor = 0;
463 	if (strlen(filename) % 4 != 0)
464 		padding_factor = 4 - (strlen(filename) % 4);
465 
466 	new_entry_byte_reqd = strlen(filename) +
467 	    sizeof(struct ext2_dirent) + padding_factor;
468 	if (sizeof_void_space >= new_entry_byte_reqd) {
469 		dir->direntlen = cpu_to_le16(dentry_length);
470 		return sizeof_void_space;
471 	}
472 
473 	return 0;
474 }
475 
ext4fs_update_parent_dentry(char * filename,int file_type)476 int ext4fs_update_parent_dentry(char *filename, int file_type)
477 {
478 	unsigned int *zero_buffer = NULL;
479 	char *root_first_block_buffer = NULL;
480 	int blk_idx;
481 	long int first_block_no_of_root = 0;
482 	int totalbytes = 0;
483 	unsigned int new_entry_byte_reqd;
484 	int sizeof_void_space = 0;
485 	int templength = 0;
486 	int inodeno = -1;
487 	int status;
488 	struct ext_filesystem *fs = get_fs();
489 	/* directory entry */
490 	struct ext2_dirent *dir;
491 	char *temp_dir = NULL;
492 	uint32_t new_blk_no;
493 	uint32_t new_size;
494 	uint32_t new_blockcnt;
495 	uint32_t directory_blocks;
496 
497 	zero_buffer = zalloc(fs->blksz);
498 	if (!zero_buffer) {
499 		printf("No Memory\n");
500 		return -1;
501 	}
502 	root_first_block_buffer = zalloc(fs->blksz);
503 	if (!root_first_block_buffer) {
504 		free(zero_buffer);
505 		printf("No Memory\n");
506 		return -1;
507 	}
508 	new_entry_byte_reqd = ROUND(strlen(filename) +
509 				    sizeof(struct ext2_dirent), 4);
510 restart:
511 	directory_blocks = le32_to_cpu(g_parent_inode->size) >>
512 		LOG2_BLOCK_SIZE(ext4fs_root);
513 	blk_idx = directory_blocks - 1;
514 
515 restart_read:
516 	/* read the block no allocated to a file */
517 	first_block_no_of_root = read_allocated_block(g_parent_inode, blk_idx,
518 						      NULL);
519 	if (first_block_no_of_root <= 0)
520 		goto fail;
521 
522 	status = ext4fs_devread((lbaint_t)first_block_no_of_root
523 				* fs->sect_perblk,
524 				0, fs->blksz, root_first_block_buffer);
525 	if (status == 0)
526 		goto fail;
527 
528 	if (ext4fs_log_journal(root_first_block_buffer, first_block_no_of_root))
529 		goto fail;
530 	dir = (struct ext2_dirent *)root_first_block_buffer;
531 	totalbytes = 0;
532 
533 	while (le16_to_cpu(dir->direntlen) > 0) {
534 		unsigned short used_len = ROUND(dir->namelen +
535 		    sizeof(struct ext2_dirent), 4);
536 
537 		/* last entry of block */
538 		if (fs->blksz - totalbytes == le16_to_cpu(dir->direntlen)) {
539 
540 			/* check if new entry fits */
541 			if ((used_len + new_entry_byte_reqd) <=
542 			    le16_to_cpu(dir->direntlen)) {
543 				dir->direntlen = cpu_to_le16(used_len);
544 				break;
545 			} else {
546 				if (blk_idx > 0) {
547 					printf("Block full, trying previous\n");
548 					blk_idx--;
549 					goto restart_read;
550 				}
551 				printf("All blocks full: Allocate new\n");
552 
553 				if (le32_to_cpu(g_parent_inode->flags) &
554 						EXT4_EXTENTS_FL) {
555 					printf("Directory uses extents\n");
556 					goto fail;
557 				}
558 				if (directory_blocks >= INDIRECT_BLOCKS) {
559 					printf("Directory exceeds limit\n");
560 					goto fail;
561 				}
562 				new_blk_no = ext4fs_get_new_blk_no();
563 				if (new_blk_no == -1) {
564 					printf("no block left to assign\n");
565 					goto fail;
566 				}
567 				put_ext4((uint64_t)new_blk_no * fs->blksz, zero_buffer, fs->blksz);
568 				g_parent_inode->b.blocks.
569 					dir_blocks[directory_blocks] =
570 					cpu_to_le32(new_blk_no);
571 
572 				new_size = le32_to_cpu(g_parent_inode->size);
573 				new_size += fs->blksz;
574 				g_parent_inode->size = cpu_to_le32(new_size);
575 
576 				new_blockcnt = le32_to_cpu(g_parent_inode->blockcnt);
577 				new_blockcnt += fs->blksz >> LOG2_SECTOR_SIZE;
578 				g_parent_inode->blockcnt = cpu_to_le32(new_blockcnt);
579 
580 				if (ext4fs_put_metadata
581 				    (root_first_block_buffer,
582 				     first_block_no_of_root))
583 					goto fail;
584 				goto restart;
585 			}
586 		}
587 
588 		templength = le16_to_cpu(dir->direntlen);
589 		totalbytes = totalbytes + templength;
590 		sizeof_void_space = check_void_in_dentry(dir, filename);
591 		if (sizeof_void_space)
592 			break;
593 
594 		dir = (struct ext2_dirent *)((char *)dir + templength);
595 	}
596 
597 	/* make a pointer ready for creating next directory entry */
598 	templength = le16_to_cpu(dir->direntlen);
599 	totalbytes = totalbytes + templength;
600 	dir = (struct ext2_dirent *)((char *)dir + templength);
601 
602 	/* get the next available inode number */
603 	inodeno = ext4fs_get_new_inode_no();
604 	if (inodeno == -1) {
605 		printf("no inode left to assign\n");
606 		goto fail;
607 	}
608 	dir->inode = cpu_to_le32(inodeno);
609 	if (sizeof_void_space)
610 		dir->direntlen = cpu_to_le16(sizeof_void_space);
611 	else
612 		dir->direntlen = cpu_to_le16(fs->blksz - totalbytes);
613 
614 	dir->namelen = strlen(filename);
615 	dir->filetype = file_type;
616 	temp_dir = (char *)dir;
617 	temp_dir = temp_dir + sizeof(struct ext2_dirent);
618 	memcpy(temp_dir, filename, strlen(filename));
619 
620 	/* update or write  the 1st block of root inode */
621 	if (ext4fs_put_metadata(root_first_block_buffer,
622 				first_block_no_of_root))
623 		goto fail;
624 
625 fail:
626 	free(zero_buffer);
627 	free(root_first_block_buffer);
628 
629 	return inodeno;
630 }
631 
search_dir(struct ext2_inode * parent_inode,char * dirname)632 static int search_dir(struct ext2_inode *parent_inode, char *dirname)
633 {
634 	int status;
635 	int inodeno = 0;
636 	int offset;
637 	int blk_idx;
638 	long int blknr;
639 	char *block_buffer = NULL;
640 	struct ext2_dirent *dir = NULL;
641 	struct ext_filesystem *fs = get_fs();
642 	uint32_t directory_blocks;
643 	char *direntname;
644 
645 	directory_blocks = le32_to_cpu(parent_inode->size) >>
646 		LOG2_BLOCK_SIZE(ext4fs_root);
647 
648 	block_buffer = zalloc(fs->blksz);
649 	if (!block_buffer)
650 		goto fail;
651 
652 	/* get the block no allocated to a file */
653 	for (blk_idx = 0; blk_idx < directory_blocks; blk_idx++) {
654 		blknr = read_allocated_block(parent_inode, blk_idx, NULL);
655 		if (blknr <= 0)
656 			goto fail;
657 
658 		/* read the directory block */
659 		status = ext4fs_devread((lbaint_t)blknr * fs->sect_perblk,
660 					0, fs->blksz, (char *)block_buffer);
661 		if (status == 0)
662 			goto fail;
663 
664 		offset = 0;
665 		do {
666 			if (offset & 3) {
667 				printf("Badly aligned ext2_dirent\n");
668 				break;
669 			}
670 
671 			dir = (struct ext2_dirent *)(block_buffer + offset);
672 			direntname = (char*)(dir) + sizeof(struct ext2_dirent);
673 
674 			int direntlen = le16_to_cpu(dir->direntlen);
675 			if (direntlen < sizeof(struct ext2_dirent))
676 				break;
677 
678 			if (dir->inode && (strlen(dirname) == dir->namelen) &&
679 			    (strncmp(dirname, direntname, dir->namelen) == 0)) {
680 				inodeno = le32_to_cpu(dir->inode);
681 				break;
682 			}
683 
684 			offset += direntlen;
685 
686 		} while (offset < fs->blksz);
687 
688 		if (inodeno > 0) {
689 			free(block_buffer);
690 			return inodeno;
691 		}
692 	}
693 
694 fail:
695 	free(block_buffer);
696 
697 	return -1;
698 }
699 
find_dir_depth(char * dirname)700 static int find_dir_depth(char *dirname)
701 {
702 	char *token = strtok(dirname, "/");
703 	int count = 0;
704 	while (token != NULL) {
705 		token = strtok(NULL, "/");
706 		count++;
707 	}
708 	return count + 1 + 1;
709 	/*
710 	 * for example  for string /home/temp
711 	 * depth=home(1)+temp(1)+1 extra for NULL;
712 	 * so count is 4;
713 	 */
714 }
715 
parse_path(char ** arr,char * dirname)716 static int parse_path(char **arr, char *dirname)
717 {
718 	char *token = strtok(dirname, "/");
719 	int i = 0;
720 
721 	/* add root */
722 	arr[i] = zalloc(strlen("/") + 1);
723 	if (!arr[i])
724 		return -ENOMEM;
725 	memcpy(arr[i++], "/", strlen("/"));
726 
727 	/* add each path entry after root */
728 	while (token != NULL) {
729 		arr[i] = zalloc(strlen(token) + 1);
730 		if (!arr[i])
731 			return -ENOMEM;
732 		memcpy(arr[i++], token, strlen(token));
733 		token = strtok(NULL, "/");
734 	}
735 	arr[i] = NULL;
736 
737 	return 0;
738 }
739 
ext4fs_iget(int inode_no,struct ext2_inode * inode)740 int ext4fs_iget(int inode_no, struct ext2_inode *inode)
741 {
742 	if (ext4fs_read_inode(ext4fs_root, inode_no, inode) == 0)
743 		return -1;
744 
745 	return 0;
746 }
747 
748 /*
749  * Function: ext4fs_get_parent_inode_num
750  * Return Value: inode Number of the parent directory of  file/Directory to be
751  * created
752  * dirname : Input parmater, input path name of the file/directory to be created
753  * dname : Output parameter, to be filled with the name of the directory
754  * extracted from dirname
755  */
ext4fs_get_parent_inode_num(const char * dirname,char * dname,int flags)756 int ext4fs_get_parent_inode_num(const char *dirname, char *dname, int flags)
757 {
758 	int i;
759 	int depth = 0;
760 	int matched_inode_no;
761 	int result_inode_no = -1;
762 	char **ptr = NULL;
763 	char *depth_dirname = NULL;
764 	char *parse_dirname = NULL;
765 	struct ext2_inode *parent_inode = NULL;
766 	struct ext2_inode *first_inode = NULL;
767 	struct ext2_inode temp_inode;
768 
769 	/* TODO: input validation make equivalent to linux */
770 	depth_dirname = zalloc(strlen(dirname) + 1);
771 	if (!depth_dirname)
772 		return -ENOMEM;
773 
774 	memcpy(depth_dirname, dirname, strlen(dirname));
775 	depth = find_dir_depth(depth_dirname);
776 	parse_dirname = zalloc(strlen(dirname) + 1);
777 	if (!parse_dirname)
778 		goto fail;
779 	memcpy(parse_dirname, dirname, strlen(dirname));
780 
781 	/* allocate memory for each directory level */
782 	ptr = zalloc((depth) * sizeof(char *));
783 	if (!ptr)
784 		goto fail;
785 	if (parse_path(ptr, parse_dirname))
786 		goto fail;
787 	parent_inode = zalloc(sizeof(struct ext2_inode));
788 	if (!parent_inode)
789 		goto fail;
790 	first_inode = zalloc(sizeof(struct ext2_inode));
791 	if (!first_inode)
792 		goto fail;
793 	memcpy(parent_inode, ext4fs_root->inode, sizeof(struct ext2_inode));
794 	memcpy(first_inode, parent_inode, sizeof(struct ext2_inode));
795 	if (flags & F_FILE)
796 		result_inode_no = EXT2_ROOT_INO;
797 	for (i = 1; i < depth; i++) {
798 		matched_inode_no = search_dir(parent_inode, ptr[i]);
799 		if (matched_inode_no == -1) {
800 			if (ptr[i + 1] == NULL && i == 1) {
801 				result_inode_no = EXT2_ROOT_INO;
802 				goto end;
803 			} else {
804 				if (ptr[i + 1] == NULL)
805 					break;
806 				printf("Invalid path\n");
807 				result_inode_no = -1;
808 				goto fail;
809 			}
810 		} else {
811 			if (ptr[i + 1] != NULL) {
812 				memset(parent_inode, '\0',
813 				       sizeof(struct ext2_inode));
814 				if (ext4fs_iget(matched_inode_no,
815 						parent_inode)) {
816 					result_inode_no = -1;
817 					goto fail;
818 				}
819 				result_inode_no = matched_inode_no;
820 			} else {
821 				break;
822 			}
823 		}
824 	}
825 
826 end:
827 	if (i == 1)
828 		matched_inode_no = search_dir(first_inode, ptr[i]);
829 	else
830 		matched_inode_no = search_dir(parent_inode, ptr[i]);
831 
832 	if (matched_inode_no != -1) {
833 		ext4fs_iget(matched_inode_no, &temp_inode);
834 		if (le16_to_cpu(temp_inode.mode) & S_IFDIR) {
835 			printf("It is a Directory\n");
836 			result_inode_no = -1;
837 			goto fail;
838 		}
839 	}
840 
841 	if (strlen(ptr[i]) > 256) {
842 		result_inode_no = -1;
843 		goto fail;
844 	}
845 	memcpy(dname, ptr[i], strlen(ptr[i]));
846 
847 fail:
848 	free(depth_dirname);
849 	if (parse_dirname)
850 		free(parse_dirname);
851 	if (ptr) {
852 		for (i = 0; i < depth; i++) {
853 			if (!ptr[i])
854 				break;
855 			free(ptr[i]);
856 		}
857 		free(ptr);
858 	}
859 	if (parent_inode)
860 		free(parent_inode);
861 	if (first_inode)
862 		free(first_inode);
863 
864 	return result_inode_no;
865 }
866 
unlink_filename(char * filename,unsigned int blknr)867 static int unlink_filename(char *filename, unsigned int blknr)
868 {
869 	int status;
870 	int inodeno = 0;
871 	int offset;
872 	char *block_buffer = NULL;
873 	struct ext2_dirent *dir = NULL;
874 	struct ext2_dirent *previous_dir;
875 	struct ext_filesystem *fs = get_fs();
876 	int ret = -1;
877 	char *direntname;
878 
879 	block_buffer = zalloc(fs->blksz);
880 	if (!block_buffer)
881 		return -ENOMEM;
882 
883 	/* read the directory block */
884 	status = ext4fs_devread((lbaint_t)blknr * fs->sect_perblk, 0,
885 				fs->blksz, block_buffer);
886 	if (status == 0)
887 		goto fail;
888 
889 	offset = 0;
890 	do {
891 		if (offset & 3) {
892 			printf("Badly aligned ext2_dirent\n");
893 			break;
894 		}
895 
896 		previous_dir = dir;
897 		dir = (struct ext2_dirent *)(block_buffer + offset);
898 		direntname = (char *)(dir) + sizeof(struct ext2_dirent);
899 
900 		int direntlen = le16_to_cpu(dir->direntlen);
901 		if (direntlen < sizeof(struct ext2_dirent))
902 			break;
903 
904 		if (dir->inode && (strlen(filename) == dir->namelen) &&
905 		    (strncmp(direntname, filename, dir->namelen) == 0)) {
906 			inodeno = le32_to_cpu(dir->inode);
907 			break;
908 		}
909 
910 		offset += direntlen;
911 
912 	} while (offset < fs->blksz);
913 
914 	if (inodeno > 0) {
915 		printf("file found, deleting\n");
916 		if (ext4fs_log_journal(block_buffer, blknr))
917 			goto fail;
918 
919 		if (previous_dir) {
920 			/* merge dir entry with predecessor */
921 			uint16_t new_len;
922 			new_len = le16_to_cpu(previous_dir->direntlen);
923 			new_len += le16_to_cpu(dir->direntlen);
924 			previous_dir->direntlen = cpu_to_le16(new_len);
925 		} else {
926 			/* invalidate dir entry */
927 			dir->inode = 0;
928 		}
929 		if (ext4fs_put_metadata(block_buffer, blknr))
930 			goto fail;
931 		ret = inodeno;
932 	}
933 fail:
934 	free(block_buffer);
935 
936 	return ret;
937 }
938 
ext4fs_filename_unlink(char * filename)939 int ext4fs_filename_unlink(char *filename)
940 {
941 	int blk_idx;
942 	long int blknr = -1;
943 	int inodeno = -1;
944 	uint32_t directory_blocks;
945 
946 	directory_blocks = le32_to_cpu(g_parent_inode->size) >>
947 		LOG2_BLOCK_SIZE(ext4fs_root);
948 
949 	/* read the block no allocated to a file */
950 	for (blk_idx = 0; blk_idx < directory_blocks; blk_idx++) {
951 		blknr = read_allocated_block(g_parent_inode, blk_idx, NULL);
952 		if (blknr <= 0)
953 			break;
954 		inodeno = unlink_filename(filename, blknr);
955 		if (inodeno != -1)
956 			return inodeno;
957 	}
958 
959 	return -1;
960 }
961 
ext4fs_get_new_blk_no(void)962 uint32_t ext4fs_get_new_blk_no(void)
963 {
964 	short i;
965 	short status;
966 	int remainder;
967 	unsigned int bg_idx;
968 	static int prev_bg_bitmap_index = -1;
969 	unsigned int blk_per_grp = le32_to_cpu(ext4fs_root->sblock.blocks_per_group);
970 	struct ext_filesystem *fs = get_fs();
971 	char *journal_buffer = zalloc(fs->blksz);
972 	char *zero_buffer = zalloc(fs->blksz);
973 	if (!journal_buffer || !zero_buffer)
974 		goto fail;
975 
976 	if (fs->first_pass_bbmap == 0) {
977 		for (i = 0; i < fs->no_blkgrp; i++) {
978 			struct ext2_block_group *bgd = NULL;
979 			bgd = ext4fs_get_group_descriptor(fs, i);
980 			if (ext4fs_bg_get_free_blocks(bgd, fs)) {
981 				uint16_t bg_flags = ext4fs_bg_get_flags(bgd);
982 				uint64_t b_bitmap_blk =
983 					ext4fs_bg_get_block_id(bgd, fs);
984 				if (bg_flags & EXT4_BG_BLOCK_UNINIT) {
985 					memcpy(fs->blk_bmaps[i], zero_buffer,
986 					       fs->blksz);
987 					put_ext4(b_bitmap_blk * fs->blksz,
988 						 fs->blk_bmaps[i], fs->blksz);
989 					bg_flags &= ~EXT4_BG_BLOCK_UNINIT;
990 					ext4fs_bg_set_flags(bgd, bg_flags);
991 				}
992 				fs->curr_blkno =
993 				    _get_new_blk_no(fs->blk_bmaps[i]);
994 				if (fs->curr_blkno == -1)
995 					/* block bitmap is completely filled */
996 					continue;
997 				fs->curr_blkno = fs->curr_blkno +
998 						(i * fs->blksz * 8);
999 				fs->first_pass_bbmap++;
1000 				ext4fs_bg_free_blocks_dec(bgd, fs);
1001 				ext4fs_sb_free_blocks_dec(fs->sb);
1002 				status = ext4fs_devread(b_bitmap_blk *
1003 							fs->sect_perblk,
1004 							0, fs->blksz,
1005 							journal_buffer);
1006 				if (status == 0)
1007 					goto fail;
1008 				if (ext4fs_log_journal(journal_buffer,
1009 						       b_bitmap_blk))
1010 					goto fail;
1011 				goto success;
1012 			} else {
1013 				debug("no space left on block group %d\n", i);
1014 			}
1015 		}
1016 
1017 		goto fail;
1018 	} else {
1019 		fs->curr_blkno++;
1020 restart:
1021 		/* get the blockbitmap index respective to blockno */
1022 		bg_idx = fs->curr_blkno / blk_per_grp;
1023 		if (fs->blksz == 1024) {
1024 			remainder = fs->curr_blkno % blk_per_grp;
1025 			if (!remainder)
1026 				bg_idx--;
1027 		}
1028 
1029 		/*
1030 		 * To skip completely filled block group bitmaps
1031 		 * Optimize the block allocation
1032 		 */
1033 		if (bg_idx >= fs->no_blkgrp)
1034 			goto fail;
1035 
1036 		struct ext2_block_group *bgd = NULL;
1037 		bgd = ext4fs_get_group_descriptor(fs, bg_idx);
1038 		if (ext4fs_bg_get_free_blocks(bgd, fs) == 0) {
1039 			debug("block group %u is full. Skipping\n", bg_idx);
1040 			fs->curr_blkno = (bg_idx + 1) * blk_per_grp;
1041 			if (fs->blksz == 1024)
1042 				fs->curr_blkno += 1;
1043 			goto restart;
1044 		}
1045 
1046 		uint16_t bg_flags = ext4fs_bg_get_flags(bgd);
1047 		uint64_t b_bitmap_blk = ext4fs_bg_get_block_id(bgd, fs);
1048 		if (bg_flags & EXT4_BG_BLOCK_UNINIT) {
1049 			memcpy(fs->blk_bmaps[bg_idx], zero_buffer, fs->blksz);
1050 			put_ext4(b_bitmap_blk * fs->blksz,
1051 				 zero_buffer, fs->blksz);
1052 			bg_flags &= ~EXT4_BG_BLOCK_UNINIT;
1053 			ext4fs_bg_set_flags(bgd, bg_flags);
1054 		}
1055 
1056 		if (ext4fs_set_block_bmap(fs->curr_blkno, fs->blk_bmaps[bg_idx],
1057 				   bg_idx) != 0) {
1058 			debug("going for restart for the block no %ld %u\n",
1059 			      fs->curr_blkno, bg_idx);
1060 			fs->curr_blkno++;
1061 			goto restart;
1062 		}
1063 
1064 		/* journal backup */
1065 		if (prev_bg_bitmap_index != bg_idx) {
1066 			status = ext4fs_devread(b_bitmap_blk * fs->sect_perblk,
1067 						0, fs->blksz, journal_buffer);
1068 			if (status == 0)
1069 				goto fail;
1070 			if (ext4fs_log_journal(journal_buffer, b_bitmap_blk))
1071 				goto fail;
1072 
1073 			prev_bg_bitmap_index = bg_idx;
1074 		}
1075 		ext4fs_bg_free_blocks_dec(bgd, fs);
1076 		ext4fs_sb_free_blocks_dec(fs->sb);
1077 		goto success;
1078 	}
1079 success:
1080 	free(journal_buffer);
1081 	free(zero_buffer);
1082 
1083 	return fs->curr_blkno;
1084 fail:
1085 	free(journal_buffer);
1086 	free(zero_buffer);
1087 
1088 	return -1;
1089 }
1090 
ext4fs_get_new_inode_no(void)1091 int ext4fs_get_new_inode_no(void)
1092 {
1093 	short i;
1094 	short status;
1095 	unsigned int ibmap_idx;
1096 	static int prev_inode_bitmap_index = -1;
1097 	unsigned int inodes_per_grp = le32_to_cpu(ext4fs_root->sblock.inodes_per_group);
1098 	struct ext_filesystem *fs = get_fs();
1099 	char *journal_buffer = zalloc(fs->blksz);
1100 	char *zero_buffer = zalloc(fs->blksz);
1101 	if (!journal_buffer || !zero_buffer)
1102 		goto fail;
1103 	int has_gdt_chksum = le32_to_cpu(fs->sb->feature_ro_compat) &
1104 		EXT4_FEATURE_RO_COMPAT_GDT_CSUM ? 1 : 0;
1105 
1106 	if (fs->first_pass_ibmap == 0) {
1107 		for (i = 0; i < fs->no_blkgrp; i++) {
1108 			uint32_t free_inodes;
1109 			struct ext2_block_group *bgd = NULL;
1110 			bgd = ext4fs_get_group_descriptor(fs, i);
1111 			free_inodes = ext4fs_bg_get_free_inodes(bgd, fs);
1112 			if (free_inodes) {
1113 				uint16_t bg_flags = ext4fs_bg_get_flags(bgd);
1114 				uint64_t i_bitmap_blk =
1115 					ext4fs_bg_get_inode_id(bgd, fs);
1116 				if (has_gdt_chksum)
1117 					bgd->bg_itable_unused = free_inodes;
1118 				if (bg_flags & EXT4_BG_INODE_UNINIT) {
1119 					put_ext4(i_bitmap_blk * fs->blksz,
1120 						 zero_buffer, fs->blksz);
1121 					bg_flags &= ~EXT4_BG_INODE_UNINIT;
1122 					ext4fs_bg_set_flags(bgd, bg_flags);
1123 					memcpy(fs->inode_bmaps[i],
1124 					       zero_buffer, fs->blksz);
1125 				}
1126 				fs->curr_inode_no =
1127 				    _get_new_inode_no(fs->inode_bmaps[i]);
1128 				if (fs->curr_inode_no == -1)
1129 					/* inode bitmap is completely filled */
1130 					continue;
1131 				fs->curr_inode_no = fs->curr_inode_no +
1132 							(i * inodes_per_grp);
1133 				fs->first_pass_ibmap++;
1134 				ext4fs_bg_free_inodes_dec(bgd, fs);
1135 				if (has_gdt_chksum)
1136 					ext4fs_bg_itable_unused_dec(bgd, fs);
1137 				ext4fs_sb_free_inodes_dec(fs->sb);
1138 				status = ext4fs_devread(i_bitmap_blk *
1139 							fs->sect_perblk,
1140 							0, fs->blksz,
1141 							journal_buffer);
1142 				if (status == 0)
1143 					goto fail;
1144 				if (ext4fs_log_journal(journal_buffer,
1145 						       i_bitmap_blk))
1146 					goto fail;
1147 				goto success;
1148 			} else
1149 				debug("no inode left on block group %d\n", i);
1150 		}
1151 		goto fail;
1152 	} else {
1153 restart:
1154 		fs->curr_inode_no++;
1155 		/* get the blockbitmap index respective to blockno */
1156 		ibmap_idx = fs->curr_inode_no / inodes_per_grp;
1157 		struct ext2_block_group *bgd =
1158 			ext4fs_get_group_descriptor(fs, ibmap_idx);
1159 		uint16_t bg_flags = ext4fs_bg_get_flags(bgd);
1160 		uint64_t i_bitmap_blk = ext4fs_bg_get_inode_id(bgd, fs);
1161 
1162 		if (bg_flags & EXT4_BG_INODE_UNINIT) {
1163 			put_ext4(i_bitmap_blk * fs->blksz,
1164 				 zero_buffer, fs->blksz);
1165 			bg_flags &= ~EXT4_BG_INODE_UNINIT;
1166 			ext4fs_bg_set_flags(bgd, bg_flags);
1167 			memcpy(fs->inode_bmaps[ibmap_idx], zero_buffer,
1168 				fs->blksz);
1169 		}
1170 
1171 		if (ext4fs_set_inode_bmap(fs->curr_inode_no,
1172 					  fs->inode_bmaps[ibmap_idx],
1173 					  ibmap_idx) != 0) {
1174 			debug("going for restart for the block no %d %u\n",
1175 			      fs->curr_inode_no, ibmap_idx);
1176 			goto restart;
1177 		}
1178 
1179 		/* journal backup */
1180 		if (prev_inode_bitmap_index != ibmap_idx) {
1181 			status = ext4fs_devread(i_bitmap_blk * fs->sect_perblk,
1182 						0, fs->blksz, journal_buffer);
1183 			if (status == 0)
1184 				goto fail;
1185 			if (ext4fs_log_journal(journal_buffer,
1186 						le32_to_cpu(bgd->inode_id)))
1187 				goto fail;
1188 			prev_inode_bitmap_index = ibmap_idx;
1189 		}
1190 		ext4fs_bg_free_inodes_dec(bgd, fs);
1191 		if (has_gdt_chksum)
1192 			bgd->bg_itable_unused = bgd->free_inodes;
1193 		ext4fs_sb_free_inodes_dec(fs->sb);
1194 		goto success;
1195 	}
1196 
1197 success:
1198 	free(journal_buffer);
1199 	free(zero_buffer);
1200 
1201 	return fs->curr_inode_no;
1202 fail:
1203 	free(journal_buffer);
1204 	free(zero_buffer);
1205 
1206 	return -1;
1207 
1208 }
1209 
alloc_single_indirect_block(struct ext2_inode * file_inode,unsigned int * total_remaining_blocks,unsigned int * no_blks_reqd)1210 static void alloc_single_indirect_block(struct ext2_inode *file_inode,
1211 					unsigned int *total_remaining_blocks,
1212 					unsigned int *no_blks_reqd)
1213 {
1214 	short i;
1215 	short status;
1216 	long int actual_block_no;
1217 	long int si_blockno;
1218 	/* si :single indirect */
1219 	__le32 *si_buffer = NULL;
1220 	__le32 *si_start_addr = NULL;
1221 	struct ext_filesystem *fs = get_fs();
1222 
1223 	if (*total_remaining_blocks != 0) {
1224 		si_buffer = zalloc(fs->blksz);
1225 		if (!si_buffer) {
1226 			printf("No Memory\n");
1227 			return;
1228 		}
1229 		si_start_addr = si_buffer;
1230 		si_blockno = ext4fs_get_new_blk_no();
1231 		if (si_blockno == -1) {
1232 			printf("no block left to assign\n");
1233 			goto fail;
1234 		}
1235 		(*no_blks_reqd)++;
1236 		debug("SIPB %ld: %u\n", si_blockno, *total_remaining_blocks);
1237 
1238 		status = ext4fs_devread((lbaint_t)si_blockno * fs->sect_perblk,
1239 					0, fs->blksz, (char *)si_buffer);
1240 		memset(si_buffer, '\0', fs->blksz);
1241 		if (status == 0)
1242 			goto fail;
1243 
1244 		for (i = 0; i < (fs->blksz / sizeof(int)); i++) {
1245 			actual_block_no = ext4fs_get_new_blk_no();
1246 			if (actual_block_no == -1) {
1247 				printf("no block left to assign\n");
1248 				goto fail;
1249 			}
1250 			*si_buffer = cpu_to_le32(actual_block_no);
1251 			debug("SIAB %u: %u\n", *si_buffer,
1252 				*total_remaining_blocks);
1253 
1254 			si_buffer++;
1255 			(*total_remaining_blocks)--;
1256 			if (*total_remaining_blocks == 0)
1257 				break;
1258 		}
1259 
1260 		/* write the block to disk */
1261 		put_ext4(((uint64_t) ((uint64_t)si_blockno * (uint64_t)fs->blksz)),
1262 			 si_start_addr, fs->blksz);
1263 		file_inode->b.blocks.indir_block = cpu_to_le32(si_blockno);
1264 	}
1265 fail:
1266 	free(si_start_addr);
1267 }
1268 
alloc_double_indirect_block(struct ext2_inode * file_inode,unsigned int * total_remaining_blocks,unsigned int * no_blks_reqd)1269 static void alloc_double_indirect_block(struct ext2_inode *file_inode,
1270 					unsigned int *total_remaining_blocks,
1271 					unsigned int *no_blks_reqd)
1272 {
1273 	short i;
1274 	short j;
1275 	short status;
1276 	long int actual_block_no;
1277 	/* di:double indirect */
1278 	long int di_blockno_parent;
1279 	long int di_blockno_child;
1280 	__le32 *di_parent_buffer = NULL;
1281 	__le32 *di_child_buff = NULL;
1282 	__le32 *di_block_start_addr = NULL;
1283 	__le32 *di_child_buff_start = NULL;
1284 	struct ext_filesystem *fs = get_fs();
1285 
1286 	if (*total_remaining_blocks != 0) {
1287 		/* double indirect parent block connecting to inode */
1288 		di_blockno_parent = ext4fs_get_new_blk_no();
1289 		if (di_blockno_parent == -1) {
1290 			printf("no block left to assign\n");
1291 			goto fail;
1292 		}
1293 		di_parent_buffer = zalloc(fs->blksz);
1294 		if (!di_parent_buffer)
1295 			goto fail;
1296 
1297 		di_block_start_addr = di_parent_buffer;
1298 		(*no_blks_reqd)++;
1299 		debug("DIPB %ld: %u\n", di_blockno_parent,
1300 		      *total_remaining_blocks);
1301 
1302 		status = ext4fs_devread((lbaint_t)di_blockno_parent *
1303 					fs->sect_perblk, 0,
1304 					fs->blksz, (char *)di_parent_buffer);
1305 
1306 		if (!status) {
1307 			printf("%s: Device read error!\n", __func__);
1308 			goto fail;
1309 		}
1310 		memset(di_parent_buffer, '\0', fs->blksz);
1311 
1312 		/*
1313 		 * start:for each double indirect parent
1314 		 * block create one more block
1315 		 */
1316 		for (i = 0; i < (fs->blksz / sizeof(int)); i++) {
1317 			di_blockno_child = ext4fs_get_new_blk_no();
1318 			if (di_blockno_child == -1) {
1319 				printf("no block left to assign\n");
1320 				goto fail;
1321 			}
1322 			di_child_buff = zalloc(fs->blksz);
1323 			if (!di_child_buff)
1324 				goto fail;
1325 
1326 			di_child_buff_start = di_child_buff;
1327 			*di_parent_buffer = cpu_to_le32(di_blockno_child);
1328 			di_parent_buffer++;
1329 			(*no_blks_reqd)++;
1330 			debug("DICB %ld: %u\n", di_blockno_child,
1331 			      *total_remaining_blocks);
1332 
1333 			status = ext4fs_devread((lbaint_t)di_blockno_child *
1334 						fs->sect_perblk, 0,
1335 						fs->blksz,
1336 						(char *)di_child_buff);
1337 
1338 			if (!status) {
1339 				printf("%s: Device read error!\n", __func__);
1340 				goto fail;
1341 			}
1342 			memset(di_child_buff, '\0', fs->blksz);
1343 			/* filling of actual datablocks for each child */
1344 			for (j = 0; j < (fs->blksz / sizeof(int)); j++) {
1345 				actual_block_no = ext4fs_get_new_blk_no();
1346 				if (actual_block_no == -1) {
1347 					printf("no block left to assign\n");
1348 					goto fail;
1349 				}
1350 				*di_child_buff = cpu_to_le32(actual_block_no);
1351 				debug("DIAB %ld: %u\n", actual_block_no,
1352 				      *total_remaining_blocks);
1353 
1354 				di_child_buff++;
1355 				(*total_remaining_blocks)--;
1356 				if (*total_remaining_blocks == 0)
1357 					break;
1358 			}
1359 			/* write the block  table */
1360 			put_ext4(((uint64_t) ((uint64_t)di_blockno_child * (uint64_t)fs->blksz)),
1361 				 di_child_buff_start, fs->blksz);
1362 			free(di_child_buff_start);
1363 			di_child_buff_start = NULL;
1364 
1365 			if (*total_remaining_blocks == 0)
1366 				break;
1367 		}
1368 		put_ext4(((uint64_t) ((uint64_t)di_blockno_parent * (uint64_t)fs->blksz)),
1369 			 di_block_start_addr, fs->blksz);
1370 		file_inode->b.blocks.double_indir_block = cpu_to_le32(di_blockno_parent);
1371 	}
1372 fail:
1373 	free(di_block_start_addr);
1374 }
1375 
alloc_triple_indirect_block(struct ext2_inode * file_inode,unsigned int * total_remaining_blocks,unsigned int * no_blks_reqd)1376 static void alloc_triple_indirect_block(struct ext2_inode *file_inode,
1377 					unsigned int *total_remaining_blocks,
1378 					unsigned int *no_blks_reqd)
1379 {
1380 	short i;
1381 	short j;
1382 	short k;
1383 	long int actual_block_no;
1384 	/* ti: Triple Indirect */
1385 	long int ti_gp_blockno;
1386 	long int ti_parent_blockno;
1387 	long int ti_child_blockno;
1388 	__le32 *ti_gp_buff = NULL;
1389 	__le32 *ti_parent_buff = NULL;
1390 	__le32 *ti_child_buff = NULL;
1391 	__le32 *ti_gp_buff_start_addr = NULL;
1392 	__le32 *ti_pbuff_start_addr = NULL;
1393 	__le32 *ti_cbuff_start_addr = NULL;
1394 	struct ext_filesystem *fs = get_fs();
1395 	if (*total_remaining_blocks != 0) {
1396 		/* triple indirect grand parent block connecting to inode */
1397 		ti_gp_blockno = ext4fs_get_new_blk_no();
1398 		if (ti_gp_blockno == -1) {
1399 			printf("no block left to assign\n");
1400 			return;
1401 		}
1402 		ti_gp_buff = zalloc(fs->blksz);
1403 		if (!ti_gp_buff)
1404 			return;
1405 
1406 		ti_gp_buff_start_addr = ti_gp_buff;
1407 		(*no_blks_reqd)++;
1408 		debug("TIGPB %ld: %u\n", ti_gp_blockno,
1409 		      *total_remaining_blocks);
1410 
1411 		/* for each 4 byte grand parent entry create one more block */
1412 		for (i = 0; i < (fs->blksz / sizeof(int)); i++) {
1413 			ti_parent_blockno = ext4fs_get_new_blk_no();
1414 			if (ti_parent_blockno == -1) {
1415 				printf("no block left to assign\n");
1416 				goto fail;
1417 			}
1418 			ti_parent_buff = zalloc(fs->blksz);
1419 			if (!ti_parent_buff)
1420 				goto fail;
1421 
1422 			ti_pbuff_start_addr = ti_parent_buff;
1423 			*ti_gp_buff = cpu_to_le32(ti_parent_blockno);
1424 			ti_gp_buff++;
1425 			(*no_blks_reqd)++;
1426 			debug("TIPB %ld: %u\n", ti_parent_blockno,
1427 			      *total_remaining_blocks);
1428 
1429 			/* for each 4 byte entry parent create one more block */
1430 			for (j = 0; j < (fs->blksz / sizeof(int)); j++) {
1431 				ti_child_blockno = ext4fs_get_new_blk_no();
1432 				if (ti_child_blockno == -1) {
1433 					printf("no block left assign\n");
1434 					goto fail1;
1435 				}
1436 				ti_child_buff = zalloc(fs->blksz);
1437 				if (!ti_child_buff)
1438 					goto fail1;
1439 
1440 				ti_cbuff_start_addr = ti_child_buff;
1441 				*ti_parent_buff = cpu_to_le32(ti_child_blockno);
1442 				ti_parent_buff++;
1443 				(*no_blks_reqd)++;
1444 				debug("TICB %ld: %u\n", ti_parent_blockno,
1445 				      *total_remaining_blocks);
1446 
1447 				/* fill actual datablocks for each child */
1448 				for (k = 0; k < (fs->blksz / sizeof(int));
1449 					k++) {
1450 					actual_block_no =
1451 					    ext4fs_get_new_blk_no();
1452 					if (actual_block_no == -1) {
1453 						printf("no block left\n");
1454 						free(ti_cbuff_start_addr);
1455 						goto fail1;
1456 					}
1457 					*ti_child_buff = cpu_to_le32(actual_block_no);
1458 					debug("TIAB %ld: %u\n", actual_block_no,
1459 					      *total_remaining_blocks);
1460 
1461 					ti_child_buff++;
1462 					(*total_remaining_blocks)--;
1463 					if (*total_remaining_blocks == 0)
1464 						break;
1465 				}
1466 				/* write the child block */
1467 				put_ext4(((uint64_t) ((uint64_t)ti_child_blockno *
1468 						      (uint64_t)fs->blksz)),
1469 					 ti_cbuff_start_addr, fs->blksz);
1470 				free(ti_cbuff_start_addr);
1471 
1472 				if (*total_remaining_blocks == 0)
1473 					break;
1474 			}
1475 			/* write the parent block */
1476 			put_ext4(((uint64_t) ((uint64_t)ti_parent_blockno * (uint64_t)fs->blksz)),
1477 				 ti_pbuff_start_addr, fs->blksz);
1478 			free(ti_pbuff_start_addr);
1479 
1480 			if (*total_remaining_blocks == 0)
1481 				break;
1482 		}
1483 		/* write the grand parent block */
1484 		put_ext4(((uint64_t) ((uint64_t)ti_gp_blockno * (uint64_t)fs->blksz)),
1485 			 ti_gp_buff_start_addr, fs->blksz);
1486 		file_inode->b.blocks.triple_indir_block = cpu_to_le32(ti_gp_blockno);
1487 		free(ti_gp_buff_start_addr);
1488 		return;
1489 	}
1490 fail1:
1491 	free(ti_pbuff_start_addr);
1492 fail:
1493 	free(ti_gp_buff_start_addr);
1494 }
1495 
ext4fs_allocate_blocks(struct ext2_inode * file_inode,unsigned int total_remaining_blocks,unsigned int * total_no_of_block)1496 void ext4fs_allocate_blocks(struct ext2_inode *file_inode,
1497 				unsigned int total_remaining_blocks,
1498 				unsigned int *total_no_of_block)
1499 {
1500 	short i;
1501 	long int direct_blockno;
1502 	unsigned int no_blks_reqd = 0;
1503 
1504 	/* allocation of direct blocks */
1505 	for (i = 0; total_remaining_blocks && i < INDIRECT_BLOCKS; i++) {
1506 		direct_blockno = ext4fs_get_new_blk_no();
1507 		if (direct_blockno == -1) {
1508 			printf("no block left to assign\n");
1509 			return;
1510 		}
1511 		file_inode->b.blocks.dir_blocks[i] = cpu_to_le32(direct_blockno);
1512 		debug("DB %ld: %u\n", direct_blockno, total_remaining_blocks);
1513 
1514 		total_remaining_blocks--;
1515 	}
1516 
1517 	alloc_single_indirect_block(file_inode, &total_remaining_blocks,
1518 				    &no_blks_reqd);
1519 	alloc_double_indirect_block(file_inode, &total_remaining_blocks,
1520 				    &no_blks_reqd);
1521 	alloc_triple_indirect_block(file_inode, &total_remaining_blocks,
1522 				    &no_blks_reqd);
1523 	*total_no_of_block += no_blks_reqd;
1524 }
1525 
1526 #endif
1527 
ext4fs_get_extent_block(struct ext2_data * data,struct ext_block_cache * cache,struct ext4_extent_header * ext_block,uint32_t fileblock,int log2_blksz)1528 static struct ext4_extent_header *ext4fs_get_extent_block
1529 	(struct ext2_data *data, struct ext_block_cache *cache,
1530 		struct ext4_extent_header *ext_block,
1531 		uint32_t fileblock, int log2_blksz)
1532 {
1533 	struct ext4_extent_idx *index;
1534 	unsigned long long block;
1535 	int blksz = EXT2_BLOCK_SIZE(data);
1536 	int i;
1537 
1538 	while (1) {
1539 		index = (struct ext4_extent_idx *)(ext_block + 1);
1540 
1541 		if (le16_to_cpu(ext_block->eh_magic) != EXT4_EXT_MAGIC)
1542 			return NULL;
1543 
1544 		if (ext_block->eh_depth == 0)
1545 			return ext_block;
1546 		i = -1;
1547 		do {
1548 			i++;
1549 			if (i >= le16_to_cpu(ext_block->eh_entries))
1550 				break;
1551 		} while (fileblock >= le32_to_cpu(index[i].ei_block));
1552 
1553 		/*
1554 		 * If first logical block number is higher than requested fileblock,
1555 		 * it is a sparse file. This is handled on upper layer.
1556 		 */
1557 		if (i > 0)
1558 			i--;
1559 
1560 		block = le16_to_cpu(index[i].ei_leaf_hi);
1561 		block = (block << 32) + le32_to_cpu(index[i].ei_leaf_lo);
1562 		block <<= log2_blksz;
1563 		if (!ext_cache_read(cache, (lbaint_t)block, blksz))
1564 			return NULL;
1565 		ext_block = (struct ext4_extent_header *)cache->buf;
1566 	}
1567 }
1568 
ext4fs_blockgroup(struct ext2_data * data,int group,struct ext2_block_group * blkgrp)1569 static int ext4fs_blockgroup
1570 	(struct ext2_data *data, int group, struct ext2_block_group *blkgrp)
1571 {
1572 	long int blkno;
1573 	unsigned int blkoff, desc_per_blk;
1574 	int log2blksz = get_fs()->dev_desc->log2blksz;
1575 	int desc_size = get_fs()->gdsize;
1576 
1577 	if (desc_size == 0)
1578 		return 0;
1579 	desc_per_blk = EXT2_BLOCK_SIZE(data) / desc_size;
1580 
1581 	if (desc_per_blk == 0)
1582 		return 0;
1583 	blkno = le32_to_cpu(data->sblock.first_data_block) + 1 +
1584 			group / desc_per_blk;
1585 	blkoff = (group % desc_per_blk) * desc_size;
1586 
1587 	debug("ext4fs read %d group descriptor (blkno %ld blkoff %u)\n",
1588 	      group, blkno, blkoff);
1589 
1590 	return ext4fs_devread((lbaint_t)blkno <<
1591 			      (LOG2_BLOCK_SIZE(data) - log2blksz),
1592 			      blkoff, desc_size, (char *)blkgrp);
1593 }
1594 
ext4fs_read_inode(struct ext2_data * data,int ino,struct ext2_inode * inode)1595 int ext4fs_read_inode(struct ext2_data *data, int ino, struct ext2_inode *inode)
1596 {
1597 	struct ext2_block_group *blkgrp;
1598 	struct ext2_sblock *sblock = &data->sblock;
1599 	struct ext_filesystem *fs = get_fs();
1600 	int log2blksz = get_fs()->dev_desc->log2blksz;
1601 	int inodes_per_block, status;
1602 	long int blkno;
1603 	unsigned int blkoff;
1604 
1605 	/* Allocate blkgrp based on gdsize (for 64-bit support). */
1606 	blkgrp = zalloc(get_fs()->gdsize);
1607 	if (!blkgrp)
1608 		return 0;
1609 
1610 	/* It is easier to calculate if the first inode is 0. */
1611 	ino--;
1612 	if ( le32_to_cpu(sblock->inodes_per_group) == 0 || fs->inodesz == 0) {
1613 		free(blkgrp);
1614 		return 0;
1615 	}
1616 	status = ext4fs_blockgroup(data, ino / le32_to_cpu
1617 				   (sblock->inodes_per_group), blkgrp);
1618 	if (status == 0) {
1619 		free(blkgrp);
1620 		return 0;
1621 	}
1622 
1623 	inodes_per_block = EXT2_BLOCK_SIZE(data) / fs->inodesz;
1624 	if ( inodes_per_block == 0 ) {
1625 		free(blkgrp);
1626 		return 0;
1627 	}
1628 	blkno = ext4fs_bg_get_inode_table_id(blkgrp, fs) +
1629 	    (ino % le32_to_cpu(sblock->inodes_per_group)) / inodes_per_block;
1630 	blkoff = (ino % inodes_per_block) * fs->inodesz;
1631 
1632 	/* Free blkgrp as it is no longer required. */
1633 	free(blkgrp);
1634 
1635 	/* Read the inode. */
1636 	status = ext4fs_devread((lbaint_t)blkno << (LOG2_BLOCK_SIZE(data) -
1637 				log2blksz), blkoff,
1638 				sizeof(struct ext2_inode), (char *)inode);
1639 	if (status == 0)
1640 		return 0;
1641 
1642 	return 1;
1643 }
1644 
read_allocated_block(struct ext2_inode * inode,int fileblock,struct ext_block_cache * cache)1645 long int read_allocated_block(struct ext2_inode *inode, int fileblock,
1646 			      struct ext_block_cache *cache)
1647 {
1648 	long int blknr;
1649 	int blksz;
1650 	int log2_blksz;
1651 	int status;
1652 	long int rblock;
1653 	long int perblock_parent;
1654 	long int perblock_child;
1655 	unsigned long long start;
1656 	/* get the blocksize of the filesystem */
1657 	blksz = EXT2_BLOCK_SIZE(ext4fs_root);
1658 	log2_blksz = LOG2_BLOCK_SIZE(ext4fs_root)
1659 		- get_fs()->dev_desc->log2blksz;
1660 
1661 	if (le32_to_cpu(inode->flags) & EXT4_EXTENTS_FL) {
1662 		long int startblock, endblock;
1663 		struct ext_block_cache *c, cd;
1664 		struct ext4_extent_header *ext_block;
1665 		struct ext4_extent *extent;
1666 		int i;
1667 
1668 		if (cache) {
1669 			c = cache;
1670 		} else {
1671 			c = &cd;
1672 			ext_cache_init(c);
1673 		}
1674 		ext_block =
1675 			ext4fs_get_extent_block(ext4fs_root, c,
1676 						(struct ext4_extent_header *)
1677 						inode->b.blocks.dir_blocks,
1678 						fileblock, log2_blksz);
1679 		if (!ext_block) {
1680 			printf("invalid extent block\n");
1681 			if (!cache)
1682 				ext_cache_fini(c);
1683 			return -EINVAL;
1684 		}
1685 
1686 		extent = (struct ext4_extent *)(ext_block + 1);
1687 
1688 		for (i = 0; i < le16_to_cpu(ext_block->eh_entries); i++) {
1689 			startblock = le32_to_cpu(extent[i].ee_block);
1690 			endblock = startblock + le16_to_cpu(extent[i].ee_len);
1691 
1692 			if (startblock > fileblock) {
1693 				/* Sparse file */
1694 				if (!cache)
1695 					ext_cache_fini(c);
1696 				return 0;
1697 
1698 			} else if (fileblock < endblock) {
1699 				start = le16_to_cpu(extent[i].ee_start_hi);
1700 				start = (start << 32) +
1701 					le32_to_cpu(extent[i].ee_start_lo);
1702 				if (!cache)
1703 					ext_cache_fini(c);
1704 				return (fileblock - startblock) + start;
1705 			}
1706 		}
1707 
1708 		if (!cache)
1709 			ext_cache_fini(c);
1710 		return 0;
1711 	}
1712 
1713 	/* Direct blocks. */
1714 	if (fileblock < INDIRECT_BLOCKS)
1715 		blknr = le32_to_cpu(inode->b.blocks.dir_blocks[fileblock]);
1716 
1717 	/* Indirect. */
1718 	else if (fileblock < (INDIRECT_BLOCKS + (blksz / 4))) {
1719 		if (ext4fs_indir1_block == NULL) {
1720 			ext4fs_indir1_block = zalloc(blksz);
1721 			if (ext4fs_indir1_block == NULL) {
1722 				printf("** SI ext2fs read block (indir 1)"
1723 					"malloc failed. **\n");
1724 				return -1;
1725 			}
1726 			ext4fs_indir1_size = blksz;
1727 			ext4fs_indir1_blkno = -1;
1728 		}
1729 		if (blksz != ext4fs_indir1_size) {
1730 			free(ext4fs_indir1_block);
1731 			ext4fs_indir1_block = NULL;
1732 			ext4fs_indir1_size = 0;
1733 			ext4fs_indir1_blkno = -1;
1734 			ext4fs_indir1_block = zalloc(blksz);
1735 			if (ext4fs_indir1_block == NULL) {
1736 				printf("** SI ext2fs read block (indir 1):"
1737 					"malloc failed. **\n");
1738 				return -1;
1739 			}
1740 			ext4fs_indir1_size = blksz;
1741 		}
1742 		if ((le32_to_cpu(inode->b.blocks.indir_block) <<
1743 		     log2_blksz) != ext4fs_indir1_blkno) {
1744 			status =
1745 			    ext4fs_devread((lbaint_t)le32_to_cpu
1746 					   (inode->b.blocks.
1747 					    indir_block) << log2_blksz, 0,
1748 					   blksz, (char *)ext4fs_indir1_block);
1749 			if (status == 0) {
1750 				printf("** SI ext2fs read block (indir 1)"
1751 					"failed. **\n");
1752 				return -1;
1753 			}
1754 			ext4fs_indir1_blkno =
1755 				le32_to_cpu(inode->b.blocks.
1756 					       indir_block) << log2_blksz;
1757 		}
1758 		blknr = le32_to_cpu(ext4fs_indir1_block
1759 				      [fileblock - INDIRECT_BLOCKS]);
1760 	}
1761 	/* Double indirect. */
1762 	else if (fileblock < (INDIRECT_BLOCKS + (blksz / 4 *
1763 					(blksz / 4 + 1)))) {
1764 
1765 		long int perblock = blksz / 4;
1766 		long int rblock = fileblock - (INDIRECT_BLOCKS + blksz / 4);
1767 
1768 		if (ext4fs_indir1_block == NULL) {
1769 			ext4fs_indir1_block = zalloc(blksz);
1770 			if (ext4fs_indir1_block == NULL) {
1771 				printf("** DI ext2fs read block (indir 2 1)"
1772 					"malloc failed. **\n");
1773 				return -1;
1774 			}
1775 			ext4fs_indir1_size = blksz;
1776 			ext4fs_indir1_blkno = -1;
1777 		}
1778 		if (blksz != ext4fs_indir1_size) {
1779 			free(ext4fs_indir1_block);
1780 			ext4fs_indir1_block = NULL;
1781 			ext4fs_indir1_size = 0;
1782 			ext4fs_indir1_blkno = -1;
1783 			ext4fs_indir1_block = zalloc(blksz);
1784 			if (ext4fs_indir1_block == NULL) {
1785 				printf("** DI ext2fs read block (indir 2 1)"
1786 					"malloc failed. **\n");
1787 				return -1;
1788 			}
1789 			ext4fs_indir1_size = blksz;
1790 		}
1791 		if ((le32_to_cpu(inode->b.blocks.double_indir_block) <<
1792 		     log2_blksz) != ext4fs_indir1_blkno) {
1793 			status =
1794 			    ext4fs_devread((lbaint_t)le32_to_cpu
1795 					   (inode->b.blocks.
1796 					    double_indir_block) << log2_blksz,
1797 					   0, blksz,
1798 					   (char *)ext4fs_indir1_block);
1799 			if (status == 0) {
1800 				printf("** DI ext2fs read block (indir 2 1)"
1801 					"failed. **\n");
1802 				return -1;
1803 			}
1804 			ext4fs_indir1_blkno =
1805 			    le32_to_cpu(inode->b.blocks.double_indir_block) <<
1806 			    log2_blksz;
1807 		}
1808 
1809 		if (ext4fs_indir2_block == NULL) {
1810 			ext4fs_indir2_block = zalloc(blksz);
1811 			if (ext4fs_indir2_block == NULL) {
1812 				printf("** DI ext2fs read block (indir 2 2)"
1813 					"malloc failed. **\n");
1814 				return -1;
1815 			}
1816 			ext4fs_indir2_size = blksz;
1817 			ext4fs_indir2_blkno = -1;
1818 		}
1819 		if (blksz != ext4fs_indir2_size) {
1820 			free(ext4fs_indir2_block);
1821 			ext4fs_indir2_block = NULL;
1822 			ext4fs_indir2_size = 0;
1823 			ext4fs_indir2_blkno = -1;
1824 			ext4fs_indir2_block = zalloc(blksz);
1825 			if (ext4fs_indir2_block == NULL) {
1826 				printf("** DI ext2fs read block (indir 2 2)"
1827 					"malloc failed. **\n");
1828 				return -1;
1829 			}
1830 			ext4fs_indir2_size = blksz;
1831 		}
1832 		if ((le32_to_cpu(ext4fs_indir1_block[rblock / perblock]) <<
1833 		     log2_blksz) != ext4fs_indir2_blkno) {
1834 			status = ext4fs_devread((lbaint_t)le32_to_cpu
1835 						(ext4fs_indir1_block
1836 						 [rblock /
1837 						  perblock]) << log2_blksz, 0,
1838 						blksz,
1839 						(char *)ext4fs_indir2_block);
1840 			if (status == 0) {
1841 				printf("** DI ext2fs read block (indir 2 2)"
1842 					"failed. **\n");
1843 				return -1;
1844 			}
1845 			ext4fs_indir2_blkno =
1846 			    le32_to_cpu(ext4fs_indir1_block[rblock
1847 							      /
1848 							      perblock]) <<
1849 			    log2_blksz;
1850 		}
1851 		blknr = le32_to_cpu(ext4fs_indir2_block[rblock % perblock]);
1852 	}
1853 	/* Tripple indirect. */
1854 	else {
1855 		rblock = fileblock - (INDIRECT_BLOCKS + blksz / 4 +
1856 				      (blksz / 4 * blksz / 4));
1857 		perblock_child = blksz / 4;
1858 		perblock_parent = ((blksz / 4) * (blksz / 4));
1859 
1860 		if (ext4fs_indir1_block == NULL) {
1861 			ext4fs_indir1_block = zalloc(blksz);
1862 			if (ext4fs_indir1_block == NULL) {
1863 				printf("** TI ext2fs read block (indir 2 1)"
1864 					"malloc failed. **\n");
1865 				return -1;
1866 			}
1867 			ext4fs_indir1_size = blksz;
1868 			ext4fs_indir1_blkno = -1;
1869 		}
1870 		if (blksz != ext4fs_indir1_size) {
1871 			free(ext4fs_indir1_block);
1872 			ext4fs_indir1_block = NULL;
1873 			ext4fs_indir1_size = 0;
1874 			ext4fs_indir1_blkno = -1;
1875 			ext4fs_indir1_block = zalloc(blksz);
1876 			if (ext4fs_indir1_block == NULL) {
1877 				printf("** TI ext2fs read block (indir 2 1)"
1878 					"malloc failed. **\n");
1879 				return -1;
1880 			}
1881 			ext4fs_indir1_size = blksz;
1882 		}
1883 		if ((le32_to_cpu(inode->b.blocks.triple_indir_block) <<
1884 		     log2_blksz) != ext4fs_indir1_blkno) {
1885 			status = ext4fs_devread
1886 			    ((lbaint_t)
1887 			     le32_to_cpu(inode->b.blocks.triple_indir_block)
1888 			     << log2_blksz, 0, blksz,
1889 			     (char *)ext4fs_indir1_block);
1890 			if (status == 0) {
1891 				printf("** TI ext2fs read block (indir 2 1)"
1892 					"failed. **\n");
1893 				return -1;
1894 			}
1895 			ext4fs_indir1_blkno =
1896 			    le32_to_cpu(inode->b.blocks.triple_indir_block) <<
1897 			    log2_blksz;
1898 		}
1899 
1900 		if (ext4fs_indir2_block == NULL) {
1901 			ext4fs_indir2_block = zalloc(blksz);
1902 			if (ext4fs_indir2_block == NULL) {
1903 				printf("** TI ext2fs read block (indir 2 2)"
1904 					"malloc failed. **\n");
1905 				return -1;
1906 			}
1907 			ext4fs_indir2_size = blksz;
1908 			ext4fs_indir2_blkno = -1;
1909 		}
1910 		if (blksz != ext4fs_indir2_size) {
1911 			free(ext4fs_indir2_block);
1912 			ext4fs_indir2_block = NULL;
1913 			ext4fs_indir2_size = 0;
1914 			ext4fs_indir2_blkno = -1;
1915 			ext4fs_indir2_block = zalloc(blksz);
1916 			if (ext4fs_indir2_block == NULL) {
1917 				printf("** TI ext2fs read block (indir 2 2)"
1918 					"malloc failed. **\n");
1919 				return -1;
1920 			}
1921 			ext4fs_indir2_size = blksz;
1922 		}
1923 		if ((le32_to_cpu(ext4fs_indir1_block[rblock /
1924 						       perblock_parent]) <<
1925 		     log2_blksz)
1926 		    != ext4fs_indir2_blkno) {
1927 			status = ext4fs_devread((lbaint_t)le32_to_cpu
1928 						(ext4fs_indir1_block
1929 						 [rblock /
1930 						  perblock_parent]) <<
1931 						log2_blksz, 0, blksz,
1932 						(char *)ext4fs_indir2_block);
1933 			if (status == 0) {
1934 				printf("** TI ext2fs read block (indir 2 2)"
1935 					"failed. **\n");
1936 				return -1;
1937 			}
1938 			ext4fs_indir2_blkno =
1939 			    le32_to_cpu(ext4fs_indir1_block[rblock /
1940 							      perblock_parent])
1941 			    << log2_blksz;
1942 		}
1943 
1944 		if (ext4fs_indir3_block == NULL) {
1945 			ext4fs_indir3_block = zalloc(blksz);
1946 			if (ext4fs_indir3_block == NULL) {
1947 				printf("** TI ext2fs read block (indir 2 2)"
1948 					"malloc failed. **\n");
1949 				return -1;
1950 			}
1951 			ext4fs_indir3_size = blksz;
1952 			ext4fs_indir3_blkno = -1;
1953 		}
1954 		if (blksz != ext4fs_indir3_size) {
1955 			free(ext4fs_indir3_block);
1956 			ext4fs_indir3_block = NULL;
1957 			ext4fs_indir3_size = 0;
1958 			ext4fs_indir3_blkno = -1;
1959 			ext4fs_indir3_block = zalloc(blksz);
1960 			if (ext4fs_indir3_block == NULL) {
1961 				printf("** TI ext2fs read block (indir 2 2)"
1962 					"malloc failed. **\n");
1963 				return -1;
1964 			}
1965 			ext4fs_indir3_size = blksz;
1966 		}
1967 		if ((le32_to_cpu(ext4fs_indir2_block[rblock
1968 						       /
1969 						       perblock_child]) <<
1970 		     log2_blksz) != ext4fs_indir3_blkno) {
1971 			status =
1972 			    ext4fs_devread((lbaint_t)le32_to_cpu
1973 					   (ext4fs_indir2_block
1974 					    [(rblock / perblock_child)
1975 					     % (blksz / 4)]) << log2_blksz, 0,
1976 					   blksz, (char *)ext4fs_indir3_block);
1977 			if (status == 0) {
1978 				printf("** TI ext2fs read block (indir 2 2)"
1979 				       "failed. **\n");
1980 				return -1;
1981 			}
1982 			ext4fs_indir3_blkno =
1983 			    le32_to_cpu(ext4fs_indir2_block[(rblock /
1984 							       perblock_child) %
1985 							      (blksz /
1986 							       4)]) <<
1987 			    log2_blksz;
1988 		}
1989 
1990 		blknr = le32_to_cpu(ext4fs_indir3_block
1991 				      [rblock % perblock_child]);
1992 	}
1993 	debug("read_allocated_block %ld\n", blknr);
1994 
1995 	return blknr;
1996 }
1997 
1998 /**
1999  * ext4fs_reinit_global() - Reinitialize values of ext4 write implementation's
2000  *			    global pointers
2001  *
2002  * This function assures that for a file with the same name but different size
2003  * the sequential store on the ext4 filesystem will be correct.
2004  *
2005  * In this function the global data, responsible for internal representation
2006  * of the ext4 data are initialized to the reset state. Without this, during
2007  * replacement of the smaller file with the bigger truncation of new file was
2008  * performed.
2009  */
ext4fs_reinit_global(void)2010 void ext4fs_reinit_global(void)
2011 {
2012 	if (ext4fs_indir1_block != NULL) {
2013 		free(ext4fs_indir1_block);
2014 		ext4fs_indir1_block = NULL;
2015 		ext4fs_indir1_size = 0;
2016 		ext4fs_indir1_blkno = -1;
2017 	}
2018 	if (ext4fs_indir2_block != NULL) {
2019 		free(ext4fs_indir2_block);
2020 		ext4fs_indir2_block = NULL;
2021 		ext4fs_indir2_size = 0;
2022 		ext4fs_indir2_blkno = -1;
2023 	}
2024 	if (ext4fs_indir3_block != NULL) {
2025 		free(ext4fs_indir3_block);
2026 		ext4fs_indir3_block = NULL;
2027 		ext4fs_indir3_size = 0;
2028 		ext4fs_indir3_blkno = -1;
2029 	}
2030 }
ext4fs_close(void)2031 void ext4fs_close(void)
2032 {
2033 	if ((ext4fs_file != NULL) && (ext4fs_root != NULL)) {
2034 		ext4fs_free_node(ext4fs_file, &ext4fs_root->diropen);
2035 		ext4fs_file = NULL;
2036 	}
2037 	if (ext4fs_root != NULL) {
2038 		free(ext4fs_root);
2039 		ext4fs_root = NULL;
2040 	}
2041 
2042 	ext4fs_reinit_global();
2043 }
2044 
ext4fs_iterate_dir(struct ext2fs_node * dir,char * name,struct ext2fs_node ** fnode,int * ftype)2045 int ext4fs_iterate_dir(struct ext2fs_node *dir, char *name,
2046 				struct ext2fs_node **fnode, int *ftype)
2047 {
2048 	unsigned int fpos = 0;
2049 	int status;
2050 	loff_t actread;
2051 
2052 #ifdef DEBUG
2053 	if (name != NULL)
2054 		printf("Iterate dir %s\n", name);
2055 #endif /* of DEBUG */
2056 	if (!dir->inode_read) {
2057 		status = ext4fs_read_inode(dir->data, dir->ino, &dir->inode);
2058 		if (status == 0)
2059 			return 0;
2060 	}
2061 	/* Search the file.  */
2062 	while (fpos < le32_to_cpu(dir->inode.size)) {
2063 		struct ext2_dirent dirent;
2064 
2065 		status = ext4fs_read_file(dir, fpos,
2066 					  sizeof(struct ext2_dirent),
2067 					  (char *)&dirent, &actread);
2068 		if (status < 0)
2069 			return 0;
2070 
2071 		if (dirent.direntlen == 0) {
2072 			printf("Failed to iterate over directory %s\n", name);
2073 			return 0;
2074 		}
2075 
2076 		if (dirent.namelen != 0) {
2077 			char filename[dirent.namelen + 1];
2078 			struct ext2fs_node *fdiro;
2079 			int type = FILETYPE_UNKNOWN;
2080 
2081 			status = ext4fs_read_file(dir,
2082 						  fpos +
2083 						  sizeof(struct ext2_dirent),
2084 						  dirent.namelen, filename,
2085 						  &actread);
2086 			if (status < 0)
2087 				return 0;
2088 
2089 			fdiro = zalloc(sizeof(struct ext2fs_node));
2090 			if (!fdiro)
2091 				return 0;
2092 
2093 			fdiro->data = dir->data;
2094 			fdiro->ino = le32_to_cpu(dirent.inode);
2095 
2096 			filename[dirent.namelen] = '\0';
2097 
2098 			if (dirent.filetype != FILETYPE_UNKNOWN) {
2099 				fdiro->inode_read = 0;
2100 
2101 				if (dirent.filetype == FILETYPE_DIRECTORY)
2102 					type = FILETYPE_DIRECTORY;
2103 				else if (dirent.filetype == FILETYPE_SYMLINK)
2104 					type = FILETYPE_SYMLINK;
2105 				else if (dirent.filetype == FILETYPE_REG)
2106 					type = FILETYPE_REG;
2107 			} else {
2108 				status = ext4fs_read_inode(dir->data,
2109 							   le32_to_cpu
2110 							   (dirent.inode),
2111 							   &fdiro->inode);
2112 				if (status == 0) {
2113 					free(fdiro);
2114 					return 0;
2115 				}
2116 				fdiro->inode_read = 1;
2117 
2118 				if ((le16_to_cpu(fdiro->inode.mode) &
2119 				     FILETYPE_INO_MASK) ==
2120 				    FILETYPE_INO_DIRECTORY) {
2121 					type = FILETYPE_DIRECTORY;
2122 				} else if ((le16_to_cpu(fdiro->inode.mode)
2123 					    & FILETYPE_INO_MASK) ==
2124 					   FILETYPE_INO_SYMLINK) {
2125 					type = FILETYPE_SYMLINK;
2126 				} else if ((le16_to_cpu(fdiro->inode.mode)
2127 					    & FILETYPE_INO_MASK) ==
2128 					   FILETYPE_INO_REG) {
2129 					type = FILETYPE_REG;
2130 				}
2131 			}
2132 #ifdef DEBUG
2133 			printf("iterate >%s<\n", filename);
2134 #endif /* of DEBUG */
2135 			if ((name != NULL) && (fnode != NULL)
2136 			    && (ftype != NULL)) {
2137 				if (strcmp(filename, name) == 0) {
2138 					*ftype = type;
2139 					*fnode = fdiro;
2140 					return 1;
2141 				}
2142 			}
2143 			free(fdiro);
2144 		}
2145 		fpos += le16_to_cpu(dirent.direntlen);
2146 	}
2147 	return 0;
2148 }
2149 
ext4fs_read_symlink(struct ext2fs_node * node)2150 static char *ext4fs_read_symlink(struct ext2fs_node *node)
2151 {
2152 	char *symlink;
2153 	struct ext2fs_node *diro = node;
2154 	int status;
2155 	loff_t actread;
2156 	size_t alloc_size;
2157 
2158 	if (!diro->inode_read) {
2159 		status = ext4fs_read_inode(diro->data, diro->ino, &diro->inode);
2160 		if (status == 0)
2161 			return NULL;
2162 	}
2163 
2164 	if (__builtin_add_overflow(le32_to_cpu(diro->inode.size), 1, &alloc_size))
2165 		return NULL;
2166 
2167 	symlink = zalloc(alloc_size);
2168 	if (!symlink)
2169 		return NULL;
2170 
2171 	if (le32_to_cpu(diro->inode.size) < sizeof(diro->inode.b.symlink)) {
2172 		strncpy(symlink, diro->inode.b.symlink,
2173 			 le32_to_cpu(diro->inode.size));
2174 	} else {
2175 		status = ext4fs_read_file(diro, 0,
2176 					   le32_to_cpu(diro->inode.size),
2177 					   symlink, &actread);
2178 		if ((status < 0) || (actread == 0)) {
2179 			free(symlink);
2180 			return NULL;
2181 		}
2182 	}
2183 	symlink[le32_to_cpu(diro->inode.size)] = '\0';
2184 	return symlink;
2185 }
2186 
ext4fs_find_file1(const char * currpath,struct ext2fs_node * currroot,struct ext2fs_node ** currfound,int * foundtype)2187 int ext4fs_find_file1(const char *currpath, struct ext2fs_node *currroot,
2188 		      struct ext2fs_node **currfound, int *foundtype)
2189 {
2190 	char fpath[strlen(currpath) + 1];
2191 	char *name = fpath;
2192 	char *next;
2193 	int status;
2194 	int type = FILETYPE_DIRECTORY;
2195 	struct ext2fs_node *currnode = currroot;
2196 	struct ext2fs_node *oldnode = currroot;
2197 
2198 	strncpy(fpath, currpath, strlen(currpath) + 1);
2199 
2200 	/* Remove all leading slashes. */
2201 	while (*name == '/')
2202 		name++;
2203 
2204 	if (!*name) {
2205 		*currfound = currnode;
2206 		return 1;
2207 	}
2208 
2209 	for (;;) {
2210 		int found;
2211 
2212 		/* Extract the actual part from the pathname. */
2213 		next = strchr(name, '/');
2214 		if (next) {
2215 			/* Remove all leading slashes. */
2216 			while (*next == '/')
2217 				*(next++) = '\0';
2218 		}
2219 
2220 		if (type != FILETYPE_DIRECTORY) {
2221 			ext4fs_free_node(currnode, currroot);
2222 			return 0;
2223 		}
2224 
2225 		oldnode = currnode;
2226 
2227 		/* Iterate over the directory. */
2228 		found = ext4fs_iterate_dir(currnode, name, &currnode, &type);
2229 		if (found == 0)
2230 			return 0;
2231 
2232 		if (found == -1)
2233 			break;
2234 
2235 		/* Read in the symlink and follow it. */
2236 		if (type == FILETYPE_SYMLINK) {
2237 			char *symlink;
2238 
2239 			/* Test if the symlink does not loop. */
2240 			if (++symlinknest == 8) {
2241 				ext4fs_free_node(currnode, currroot);
2242 				ext4fs_free_node(oldnode, currroot);
2243 				return 0;
2244 			}
2245 
2246 			symlink = ext4fs_read_symlink(currnode);
2247 			ext4fs_free_node(currnode, currroot);
2248 
2249 			if (!symlink) {
2250 				ext4fs_free_node(oldnode, currroot);
2251 				return 0;
2252 			}
2253 
2254 			debug("Got symlink >%s<\n", symlink);
2255 
2256 			if (symlink[0] == '/') {
2257 				ext4fs_free_node(oldnode, currroot);
2258 				oldnode = &ext4fs_root->diropen;
2259 			}
2260 
2261 			/* Lookup the node the symlink points to. */
2262 			status = ext4fs_find_file1(symlink, oldnode,
2263 						    &currnode, &type);
2264 
2265 			free(symlink);
2266 
2267 			if (status == 0) {
2268 				ext4fs_free_node(oldnode, currroot);
2269 				return 0;
2270 			}
2271 		}
2272 
2273 		ext4fs_free_node(oldnode, currroot);
2274 
2275 		/* Found the node! */
2276 		if (!next || *next == '\0') {
2277 			*currfound = currnode;
2278 			*foundtype = type;
2279 			return 1;
2280 		}
2281 		name = next;
2282 	}
2283 	return -1;
2284 }
2285 
ext4fs_find_file(const char * path,struct ext2fs_node * rootnode,struct ext2fs_node ** foundnode,int expecttype)2286 int ext4fs_find_file(const char *path, struct ext2fs_node *rootnode,
2287 	struct ext2fs_node **foundnode, int expecttype)
2288 {
2289 	int status;
2290 	int foundtype = FILETYPE_DIRECTORY;
2291 
2292 	symlinknest = 0;
2293 	if (!path)
2294 		return 0;
2295 
2296 	status = ext4fs_find_file1(path, rootnode, foundnode, &foundtype);
2297 	if (status == 0)
2298 		return 0;
2299 
2300 	/* Check if the node that was found was of the expected type. */
2301 	if ((expecttype == FILETYPE_REG) && (foundtype != expecttype))
2302 		return 0;
2303 	else if ((expecttype == FILETYPE_DIRECTORY)
2304 		   && (foundtype != expecttype))
2305 		return 0;
2306 
2307 	return 1;
2308 }
2309 
ext4fs_open(const char * filename,loff_t * len)2310 int ext4fs_open(const char *filename, loff_t *len)
2311 {
2312 	struct ext2fs_node *fdiro = NULL;
2313 	int status;
2314 
2315 	if (ext4fs_root == NULL)
2316 		return -1;
2317 
2318 	ext4fs_file = NULL;
2319 	status = ext4fs_find_file(filename, &ext4fs_root->diropen, &fdiro,
2320 				  FILETYPE_REG);
2321 	if (status == 0)
2322 		goto fail;
2323 
2324 	if (!fdiro->inode_read) {
2325 		status = ext4fs_read_inode(fdiro->data, fdiro->ino,
2326 				&fdiro->inode);
2327 		if (status == 0)
2328 			goto fail;
2329 	}
2330 	*len = le32_to_cpu(fdiro->inode.size);
2331 	ext4fs_file = fdiro;
2332 
2333 	return 0;
2334 fail:
2335 	ext4fs_free_node(fdiro, &ext4fs_root->diropen);
2336 
2337 	return -1;
2338 }
2339 
ext4fs_mount(void)2340 int ext4fs_mount(void)
2341 {
2342 	struct ext2_data *data;
2343 	int status;
2344 	struct ext_filesystem *fs = get_fs();
2345 	data = zalloc(SUPERBLOCK_SIZE);
2346 	if (!data)
2347 		return 0;
2348 
2349 	/* Read the superblock. */
2350 	status = ext4_read_superblock((char *)&data->sblock);
2351 
2352 	if (status == 0)
2353 		goto fail;
2354 
2355 	/* Make sure this is an ext2 filesystem. */
2356 	if (le16_to_cpu(data->sblock.magic) != EXT2_MAGIC)
2357 		goto fail_noerr;
2358 
2359 	if (le32_to_cpu(data->sblock.revision_level) == 0) {
2360 		fs->inodesz = 128;
2361 		fs->gdsize = 32;
2362 	} else {
2363 		int missing = __le32_to_cpu(data->sblock.feature_incompat) &
2364 			      ~(EXT4_FEATURE_INCOMPAT_SUPP |
2365 				EXT4_FEATURE_INCOMPAT_SUPP_LAZY_RO);
2366 
2367 		if (missing) {
2368 			/*
2369 			 * This code used to be relaxed about feature flags.
2370 			 * We don't stop the mount to avoid breaking existing setups.
2371 			 * But, incompatible features can cause serious read errors.
2372 			 */
2373 			log_err("fs uses incompatible features: %08x, ignoring\n",
2374 				missing);
2375 		}
2376 
2377 		debug("EXT4 features COMPAT: %08x INCOMPAT: %08x RO_COMPAT: %08x\n",
2378 		      __le32_to_cpu(data->sblock.feature_compatibility),
2379 		      __le32_to_cpu(data->sblock.feature_incompat),
2380 		      __le32_to_cpu(data->sblock.feature_ro_compat));
2381 
2382 		fs->inodesz = le16_to_cpu(data->sblock.inode_size);
2383 		fs->gdsize = le32_to_cpu(data->sblock.feature_incompat) &
2384 			EXT4_FEATURE_INCOMPAT_64BIT ?
2385 			le16_to_cpu(data->sblock.descriptor_size) : 32;
2386 	}
2387 
2388 	debug("EXT2 rev %d, inode_size %d, descriptor size %d\n",
2389 	      le32_to_cpu(data->sblock.revision_level),
2390 	      fs->inodesz, fs->gdsize);
2391 
2392 	data->diropen.data = data;
2393 	data->diropen.ino = 2;
2394 	data->diropen.inode_read = 1;
2395 	data->inode = &data->diropen.inode;
2396 
2397 	status = ext4fs_read_inode(data, 2, data->inode);
2398 	if (status == 0)
2399 		goto fail;
2400 
2401 	ext4fs_root = data;
2402 
2403 	return 1;
2404 fail:
2405 	log_debug("Failed to mount ext2 filesystem...\n");
2406 fail_noerr:
2407 	free(data);
2408 	ext4fs_root = NULL;
2409 
2410 	return 0;
2411 }
2412