本文原创为freas_1990,转载请标明出处:http://blog.youkuaiyun.com/freas_1990/article/details/18630413
Linux内核在古老时代,比较死板,没有较为灵活的接口给到内核开发人员。
kmalloc是其中一个,用于给内核开发人员提供内存获取接口。
如果没有kmalloc,内核的内存使用会非常死板,甚至可以说仅仅是一个玩具——想象一下,没有kmalloc,网络协议栈将如何实现呢?抓狂吧!
kmalloc的设计如下:
/*
* A block header. This is in front of every malloc-block, whether free or not.
*/
struct block_header {
unsigned long bh_flags;
union {
unsigned long ubh_length;
struct block_header *fbh_next;
} vp;
};
/* * The page descriptor is at the front of every page that malloc has in use. */ struct page_descriptor { struct page_descriptor *next; struct block_header *firstfree; int order; int nfree; };
#define PAGE_DESC(p) ((struct page_descriptor *)(((unsigned long)(p)) & PAGE_MASK)) /* * A size descriptor describes a specific class of malloc sizes. * Each class of sizes has its own freelist. */ struct size_descriptor { struct page_descriptor *firstfree; int size; int nblocks; int nmallocs; int nfrees; int nbytesmalloced; int npages; };设计思想和malloc大同小异。
kmalloc()的filter逻辑非常复杂,这里不列举了,感兴趣的童鞋可以打开source code看一下:)