I found many links but almost all are pointing to fix not the reason.
I created a 7GB ext4 partition on a sd card connected via USB card reader to PC. I have an application which is writing 10488576 bytes to the mentioned partition (/dev/sdc2). After the application run the filesystem is looking corrupt:
#fsck.ext4 -v /dev/sdc2
e2fsck 1.42.8 (20-Jun-2013)
ext2fs_open2: Bad magic number in super-block
fsck.ext4: Superblock invalid, trying backup blocks...
Superblock has an invalid journal (inode 8).
Clear<y>? no
fsck.ext4: Illegal inode number while checking ext3 journal for /dev/sdc2
/dev/sdc2: ***** FILE SYSTEM WAS MODIFIED *****
/dev/sdc2: ********** WARNING: Filesystem still has errors **********
#dumpe2fs /dev/sdc2
dumpe2fs 1.42.8 (20-Jun-2013)
dumpe2fs: Bad magic number in super-block while trying to open /dev/sdc2
Couldn't find valid filesystem superblock.
The application is simply using something like below (i can't post exact code):
char *write_buf; //declared in header
write_buf = (char *) malloc(size) // where size = 10488576. This allocation is happening in function a() called from main
char *buf; // declared locally in function b()
buf = write_buf; // in function b()
write(fd,buf,size); // in function b()
The filesystem block size is 4K. Backup superblock at 32768 , 98304 ,163840 ,229376 , 294912 ,819200, 884736 ,1605632 Let me know if any more information required. I need to understand what might cause this corruption , because I'm very much affirmative that something may be wrong with application code.
EDIT:
I can see that primary superblock starts at 0 , and the lseek() call before write()
is also doing SEEK_SET
to 0, which would overwrite superblock information. I am going to try lseek far from superblock before write()
.
EDIT
:
I have got this fixed by doing as I mentioned above. As per dumpe2fs o/p I had below for group 0:
Group 0: (Blocks 0-32767)
Checksum 0x8bba, unused inodes 8069
Primary superblock at 0, Group descriptors at 1-1
Reserved GDT blocks at 2-474
Block bitmap at 475 (+475), Inode bitmap at 491 (+491)
Inode table at 507-1011 (+507)
24175 free blocks, 8069 free inodes, 2 directories, 8069 unused inodes
Free blocks: 8593-32767
Free inodes: 12-8080
So before writing I did lseek to 8593*4096 .Now filesystem is not getting corrupt.
I have got this fixed by doing as I mentioned above. As per dumpe2fs o/p I had below for group 0:
Group 0: (Blocks 0-32767)
Checksum 0x8bba, unused inodes 8069
Primary superblock at 0, Group descriptors at 1-1
Reserved GDT blocks at 2-474
Block bitmap at 475 (+475), Inode bitmap at 491 (+491)
Inode table at 507-1011 (+507)
24175 free blocks, 8069 free inodes, 2 directories, 8069 unused inodes
Free blocks: 8593-32767
Free inodes: 12-8080
So before writing I did lseek
to 8593*4096.Now filesystem is not getting corrupt.