I am working on some ext2 filesystem stuff for a school project (implement ls, mkdir, that kind of thing) and have found that I am generating a lot of redundant code for tasks where I need to traverse an inode's i_block. I have functions to count the number of dir entries, search the dir entries for a strcmp name match, reading data, writing data... traversing i_block seems common to many problems. I am attempting to write something akin to an iterator for the i_block to remove this redundancy.
I am wondering what would be a good way to do this? are there examples where this or something similar is done in linux system code? or is this simply a bad idea.
The code I have come up with thus far:
// returns block number located at iter position
// accepts a minode which is a struct wrapping an inode (in memory inode)
// accepts an iter which will self mutate and should start at 0
int iter_i_block(minode *mip, int *iter) {
static char buf[BLKSIZE]; // static buffer
// buffer number used to check if a new block needs to be read in
static int bufno;
// inode number used to determine if we are working on a new inode
static int ino;
// block number to return
int bno;
// flag for if this a different inode than last time
int new_ino = 0;
if (ino != mip->ino) {
ino = mip->ino;
new_ino = 1;
}
// direct blocks
if (*iter < 12) {
bno = mip->inode.i_block[*iter];
(*iter)++;
bufno = bno;
return bno;
}
// indirect blocks
if (*iter < 12 + BLKSIZE_1024 / sizeof(int)) {
if (!mip->inode.i_block[12])
return 0;
if (new_ino || bufno != 12)
get_block(mip->mount_entry, mip->inode.i_block[12], buf);
bufno = 12;
bno = *((int *)buf + (*iter - 12));
(*iter)++;
return bno;
}
// double indirect blocks (not shown)
// triple indirect blocks (not shown)
return 0;
}
Any advice is appreciated! Thank you