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