免费 space 位图 C 实现
Free space bitmap C implementation
我正在尝试开发一个简单的文件系统(Linux 内核)并且我正在考虑使用位图来跟踪 used/free 块,如下所述:
https://en.wikipedia.org/wiki/Free_space_bitmap
但是,我在 C 中找不到此类系统的任何实现。我想看一些示例,以便我可以实现与我的系统类似的东西。
有什么可以找到它们的建议吗?
这是我在阅读这个问题后做出的一个快速实现。
int mem_block_size;
int mem_block_count;
uint *bit_map;
char *buffer;
void init_memory_map(int block_size, int block_count)
{
mem_block_size = block_size;
mem_block_count = block_count;
buffer = (char*)malloc(block_size * block_count);
bit_map = (uint*)calloc((block_count / 32) + ((block_count % 32) != 0), 4);
}
inline
int is_allocated(int index)
{
return (bit_map[index / 32] & (1 << (index % 32))) != 0;
}
inline
void allocate_frame(int index)
{
bit_map[index / 32] |= 1 << (index % 32);
}
inline
void clear_frame(int index)
{
bit_map[index / 32] &= ~(1 << (index % 32));
}
char* allocate_block(int block_count)
{
int index = 0, free_frames = 0;
while(index < mem_block_count)
{
if (!is_allocated(index))
{
free_frames++;
if (free_frames == block_count)
{
int frame_index = index - block_count + 1;
index = 0;
while(index < block_count)
{
allocate_block(frame_index + index);
index++;
}
return (buffer + frame_index * mem_block_size);
}
}
else free_frames = 0;
index++;
}
perror("memory error\n");
return 0;
}
基本思想是,您维护一个位图来跟踪分配的帧。每个帧充当固定大小的缓冲区。完成框架后,您可以通过在位图中设置 bit off 来将其标记为空闲。
我正在尝试开发一个简单的文件系统(Linux 内核)并且我正在考虑使用位图来跟踪 used/free 块,如下所述:
https://en.wikipedia.org/wiki/Free_space_bitmap
但是,我在 C 中找不到此类系统的任何实现。我想看一些示例,以便我可以实现与我的系统类似的东西。
有什么可以找到它们的建议吗?
这是我在阅读这个问题后做出的一个快速实现。
int mem_block_size;
int mem_block_count;
uint *bit_map;
char *buffer;
void init_memory_map(int block_size, int block_count)
{
mem_block_size = block_size;
mem_block_count = block_count;
buffer = (char*)malloc(block_size * block_count);
bit_map = (uint*)calloc((block_count / 32) + ((block_count % 32) != 0), 4);
}
inline
int is_allocated(int index)
{
return (bit_map[index / 32] & (1 << (index % 32))) != 0;
}
inline
void allocate_frame(int index)
{
bit_map[index / 32] |= 1 << (index % 32);
}
inline
void clear_frame(int index)
{
bit_map[index / 32] &= ~(1 << (index % 32));
}
char* allocate_block(int block_count)
{
int index = 0, free_frames = 0;
while(index < mem_block_count)
{
if (!is_allocated(index))
{
free_frames++;
if (free_frames == block_count)
{
int frame_index = index - block_count + 1;
index = 0;
while(index < block_count)
{
allocate_block(frame_index + index);
index++;
}
return (buffer + frame_index * mem_block_size);
}
}
else free_frames = 0;
index++;
}
perror("memory error\n");
return 0;
}
基本思想是,您维护一个位图来跟踪分配的帧。每个帧充当固定大小的缓冲区。完成框架后,您可以通过在位图中设置 bit off 来将其标记为空闲。