In the registration of simplefs_file_ops callbacks, there is no open operation, which may lead to creating unexpected space. We can specify our own open operation by truncating, and here is a possible implementation:
/*
* Called when a file is opened in the simplefs.
* It checks the flags associated with the file opening mode (O_WRONLY, O_RDWR, O_TRUNC)
* and performs truncation if the file is being opened for write or read/write and
* the O_TRUNC flag is set.
*
* Truncation is achieved by reading the file's index block from disk, iterating
* over the data block pointers, releasing the associated data blocks, and updating
* the inode metadata (size and block count).
*
static int simplefs_open(struct inode *inode, struct file *file)
{
bool wronly = (bool) (file->f_flags & O_WRONLY);
bool rdwr = (bool) (file->f_flags & O_RDWR);
bool trunc = (bool) (file->f_flags & O_TRUNC);
if ((wronly || rdwr) && trunc && inode->i_size) {
struct super_block *sb = inode->i_sb;
struct simplefs_sb_info *sbi = SIMPLEFS_SB(sb);
struct simplefs_inode_info *ci = SIMPLEFS_INODE(inode);
struct simplefs_file_index_block *index;
struct buffer_head *bh_index;
sector_t iblock;
/* Fetch the file's index block from disk */
bh_index = sb_bread(sb, ci->index_block);
if (!bh_index)
return -EIO;
index = (struct simplefs_file_index_block *) bh_index->b_data;
for (iblock = 0; index->blocks[iblock]; iblock++) {
put_block(sbi, index->blocks[iblock]);
index->blocks[iblock] = 0;
}
inode->i_size = 0;
inode->i_blocks = 1;
brelse(bh_index);
}
return 0;
}
const struct file_operations simplefs_file_ops = {
.owner = THIS_MODULE,
.open = simplefs_open,
...
};
In the registration of
simplefs_file_ops
callbacks, there is noopen
operation, which may lead to creating unexpected space. We can specify our ownopen
operation by truncating, and here is a possible implementation: