What is kernel mode in linux

Kernel mode setting

This article or section needs expansion.

Kernel Mode Setting (KMS) is a method for setting display resolution and depth in the kernel space rather than user space.

The Linux kernel’s implementation of KMS enables native resolution in the framebuffer and allows for instant console (tty) switching. KMS also enables newer technologies (such as DRI2) which will help reduce artifacts and increase 3D performance, even kernel space power-saving.

Contents

Background

Previously, setting up the video card was the job of the X server. Because of this, it was not easily possible to have fancy graphics in virtual consoles. Also, each time a switch from X to a virtual console was made ( Ctrl+Alt+F2 ), the server had to give control over the video card to the kernel, which was slow and caused flickering. The same «painful» process happened when the control was given back to the X server ( Alt+F7 when X runs in VT7).

With Kernel Mode Setting (KMS), the kernel is now able to set the mode of the video card. This makes fancy graphics during bootup, virtual console and X fast switching possible, among other things.

Installation

At first, note that for any method you use, you should always disable:

  • Any vga= options in your bootloader as these will conflict with the native resolution enabled by KMS.
  • Any video= lines that enable a framebuffer that conflicts with the driver.
  • Any other framebuffer drivers (such as uvesafb).

Late KMS start

Intel, Nouveau, ATI and AMDGPU drivers already enable KMS automatically for all chipsets, so you need not install it manually.

The proprietary NVIDIA driver supports KMS (since 364.12), which has to be manually enabled.

Early KMS start

KMS is typically initialized after the initramfs stage. However it is possible to already enable KMS during the initramfs stage. Add the required module for the video driver to the MODULES array in /etc/mkinitcpio.conf :

  • amdgpu for AMDGPU, or radeon when using the legacy ATI driver.
  • i915 for Intel graphics.
  • nouveau for the open-source Nouveau driver.
  • mgag200 for Matrox graphics.
  • Depending on QEMU graphics in use: virtio-gpu for VirtIO, qxl for QXL, or cirrus for Cirrus.
  • nvidia nvidia_modeset nvidia_uvm nvidia_drm for nvidia driver. See NVIDIA#DRM kernel mode setting for details.

For example to enable early KMS for the Intel graphics driver:

If you are using a custom EDID file (not applicable for the built-in resolutions), you should embed it into initramfs as well:

Troubleshooting

My fonts are too tiny

See Linux console#Fonts for how to change your console font to a large font. The Terminus font ( terminus-font ) is available in many sizes, such as ter-132n which is larger.

Alternatively, disabling modesetting might switch to lower resolution and make fonts appear larger.

Problem upon bootloading and dmesg

Polling for connected display devices on older systems can be quite expensive. Poll will happen periodically and can in worst cases take several hundred milliseconds, depending on the hardware. This will cause visible stalls, for example in video playback. These stalls might happen even when your video is on HDP output but you have other non HDP outputs in your hw configuration. If you experience stalls in display output occurring every 10 seconds, disabling polling might help.

If you see an error code of 0x00000010 (2) while booting up, (you will get about 10 lines of text, the last part denoting that error code), use:

Forcing modes and EDID

If your native resolution is not automatically configured or no display at all is detected, then your monitor might send none or just a skewed EDID file. The kernel will try to catch this case and will set one of the most typical resolutions.

Читайте также:  Bcm43142 wireless network adapter driver windows 10 sony vaio

In case you have the EDID file for your monitor you merely need to explicitly enforce it (see below). However most often one does not have direct access to a sane file and it is necessary to either extract an existing one and fix it or to generate a new one.

Generating new EDID binaries for various resolutions and configurations is possible during kernel compilation by following the upstream documentation (also see here for a short guide). Other solutions are outlined in details in this article. Extracting an existing one is in most cases easier, e.g. if your monitor works fine under Windows you might have luck extracting the EDID from the corresponding driver, or if a similar monitor works which has the same settings you may use get-edid from the read-edid package. You can also try looking in /sys/class/drm/*/edid .

After having prepared your EDID place it in a folder, e.g. called edid under /usr/lib/firmware and copy your binary into it.

To load it at boot, specify the following in the kernel command line:

For kernels older than 4.13, use this line instead:

In order to apply it only to a specific connector use:

For the built-in resolutions, refer to the table below. The Name column specifies the name which one is supposed to use in order to enforce its usage.

Resolution Name
800×600 edid/800×600.bin
1024×768 edid/1024×768.bin
1280×1024 edid/1280×1024.bin
1600×1200 (kernel 3.10 or higher) edid/1600×1200.bin
1680×1050 edid/1680×1050.bin
1920×1080 edid/1920×1080.bin

If you are doing early KMS, you must include the custom EDID file in the initramfs, otherwise you will run into problems.

The value of the drm.edid_firmware parameter may also be altered after boot by writing to /sys/module/drm/parameters/edid_firmware :

This will only take affect for newly plugged in displays, already plugged-in screens will continue to use their existing EDID settings. For external displays replugging them is sufficient to see the effect however.

Since kernel 3.15, to load an EDID after boot, you can use debugfs instead of a kernel command line parameter if the kernel is not in lockdown mode. This is very useful if you swap the monitors on a connector or just for testing. Once you have an EDID file as above, run:

Forcing modes

A mode can be forced on the kernel command line. Unfortunately, the command line option video is poorly documented in the DRM case. Bits and pieces on how to use it can be found in

  • https://cgit.freedesktop.org/nouveau/linux-2.6/tree/Documentation/fb/modedb.txt
  • https://cgit.freedesktop.org/nouveau/linux-2.6/tree/drivers/gpu/drm/drm_fb_helper.c
  • : Connector, e.g. DVI-I-1, see /sys/class/drm/ for available connectors
  • x : resolution
  • M : compute a CVT mode?
  • R : reduced blanking?
  • — : color depth
  • @ : refresh rate
  • i : interlaced (non-CVT mode)
  • m : margins?
  • e : output forced to on
  • d : output forced to off
  • D : digital output forced to on (e.g. DVI-I connector)

You can override the modes of several outputs using video= several times, for instance, to force DVI to 1024×768 at 85 Hz and TV-out off:

To get the name and current status of connectors, you can use the following shell oneliner:

Disabling modesetting

You may want to disable KMS for various reasons. To disable KMS add nomodeset as a kernel parameter. See Kernel parameters for more info.

Источник

Kernel mode setting (Русский)

Эта статья или раздел нуждается в переводе

Kernel Mode Setting (KMS) представляет собой метод для задания разрешения дисплея и глубины в пространстве ядра, а не в пространстве пользователя.

Реализация KMS в ядре Linux активирует родное расширение в framebuffer и допускает мгновенное переключение консолей (tty). KMS содержит новые технологии (такие как DRI2) которые помогают снизить количество артефактов и увеличить производительность в 3D, даже при включенном режиме энергосбережения.

Contents

История

Ранее настройками видео карты занимался непосредственно X сервер. По этой причине достигнуть высокого качества графики в tty консолях было непросто. Кроме того, каждый раз при переключении из X в виртуальную консоль с помощью комбинации клавиш ( Ctrl+Alt+F1 ) сервер должен был передавать управление видеокартой ядру, что было медленным и вызывало мерцания. Особенно «болезненным» был переход управления обратно к X серверу ( Ctrl+Alt+F7 ).

Читайте также:  Ssh key linux ���������

С использованием Kernel Mode Setting (KMS) ядру стала доступна установка режимов видео карты. Наряду с другими достоинствами это улучшает визуальные эффекты при установке параметров графики, а также позволяет быстрее переключаться между виртуальными консолями и X.

Установка

Обратите внимание — для любых используемых Вами методов необходимо всегда отключать:

  • Любые vga= режимы в загрузчике, так как это вызовет конфликт с разрешением, активированным в KMS.
  • Любые video= строки, активирующие framebuffer, что вызовет конфликт с драйвером.
  • Любые другие драйвера framebuffer (такие как uvesafb).

Поздний запуск KMS

Драйвера Intel, Nouveau и ATI уже активируют KMS автоматически для всех чипсетов, так что не требуется ручной настройки.

Проприетарные драйвера NVIDIA и AMD Catalyst не используют стек свободных драйверов. В случае использования KMS необходимо заменить ими свободные драйвера.

Ранний запуск KMS

Ранний запуск KMS возможен во время процесса загрузки путём добавления модуля radeon (для ATI/AMD карт), i915 (для графики Intel) или nouveau (для карт Nvidia) в строку MODULES в /etc/mkinitcpio.conf . Например:

Если Вы используете изменённый файл EDID (не совпадающий с преднастроенными разрешениями), следует встроить его в initramfs:

Пересоберите образ ядра (смотрите статью о mkinitcpio для получения дополнительной информации):

Устранение неполадок

Мои шрифты слишком маленькие

Смотрите статью Fonts о том, как изменить шрифт в консоли на более крупный. Например, шрифт Terminus ( terminus-font ) доступен в нескольких размерах, в том числе и в больших.

Проблемы во время загрузки и dmesg

Опрос подключенных дисплеев на старых системах может быть довольно громоздким. Опрос происходит периодически и может занять несколько сотен миллисекунд в зависимости от оборудования.

Если выскакивает ошибка с кодом 0x00000010 (2) во время процесса загрузки (Вы можете получить около 10 строк текста, последняя часть содержит этот код), используйте:

Принудительный режим и EDID

Эта статья или раздел нуждается в переводе

В случае когда Ваш дисплей не отправляет соответствующий EDID или вызывает какие-либо проблемы, Вы будете уведомлены, что родное разрешение автоматически не настроено или не отображается вообще. Ядро имеет условие для загрузки бинарных данных EDID, и поддерживает четыре наиболее типичных разрешения.

Если у Вас имеется EDID файл для Вашего монитора, процесс упрощается. Если нет, можете использовать один из преднастроенных EDID файлов (или сгенерированных однажды во время компиляции ядра, больше информации здесь) или создать свой собственный EDID.

В случае когда EDID имеется (например извлечённый из Windows драйверов для Вашего монитора или полученный командой get-edid из пакета read-edid ), создайте директорию edid в /usr/lib/firmware :

затем скопируйте Ваш файл в директорию /usr/lib/firmware/edid .

Для запуска во время загрузки, следуйте указаниям из kernel command line:

Также, можно указать только для заданного дисплея:

Для преднастроенные разрешений, смотри таблицу имён спецификаций:

Разрешение Имя спецификации
1024×768 edid/1024×768.bin
1280×1024 edid/1280×1024.bin
1600×1200 (kernel 3.10 or higher) edid/1600×1200.bin
1680×1050 edid/1680×1050.bin
1920×1080 edid/1920×1080.bin

Если осуществлён ранний запуск KMS, необходимо включить кастомизированный файл EDID в initramfs иначе возможны проблемы.

Вы также можете собрать собственный EDID с использованием makefile входящего в ядро. Полная информация доступна по адресам здесь и здесь.

Режим может быть принудительным в командной строке ядра. К сожалению, опция командной строки видео бедно документирована в случае с DRM. Части и куски того как это использовать можно найти в

  • : Коннектор, т.н. DVI-I-1, смотри доступные здесь /sys/class/drm/
  • x : разрешение
  • M: посчитать режим CVT?
  • R: снижение мерцания?
  • — : глубина цвета
  • @ : частота обновления
  • i: черезстрочный (non-CVT mode)
  • m: поля?
  • e: принудительный вывод on
  • d: принудительный вывод off
  • D: принудительный цифровой вывод on (т.н. DVI-I коннектор)

Вы можете переопределять режимы нескольких выходов использующих «video» несколько раз, в частности, для вывода DVI в 1024×768 на 85 Hz и отключения TV-out:

Для получения имени и текущего статуса коннекторов, Вы можете использовать однострочную команду:

Отключение modesetting

Вы можете захотеть отключить KMS по различным причинам, таким как получение пустого экрана или «no signal» ошибку с монитора, когда используются драйвера Catalyst, и т.п. Для отключения KMS добавьте nomodeset в параметры ядра. См. Kernel parameters для более подробной информации.

Читайте также:  Скрин рабочего стола windows 10 приложение

Источник

What is the Linux kernel?

Overview

The Linux® kernel is the main component of a Linux operating system (OS) and is the core interface between a computer’s hardware and its processes. It communicates between the 2, managing resources as efficiently as possible.

The kernel is so named because—like a seed inside a hard shell—it exists within the OS and controls all the major functions of the hardware, whether it’s a phone, laptop, server, or any other kind of computer.

What the kernel does

The kernel has 4 jobs:

Memory management: Keep track of how much memory is used to store what, and where

  • Process management: Determine which processes can use the central processing unit (CPU), when, and for how long
  • Device drivers: Act as mediator/interpreter between the hardware and processes
  • System calls and security: Receive requests for service from the processes
  • The kernel, if implemented properly, is invisible to the user, working in its own little world known as kernel space, where it allocates memory and keeps track of where everything is stored. What the user sees—like web browsers and files—are known as the user space. These applications interact with the kernel through a system call interface (SCI).

    Think about it like this. The kernel is a busy personal assistant for a powerful executive (the hardware). It’s the assistant’s job to relay messages and requests (processes) from employees and the public (users) to the executive, to remember what is stored where (memory), and to determine who has access to the executive at any given time and for how long.

    Where the kernel fits within the OS

    To put the kernel in context, you can think of a Linux machine as having 3 layers:

    1. The hardware: The physical machine—the bottom or base of the system, made up of memory (RAM) and the processor or central processing unit (CPU), as well as input/output (I/O) devices such as storage, networking, and graphics. The CPU performs computations and reads from, and writes to, memory.
    2. The Linux kernel: The core of the OS. (See? It’s right in the middle.) It’s software residing in memory that tells the CPU what to do.
    3. User processes: These are the running programs that the kernel manages. User processes are what collectively make up user space. User processes are also known as just processes. The kernel also allows these processes and servers to communicate with each other (known as inter-process communication, or IPC).

    Code executed by the system runs on CPUs in 1 of 2 modes: kernel mode or user mode. Code running in the kernel mode has unrestricted access to the hardware, while user mode restricts access to the CPU and memory to the SCI. A similar separation exists for memory (kernel space and user space). These 2 small details form the base for some complicated operations like privilege separation for security, building containers, and virtual machines.

    This also means that if a process fails in user mode, the damage is limited and can be recovered by the kernel. However, because of its access to memory and the processor, a kernel process crash can crash the entire system. Since there are safeguards in place and permissions required to cross boundaries, user process crashes usually can’t cause too many problems.

    Why choose Red Hat?

    At Red Hat, Linux is the foundation of everything we do. Red Hat is the second largest corporate contributor to the Linux kernel, bringing with it the experience and expertise of 25 years and a large community of partners, customers, and experts from across the industry. That’s a long relationship, with a history and level of experience that’s hard to come by.

    The Linux kernel is open source, and open source is at the core of Red Hat’s values. Learn why we’ve built our company on our conviction that Red Hat® Enterprise Linux is the best.

    Источник

    Оцените статью