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