Alex Rivera | Logout

Why does Linux on x86 use different segments for user processes and the kernel?

Asked 2011-01-01T18:01:56.487
19

So, I know that Linux uses four default segments for an x86 processor (kernel code, kernel data, user code, user data), but they all have the same base and limit (0x00000000 and 0xfffff), meaning each segment maps to the same set of linear addresses.

Given this, why even have user/kernel segments? I understand why there should be separate segments for code and data (just due to how the x86 processor deals with the cs and ds registers), but why not have a single code segment and a single data segment? Memory protection is done through paging, and the user and kernel segments map to the same linear addresses anyway.

Edit
Report

1 Answer

16

The x86 architecture associates a type and a privilege level with each segment descriptor. The type of a descriptor allows segments to be made read only, read/write, executable, etc., but the main reason for different segments having the same base and limit is to allow a different descriptor privilege level (DPL) to be used.

The DPL is two bits, allowing the values 0 through 3 to be encoded. When the privilege level is 0, then it is said to be ring 0, which is the most privileged. The segment descriptors for the Linux kernel are ring 0 whereas the segment descriptors for user space are ring 3 (least privileged). This is true for most segmented operating systems; the core of the operating system is ring 0 and the rest is ring 3.

The Linux kernel sets up, as you mentioned, four segments:

  • __KERNEL_CS (Kernel code segment, base=0, limit=4GB, type=10, DPL=0)
  • __KERNEL_DS (Kernel data segment, base=0, limit=4GB, type=2, DPL=0)
  • __USER_CS (User code segment, base=0, limit=4GB, type=10, DPL=3)
  • __USER_DS (User data segment, base=0, limit=4GB, type=2, DPL=3)

The base and limit of all four are the same, but the kernel segments are DPL 0, the user segments are DPL 3, the code segments are executable and readable (not writable), and the data segments are readable and writable (not executable).

See also:

Your Answer