운영 체제에서 사용자 모드와 커널 모드의 차이점은 무엇입니까?
사용자 모드와 커널 모드의 차이점은 무엇이며, 둘 중 하나를 활성화하는 이유와 방법 및 사용 사례는 무엇입니까?
커널 모드
커널 모드에서 실행 코드는 기본 하드웨어에 대한 완전하고 제한없는 액세스 권한을 갖습니다. 모든 CPU 명령을 실행하고 모든 메모리 주소를 참조 할 수 있습니다. 커널 모드는 일반적으로 운영 체제의 가장 낮은 수준의 가장 신뢰할 수있는 기능을 위해 예약되어 있습니다. 커널 모드의 충돌은 치명적입니다. 그들은 전체 PC를 중지합니다.
사용자 모드
사용자 모드에서 실행 코드는 하드웨어 또는 참조 메모리에 직접 액세스 할 수 없습니다. 사용자 모드에서 실행되는 코드는 하드웨어 또는 메모리에 액세스하기 위해 시스템 API에 위임해야합니다. 이러한 종류의 격리를 통해 제공되는 보호 기능으로 인해 사용자 모드의 충돌은 항상 복구 할 수 있습니다. 컴퓨터에서 실행되는 대부분의 코드는 사용자 모드에서 실행됩니다.
더 읽어보기
컴퓨터가 작동 할 수있는 두 가지 모드입니다. 이전에는 컴퓨터가 큰 방 같았을 때 무언가 충돌하면 전체 컴퓨터가 중단됩니다. 그래서 컴퓨터 설계자들은 그것을 바꾸기로 결정합니다. 최신 마이크로 프로세서는 하드웨어에서 적어도 두 가지 상태를 구현합니다.
사용자 모드 :
- 모든 사용자 프로그램이 실행되는 모드. RAM 및 하드웨어에 액세스 할 수 없습니다. 그 이유는 모든 프로그램이 커널 모드에서 실행되면 서로의 메모리를 덮어 쓸 수 있기 때문입니다. 이러한 기능에 액세스해야하는 경우 기본 API를 호출합니다. 시스템 프로세스를 제외한 창에서 시작한 각 프로세스는 사용자 모드로 실행됩니다.
커널 모드 :
- 모든 커널 프로그램이 실행되는 모드 (다른 드라이버). 모든 리소스와 기본 하드웨어에 액세스 할 수 있습니다. 모든 CPU 명령을 실행할 수 있으며 모든 메모리 주소에 액세스 할 수 있습니다. 이 모드는 가장 낮은 수준에서 작동하는 드라이버를 위해 예약되어 있습니다.
전환이 발생하는 방식.
사용자 모드에서 커널 모드로의 전환은 CPU에 의해 자동으로 수행되지 않습니다. CPU가 인터럽트 (타이머, 키보드, I / O)에 의해 중단됩니다. 인터럽트가 발생하면 CPU는 현재 실행중인 프로그램의 실행을 중지하고 커널 모드로 전환하고 인터럽트 처리기를 실행합니다. 이 핸들러는 CPU의 상태를 저장하고, 작업을 수행하고, 상태를 복원하고 사용자 모드로 돌아갑니다.
http://en.wikibooks.org/wiki/Windows_Programming/User_Mode_vs_Kernel_Mode
http://tldp.org/HOWTO/KernelAnalysis-HOWTO-3.html
http://en.wikipedia.org/wiki/Direct_memory_access
http://en.wikipedia.org/wiki/Interrupt_request
Windows를 실행하는 컴퓨터의 프로세서에는 사용자 모드와 커널 모드의 두 가지 모드가 있습니다. 프로세서는 프로세서에서 실행중인 코드 유형에 따라 두 가지 모드 사이를 전환합니다. 응용 프로그램은 사용자 모드에서 실행되고 핵심 운영 체제 구성 요소는 커널 모드에서 실행됩니다. 많은 드라이버가 커널 모드에서 실행되지만 일부 드라이버는 사용자 모드에서 실행될 수 있습니다.
사용자 모드 응용 프로그램을 시작하면 Windows에서 응용 프로그램에 대한 프로세스를 만듭니다. 이 프로세스는 애플리케이션에 개인용 가상 주소 공간과 개인용 핸들 테이블을 제공합니다. 응용 프로그램의 가상 주소 공간은 개인용이므로 한 응용 프로그램은 다른 응용 프로그램에 속한 데이터를 변경할 수 없습니다. 각 응용 프로그램은 격리되어 실행되며 응용 프로그램이 충돌하는 경우 충돌은 해당 응용 프로그램으로 제한됩니다. 다른 응용 프로그램과 운영 체제는 충돌의 영향을받지 않습니다.
개인용 일뿐만 아니라 사용자 모드 응용 프로그램의 가상 주소 공간이 제한됩니다. 사용자 모드에서 실행중인 프로세서는 운영 체제 용으로 예약 된 가상 주소에 액세스 할 수 없습니다. 사용자 모드 응용 프로그램의 가상 주소 공간을 제한하면 응용 프로그램이 중요한 운영 체제 데이터를 변경하거나 손상시킬 수 있습니다.
커널 모드에서 실행되는 모든 코드는 단일 가상 주소 공간을 공유합니다. 이는 커널 모드 드라이버가 다른 드라이버 및 운영 체제 자체와 분리되지 않음을 의미합니다. 커널 모드 드라이버가 실수로 잘못된 가상 주소에 쓰는 경우 운영 체제 또는 다른 드라이버에 속한 데이터가 손상 될 수 있습니다. 커널 모드 드라이버가 충돌하면 전체 운영 체제가 충돌합니다.
Windows 사용자 인 경우이 링크를 통해 더 많은 정보를 얻을 수 있습니다.
나는 어둠 속에서 찔러서 당신이 Windows에 대해 이야기하고 있다고 생각할 것입니다. 간단히 말해서 커널 모드는 하드웨어에 대한 전체 액세스 권한을 갖지만 사용자 모드는 그렇지 않습니다. 예를 들어 대부분의 장치 드라이버는 아니지만 대부분의 장치 드라이버는 하드웨어의 세부 사항을 제어해야하기 때문에 커널 모드로 작성됩니다.
이 wikibook을 참조하십시오 .
CPU 링은 가장 명확한 구분입니다.
x86 보호 모드에서 CPU는 항상 4 개의 링 중 하나에 있습니다. Linux 커널은 0과 3 만 사용합니다.
- 커널의 경우 0
- 사용자 3 명
이것은 커널 대 사용자 영역의 가장 어렵고 빠른 정의입니다.
Linux가 링 1과 2를 사용하지 않는 이유 : CPU 권한 링 : 링 1과 2가 사용되지 않는 이유는 무엇입니까?
현재 링은 어떻게 결정됩니까?
현재 벨소리는 다음 조합으로 선택됩니다.
global descriptor table: a in-memory table of GDT entries, and each entry has a field
Privl
which encodes the ring.The LGDT instruction sets the address to the current descriptor table.
the segment registers CS, DS, etc., which point to the index of an entry in the GDT.
For example,
CS = 0
means the first entry of the GDT is currently active for the executing code.
What can each ring do?
The CPU chip is physically built so that:
ring 0 can do anything
ring 3 cannot run several instructions and write to several registers, most notably:
cannot change its own ring! Otherwise, it could set itself to ring 0 and rings would be useless.
In other words, cannot modify the current segment descriptor, which determines the current ring.
cannot modify the page tables: How does x86 paging work?
In other words, cannot modify the CR3 register, and paging itself prevents modification of the page tables.
This prevents one process from seeing the memory of other processes for security / ease of programming reasons.
cannot register interrupt handlers. Those are configured by writing to memory locations, which is also prevented by paging.
Handlers run in ring 0, and would break the security model.
In other words, cannot use the LGDT and LIDT instructions.
cannot do IO instructions like
in
andout
, and thus have arbitrary hardware accesses.Otherwise, for example, file permissions would be useless if any program could directly read from disk.
More precisely thanks to Michael Petch: it is actually possible for the OS to allow IO instructions on ring 3, this is actually controlled by the Task state segment.
What is not possible is for ring 3 to give itself permission to do so if it didn't have it in the first place.
Linux always disallows it. See also: Why doesn't Linux use the hardware context switch via the TSS?
How do how programs and operating systems transition between rings?
when the CPU is turned on, it starts running the initial program in ring 0 (well kind of, but it is a good approximation). You can think this initial program as being the kernel (but it is normally a bootloader that then calls the kernel still in ring 0).
when an userland process wants the kernel to do something for it like write to a file, it uses an instruction that generates an interrupt such as
int 0x80
to signal the kernel.When this happens, the CPU calls and interrupt callback handler which the kernel registered at boot time.
This handler runs in ring 0, which decides if the kernel will allow this action, do the action, and restart the userland program in ring 3.
when the
exec
system call is used (or when the kernel will start/init
), the kernel prepares the registers and memory of the new userland process, then it jumps to the entry point and switches the CPU to ring 3If the program tries to do something naughty like write to a forbidden register or memory address (because of paging), the CPU also calls some kernel callback handler in ring 0.
But since the userland was naughty, the kernel might kill the process this time, or give it a warning with a signal.
When the kernel boots, it setups a hardware clock with some fixed frequency, which generates interrupts periodically.
This hardware clock generates interrupts that run ring 0, and allow it to schedule which userland processes to wake up.
This way, scheduling can happen even if the processes are not making any system calls.
What is the point of having multiple rings?
There are two major advantages of separating kernel and userland:
- it is easier to make programs as you are more certain one won't interfere with the other. E.g., one userland process does not have to worry about overwriting the memory of another program because of paging, nor about putting hardware in an invalid state for another process.
- it is more secure. E.g. file permissions and memory separation could prevent a hacking app from reading your bank data. This supposes, of course, that you trust the kernel.
How to play around with it?
I've created a bare metal setup that should be a good way to manipulate rings directly: https://github.com/cirosantilli/x86-bare-metal-examples
I didn't have the patience to make a userland example unfortunately, but I did go as far as paging setup, so userland should be feasible. I'd love to see a pull request.
Alternatively, Linux kernel modules run in ring 0, so you can use them to try out privileged operations, e.g. read the control registers: How to access the control registers cr0,cr2,cr3 from a program? Getting segmentation fault
Here is a convenient QEMU + Buildroot setup to try it out without killing your host.
The downside of kernel modules is that other kthreads are running and could interfere with your experiments. But in theory you can take over all interrupt handlers with your kernel module and own the system, that would be an interesting project actually.
Negative rings
While negative rings are not actually referenced in the Intel manual, there are actually CPU modes which have further capabilities than ring 0 itself, and so are a good fit for the "negative ring" name.
One example is the hypervisor mode used in virtualization.
For further details see: https://security.stackexchange.com/questions/129098/what-is-protection-ring-1
ARM
In ARM, the rings are called Exception Levels instead, but the main ideas remain the same.
There exist 4 exception levels in ARMv8, commonly used as:
EL0: userland
EL1: kernel
EL2: hypervisors, for example Xen.
A hypervisor is to an OS, what an OS is to userland.
For example, Xen allows you to run multiple OSes such as Linux or Windows on the same system at the same time, and it isolates the OSes from one another for security and ease of debug, just like Linux does for userland programs.
Hypervisors are a key part of today's cloud infrastructure: they allow multiple servers to run on a single hardware, keeping hardware usage always close to 100% and saving a lot of money.
AWS for example used Xen until 2017 when its move to KVM made the news.
EL3: yet another level. TODO example.
The ARMv8 Architecture Reference Model DDI 0487C.a - Chapter D1 - The AArch64 System Level Programmer's Model - Figure D1-1 illustrates this beautifully:
Note how ARM, maybe due to the benefit of hindsight, has a better naming convention for the privilege levels than x86, without the need for negative levels: 0 being the lower and 3 highest. Higher levels tend to be created more often than lower ones.
The current EL can be queried with the MRS
instruction: what is the current execution mode/exception level, etc?
ARM does not require all exception levels to be present to allow for implementations that don't need the feature to save chip area. ARMv8 "Exception levels" says:
An implementation might not include all of the Exception levels. All implementations must include EL0 and EL1. EL2 and EL3 are optional.
QEMU for example defaults to EL1, but EL2 and EL3 can be enabled with command line options: qemu-system-aarch64 entering el1 when emulating a53 power up
Other answers already explained the difference between user and kernel mode. If you really want to get into detail you should get a copy of Windows Internals, an excellent book written by Mark Russinovich and David Solomon describing the architecture and inside details of the various Windows operating systems.
What
Basically the difference between kernel and user modes is not OS dependent and is achieved only by restricting some instructions to be run only in kernel mode by means of hardware design. All other purposes like memory protection can be done only by that restriction.
How
It means that the processor lives in either the kernel mode or in the user mode. Using some mechanisms the architecture can guarantee that whenever it is switched to the kernel mode the OS code is fetched to be run.
Why
Having this hardware infrastructure these could be achieved in common OSes:
- Protecting user programs from accessing whole the memory, to not let programs overwrite the OS for example,
- preventing user programs from performing sensitive instructions such as those that change CPU memory pointer bounds, to not let programs break their memory bounds for example.
'IT박스' 카테고리의 다른 글
해시 테이블에 비해 이진 검색 트리의 장점 (0) | 2020.08.31 |
---|---|
10.10 Yosemite에 Rubyracer gem을 설치하는 방법은 무엇입니까? (0) | 2020.08.31 |
T-SQL은 저장 프로 시저의 SELECTed 값을 가져옵니다. (0) | 2020.08.30 |
알고리즘이 O (log log n) 복잡성을 갖게하는 원인은 무엇입니까? (0) | 2020.08.30 |
반응 렌더 기능에서 빈 값을 반환 할 수 있습니까? (0) | 2020.08.30 |