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