19

remap_pfn_range函数(用于mmap驱动程序中的调用)可用于将内核内存映射到用户空间。它是如何完成的?任何人都可以解释精确的步骤吗?内核模式是特权模式 (PM),而用户空间是非特权 (NPM)。在 PM 中,CPU 可以访问所有内存,而在 NPM 中,某些内存受到限制 - CPU 无法访问。当remap_pfn_range被调用时,仅限于 PM 的内存范围现在如何可供用户空间访问?

remap_pfn_range代码有pgprot_t struct。这是与保护映射相关的结构。什么是保护映射?是上面问题的答案吗?

4

2 回答 2

18

It's simple really, kernel memory (usually) simply has a page table entry with the architecture specific bit that says: "this page table entry is only valid while the CPU is in kernel mode".

What remap_pfn_range does is create another page table entry, with a different virtual address to the same physical memory page that doesn't have that bit set.

Usually, it's a bad idea btw :-)

于 2012-01-09T12:41:25.437 回答
10

该机制的核心是页表MMU:

相关图片1 http://windowsitpro.com/content/content/3686/figure_01.gif

或这个:

相关图片

上图都是x86硬件内存MMU的特性,与Linux内核无关。

下面描述了 VMA 如何链接到进程的 task_struct:

相关图片 http://image9.360doc.com/DownloadImg/2010/05/0320/3083800_2.gif

相关图片
(来源:slideplayer.com

并在这里查看函数本身:

http://lxr.free-electrons.com/source/mm/memory.c#L1756

物理内存中的数据可以通过内核的PTE被内核访问,如下图:

页面保护标志linux内核的图像结果
(来源:tldp.org

但是在调用 remap_pfn_range() 之后,派生了一个 PTE(用于现有内核内存,但要在用户空间中访问它)(具有不同的页面保护标志)。进程的 VMA 内存将更新为使用此 PTE 访问相同的内存 - 从而最大限度地减少复制浪费内存的需要。但是内核和用户空间PTE有不同的属性——用来控制对物理内存的访问,VMA也会在进程级别指定属性:

vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP;

于 2012-01-31T07:23:25.350 回答