i试图开发一个简单的文件系统(Linux内核),我正在考虑使用位图跟踪以下所述的使用/自由块:
https://en.wikipedia.org/wiki/free_space_bitmap
nocey,我找不到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_frame(frame_index + index);
index++;
}
return (buffer + frame_index * mem_block_size);
}
}
else free_frames = 0;
index++;
}
perror("memory error\n");
return 0;
}
基本思想是,您要维护一些位图,以保留分配框架的跟踪。每个框架作为固定尺寸的缓冲区。完成框架后,您可以通过在位映射中放置位。