Al Viro does not often stray outside of the core virtual filesystem area; when he does, it is usually worthy of note. Recently, he wandered into memory management with this patch series to the slab allocator and some of its users. Kernel developers will often put considerable effort into small optimizations, but it is still interesting to look at just how much effort has gone toward the purpose of avoiding a single pointer dereference in some memory-allocation hot paths.
Al Viro 通常很少涉足核心虚拟文件系统(VFS)以外的领域;而一旦他这样做,往往就值得关注。最近,他通过一组针对 slab 分配器及其部分使用者的补丁,进入了内存管理领域。内核开发者经常会在一些微小的优化上投入大量精力,但即便如此,看到为了在某些内存分配的热点路径中避免一次指针解引用而付出如此多的努力,仍然令人印象深刻。
The slab cache
slab 缓存
The kernel\’s slab allocator exists to provide quick allocations of fixed-sized objects. For example, the kernel uses large numbers of dentry structures to cache information about file names; on the system where this is being written, there are currently over 800,000 active dentry structures, as reported by /proc/slabinfo. Requests to allocate and free these structures are frequent, so their performance matters.
内核中的 slab 分配器用于快速分配固定大小的对象。例如,内核会使用大量的 dentry 结构来缓存文件名相关的信息;在撰写本文的系统上,根据 /proc/slabinfo 的统计,目前有超过 80 万个活跃的 dentry 结构。这些结构的分配和释放请求非常频繁,因此它们的性能至关重要。
The slab allocator provides a function, kmem_cache_create(), that returns a pointer to a newly allocated and initialized kmem_cache structure. This pointer, in turn, can be used (by calling kmem_cache_alloc()), to allocate a new object of the size that this particular cache was configured for. The virtual filesystem layer, for example, can use a slab cache to allocate dentry structures. The slab allocator will maintain a cache of available structures, handing them out on request; it will also make an effort to lay them out optimally in pages of memory obtained from the page allocator. Even simple operations in the kernel may involve allocating and freeing a number of objects, so considerable effort has gone into optimizing the slab allocator over time.
slab 分配器提供了一个函数 kmem_cache_create(),它会返回一个指向新分配并初始化完成的 kmem_cache 结构的指针。随后可以通过调用 kmem_cache_alloc(),使用这个指针来分配该缓存所配置大小的新对象。例如,虚拟文件系统层就可以使用一个 slab 缓存来分配 dentry 结构。slab 分配器会维护一个可用对象的缓存池,在请求到来时直接分发;同时,它还会尽量将这些对象在从页分配器获取的内存页中进行最优布局。即便是内核中很简单的操作,也可能涉及多个对象的分配和释放,因此 slab 分配器多年来一直是重点优化对象。
While slab caches can be created and destroyed dyn





