1. 位图是什么?
位图是一种资源管理的方式,按位bit与资源一对一的对应关系。
位图中的每一位将于内存中的每一页一一对应。
一个位有 2 种状态,即 0 和 1 ,用位图中的每一个位来表示实际物理内存的 4KB(一页) 。
如果某位为 0 ,表示该位对应的页未分配。
反之,某位为 1 ,表示该位对应的页已分配。
2. 实现位图
实现位图,用到两个文件,bitmap.c 和 bitmap.h。
bitmap.h 是关于位图的定义和一些函数声明。
bitmap.c 是操作位图的一些函数。
bitmap.h
#ifndef __LIB_KERNEL_BITMAP_H
#define __LIB_KERNEL_BITMAP_H
#include "../std_int.h"
#include "../string.h"
#define BITMAP_MASK 1
struct bitmap {
uint32_t btmp_bytes_len;
/* 在遍历位图时,整体上以字节为单位,细节上是以位为单位,所以此处位图的指针必须是单字节 */
uint8_t* bits;
};
void bitmap_init(struct bitmap* btmp);
bool bitmap_scan_test(struct bitmap* btmp, uint32_t bit_idx);
int bitmap_scan(struct bitmap* btmp, uint32_t cnt);
void bitmap_set(struct bitmap* btmp, uint32_t bit_idx, int8_t value);
#endif
bitmap.h 中定义一个结构体 struct bitmap, 它包含两个元素,位图的大小和位图的地址。
通过这个结构体就能找到位图。
bitmap.c
#include "bitmap.h"