Виртуальная память и MMU: когда они используются, а когда нет?

1194
iMineLink

Я задаюсь вопросом о том, как можно управлять системой виртуальной памяти вместе с MMU, когда необходимо поддерживать некоторые «фиксированные» адреса в адресном пространстве.

Например, когда машина загружается, ЦПУ начинает считывать первую инструкцию с фиксированного адреса (который сопоставлен с каким-либо ПЗУ), затем выдает адреса периферийным устройствам (если используется система ввода-вывода с отображением в памяти), и Затем ОС загружается. Я также знаю, что подпрограммы прерывания и подобные вещи должны находиться в «фиксированной» позиции в памяти, и эти вещи загружаются ОС.

Я могу подумать, что MMU отключен в таком процессе, а затем он включен после загрузки ОС.

Я могу подумать, что процессы, описанные выше, используют системное адресное пространство и что системное адресное пространство не виртуализировано, несмотря на то, что пользовательское адресное пространство фактически есть.

Это приведет к тому, что пул физических адресов останется неизменным для доступа к периферийным устройствам ввода-вывода, подпрограммам прерывания и т. Д., А также к виртуальному пользовательскому пространству, управляемому MMU, где процессы могут обрабатывать все данные, необходимые для разработки., требующий к ОС доступа к периферийным устройствам ввода / вывода.

Но я не уверен в этих вещах. Вот я и спрашиваю, когда MMU на самом деле включен? Это касается всех адресов или только адресов пользователя? Правда ли, что некоторые адреса могут обходить MMU даже во время работы системы, чтобы получить доступ к фиксированным позициям памяти? Или я упускаю некоторые важные подсказки?

3

2 ответа на вопрос

1
Jamie Hanrahan

Sorry but the speculation in the chosen answer is misleading, and leaves out the most important aspect, which is address translation via page tables.

It is true that when any PC-compatible machine boots it starts out in "real mode". And modern 32-bit operating systems on x86 do run in "protected mode", which includes segmented addressing as defined by the GDT. However they then also enable page table-based address translation by setting the PG (paging) bit, bit 31, in CR0. This is never turned off for the life of the OS.

Also, in most modern 32-bit operating systems, GDT-based segmented addressing is essentially bypassed: All of the commonly-used GDTEs are set up with base address 0, size 4 billion bytes. So although the MMU does go through the motions of adding the relevant segment "base address" to the "displacement" that comes from the instruction, this is effectively a no-op. A different set of GDTEs is used for ring 0 vs ring 3, but they all have the same base address and size. The "privilege level" fields (0 vs 3) are about all that is different. This enables the "privileged access" bit in the page table entries to be effective, allowing memory to be protected for kernel- mode or user+kernel mode access on a page-by-page basis. That is not possible with segment descriptors; they are far too coarse-grained.

In x64 CPUs the segmenting mechanism essentially disappears while in long mode. Page table-based address translation of course still happens as long as the PG bit is set, which it is throughout the life of the OS. The MMU is most emphatically not disabled while in kernel mode, nor does the "SO" (or anything) use 1:1 mapping between virtual and physical addresses.

Accesses to known physical addresses, like those assigned to PCI-like peripherals, is done by allocating unused virtual addresses and setting up the correspondnig page table entries with the required physical page numbers. Code in device drivers then uses the virtual addresses.

Yes, DMA primarily works on physical addresses. A dumb/cheap DMA controller indeed just transfers to a physically contiguous buffer with a given start address and length. To support such devices either the OS or device driver will allocate physically contiguous "bounce buffers" for the DMA device to access, and copy data between there and the user's buffer.

Smart/more expensive DMA controllers can handle buffers that occupy discontiguous ranges of physical addressses (referred to as "scatter-gather mapping"). These are much preferred for high-performance devices.

An IOMMU can allow stupid/cheap DMA controllers to access a physically discontiguous buffer as if it was contiguous. However, platforms with IOMMUs are not yet ubiquitous enough to say "your platform must have an IOMMU for our OS". Therefore, at present, IOMMUs are primarily used by virtual machine monitors.

-1
LawrenceC

x86 CPUs boot up in a "real mode" - basically, 16-bit mode where the CPU can only see the first 1MB of RAM. One of the first tasks of a BIOS bootloader (or UEFI may do this directly) is to switch the CPU into "protected" mode. Protected memory is available in this mode, and the CPU has privilege levels in this mode - generally "kernel" and "user."

I'm a bit fuzzy on this, but how the MMU maps memory is controlled by the Global Descriptor Table (GDT). Kernel mode can change the GDT, user mode cannot.

So when kernel mode is entered, it can set the GDT to a memory mapping that either identity maps all memory (i.e. acts like it's not mapped at all) or maps it in a way that gives it access to all devices, etc. When it returns to user mode, it can load more restrictive GDT before handing control back.

I might be wrong - it may be when the CPU enters kernel mode it simply disables the MMU but I do believe it can be used by kernel mode as well in this fashion.

Это имеет смысл! Так что либо SO использует отображение памяти «1: 1», либо вообще отключает MMU в режиме ядра ... Такие вещи, как контроллеры DMA, которым присваивается базовый адрес и размер буфера для передачи данных непосредственно из или в RAM, используя поэтому адреса, которые последовательно, управляются в пространстве ядра? iMineLink 10 лет назад 0
Есть некоторые подробности о загрузчике Windows в http://channel9.msdn.com/Shows/Going+Deep/Inside-Windows-8-Chris-Stevens-Boot-Environment David Marshall 10 лет назад 0
DMA, вероятно, работает только на уровне физических адресов - хотя более новые процессоры имеют IOMMU, который может разрешить преобразование адресов ввода-вывода устройства. LawrenceC 10 лет назад 0
@DavidMarshall спасибо за видео, я скачал его и посмотрю как можно скорее. > Ультразвуковой нож интересный! iMineLink 10 лет назад 0

Похожие вопросы