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