1

这篇文章中我意识到:

kmalloc 可以处理的最小分配是 32 或 64 字节

您取回的实际内存取决于系统的架构

但在那里和其他网站上也提到了内存页面大小。我无法弄清楚页面大小与最小kmalloc()分配有何关系?页面大小通常是 4096 字节,但最小的分配是 32 或 64 字节(取决于 arch)。

那么最小kmalloc()分配和页面大小有什么关系呢?为什么最小的分配是 32 或 64 字节而不是 16(例如)?

4

1 回答 1

0

那么最小kmalloc()分配和页面大小有什么关系呢?

没有任何。他们是无关的。

源代码中可以看到:

#ifdef CONFIG_SLAB
// ...
#ifndef KMALLOC_SHIFT_LOW
#define KMALLOC_SHIFT_LOW   5
#endif

#ifdef CONFIG_SLUB
// ...
#ifndef KMALLOC_SHIFT_LOW
#define KMALLOC_SHIFT_LOW   3
#endif
#endif

#ifdef CONFIG_SLOB
// ...
#ifndef KMALLOC_SHIFT_LOW
#define KMALLOC_SHIFT_LOW   3
#endif
#endif

// ...

#ifndef KMALLOC_MIN_SIZE
#define KMALLOC_MIN_SIZE (1 << KMALLOC_SHIFT_LOW)
#endif

最终为不同分配器定义的宏都不依赖于页面大小,因此页面大小和最小分配大小KMALLOC_MIN_SIZE之间没有关系。kmalloc()

但是,在某些架构上,如果kmalloc()内存也用于直接内存访问,则最小大小可能会有所不同。这就是为什么你看到#ifndef上面的各种。它仍然与页面大小无关。

/*
 * Some archs want to perform DMA into kmalloc caches and need a guaranteed
 * alignment larger than the alignment of a 64-bit integer.
 * Setting ARCH_KMALLOC_MINALIGN in arch headers allows that.
 */
#if defined(ARCH_DMA_MINALIGN) && ARCH_DMA_MINALIGN > 8
#define ARCH_KMALLOC_MINALIGN ARCH_DMA_MINALIGN
#define KMALLOC_MIN_SIZE ARCH_DMA_MINALIGN
#define KMALLOC_SHIFT_LOW ilog2(ARCH_DMA_MINALIGN)
#else
#define ARCH_KMALLOC_MINALIGN __alignof__(unsigned long long)
#endif

的值ARCH_DMA_MINALIGN是特定于体系结构的,通常与处理器 L1 缓存大小有关,例如ARM

#define L1_CACHE_SHIFT      CONFIG_ARM_L1_CACHE_SHIFT
#define L1_CACHE_BYTES      (1 << L1_CACHE_SHIFT)

/*
 * Memory returned by kmalloc() may be used for DMA, so we must make
 * sure that all such allocations are cache aligned. Otherwise,
 * unrelated code may cause parts of the buffer to be read into the
 * cache before the transfer is done, causing old data to be seen by
 * the CPU.
 */
#define ARCH_DMA_MINALIGN   L1_CACHE_BYTES
于 2020-02-28T02:07:17.720 回答