Kernel/Gentoo Kernel Configuration Guide/ru

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

Введение
Операционной системой Gentoo предусматриваются два способа управления установкой и обновлением ядра: автоматический (genkernel) и вручную. Хотя автоматический способ может рассматриваться как более легкий для пользователя, существует множество причин, по которым большинство пользователей Gentoo выбирают конфигурацию ядра вручную: большая гибкость, меньшие размеры ядра, более короткое время компиляции, приобретение опыта, сильная скука и т. д.

В этом руководстве не охватывается автоматический способ конфигурации ядра (genkernel). Если для компиляции и установки ядра требуется использовать утилиту genkernel, обратитесь к документации по Genkernel.

Данное руководство не стремится задокументировать процесс конфигурации вручную от начала до конца -- процесс конфигурации опирается на определенную долю здравого смысла и относительно высокий уровень технической подготовки и знаний о системе. Вместо этого, в руководстве вводятся основные представления о конфигурации ядра вручную и описываются в подробностях наиболее распространенные подводные камни, с которыми сталкиваются пользователи.

Данный документ написан с учетом последних версий ядер и наиболее распространенных архитектур компьютера. Некоторые подробности могут отличаться в случае использования старых ядер или более экзотических архитектур, но большая часть содержимого будет все же применима.

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


 * В Руководстве по версиям ядер перечислены различные доступные пакеты с исходными текстами ядра.
 * В Руководстве по обновлению ядра объясняется как обновить ядро или перейти с одного на другое.
 * В Настольной книге Gentoo также охватываются некоторые аспекты установки ядра.

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

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

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

Сравнение встроенных в ядро параметров и загружаемых модулей ядра
Большинство параметров конфигурации могут находиться в трех состояниях: они могут быть как отключены вовсе (N), прямо встроены в ядро (Y), или собраны в качестве модулей (M). Модули хранятся вне ядра на файловой системе, в то время как встроенные компоненты встраиваются прямо в образ ядра.

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

С некоторыми настройками, встроенные параметры являются абсолютной необходимостью. Например, если раздел root расположен на файловой системе, система не загрузится, если ext2 был встроен в качестве модуля (системе потребуется обратиться к разделу root чтобы найти модуль ext2, но обращения не произойдет до тех пор, пока модуль ext2 не будет загружен!).

Hardware support
Beyond detecting the architecture type of your system, the configuration utility makes no attempt to identify which hardware is actually present in your system. While there are default settings for some hardware support, you almost certainly need to find and select the configuration options relevant to your system's hardware configuration.

This simply requires knowledge of the components inside and connected to your computer, or for you to identify these components. For most internal components, you need to identify the chipset used on each one, rather than the retail product name.

There are some utilities available that will help you. (part of the package) will identify your PCI-based and AGP-based hardware, and this includes components built onto the motherboard itself. (from the package) will identify devices connected to USB ports.

The situation is somewhat confused by varying degrees of standardisation in the hardware world. Unless you really deviate from the defaults, your IDE hard disks will "just work", as will your PS/2 or USB keyboard and mouse. You'll get basic VGA display support. However, some devices such as ethernet adapters are barely standardised at all, so you'll have to identify the ethernet chipset and select the appropriate hardware support for your specific card to get any network access at all.

In addition, while some things just-about-work with the default settings, you may need to select more specialised options to get the full potential from your system. For example, if you do not enable the support for the appropriate IDE chipset, your IDE hard disks will run very slowly.

Kernel features
As well as hardware support, you also need to think in terms of the software features you require in your kernel. One important example of such a feature is filesystem support: you need to select support for the filesystems in use on your hard disk, as well as any filesystems you might be using on external storage (e.g. VFAT on USB flash disks).

Another common example is advanced network functionality. If you want to do some kind of routing or firewalling, you need to ensure the relevant configuration items are included in your kernel config.

Ready?
Now that we've introduced the concepts, you should be able to start identifying your hardware and browsing through the configuration menus, selecting the required kernel options for your system.

The rest of this page aims to clear up common areas of confusion, and provide advice for how to avoid common problems which users often run into. Good luck!

SATA disks are SCSI
Most modern desktop systems ship with storage devices (hard disk and CD/DVD drives) on a Serial ATA bus, rather than the older IDE (ribbon cable) bus type.

SATA support in Linux is implemented in a layer referred to as libata, which sits below the SCSI subsystem. For this reason, SATA drivers are found in the SCSI driver section of the configuration. Additionally, your storage devices will be treated as SCSI devices, which means SCSI disk/cdrom support is required too. Your SATA hard disk will be named as (e.g.) and your SATA CD/DVD drive will be named as (e.g.).

Although the majority of these drivers are for SATA controllers, libata was not designed to be SATA-specific. All common IDE drivers will also be ported to libata in the near future, and at this point, the above considerations will also apply for IDE users.

Configuration options for libata

IDE chipsets and DMA
Despite the introduction of SATA, IDE devices are still very common and depended upon by many. IDE is a fairly generic technology, and as such, Linux supports almost all IDE controllers out-of-the-box without any controller-specific options selected.

However, IDE is an old technology, and in it's original Programmed Input/Output incarnation, it is unable to provide the transfer rates required for speedy access to modern storage devices. The generic IDE driver is limited to these PIO transfer modes, which result in slow data transfer rates, and significantly high CPU usage while data is being transferred to/from disk.

Unless you're dealing with a pre-1995 system, your IDE controller will also support an alternative transfer mode, known as Direct Memory Access (DMA). DMA is much much faster, and CPU utilisation is barely affected while data transfers are taking place. If you are suffering from really poor general system performance and you are using an IDE disk, chances are that DMA is not being used.

If you're not using libata for your IDE disks, then you'll need to check for DMA usage and enable it.

To enable DMA on your IDE devices, you simply need to enable the configuration option for your IDE controller.

USB Host Controllers
USB is a widely adopted bus for connecting external peripherals to your computer. One of the reasons behind the success of USB is that it is a standardised protocol, however the USB host controller devices (HCDs) implemented on the host computer do vary a little. There are 3 main types:


 * is the Universal Host Controller Interface. It supports USB 1.1, and is usually found on motherboards based on a VIA or Intel chipset.
 * is the Open Host Controller Interface. It supports USB 1.1 and is usually found on motherboards based on an Nvidia or SiS chipset.
 * is the Extended Host Controller Interface. It is the only common host controller to support USB 2.0, and can typically be found on any computer that supports USB 2.0.

Most systems will come with two of the above interface types: EHCI (USB 2.0), plus either UHCI or OHCI (USB 1.1). It is important that you select both types present on your system. While all USB 2.0 devices are backwards compatible with USB 1.1, a large proportion of USB devices (even the ones being manufactured today) are based on the USB 1.1 interface - why would a USB mouse need more than 1.5mbit/sec?

If you do not select the relevant options corresponding to the USB HCD types present on your system, you may experience 'dead' USB ports: you plug a device in, but it does not get power or respond in any way.

A neat  trick (from the  package) makes it relatively easy to detect which HCDs are present in your system. Ignoring the FireWire controller which was also matched, it is easy to spot that my system requires OHCI and EHCI support:

Multiprocessor, Hyper-Threading and Multi-Core systems
Many computer systems are based on multiple processors, but not always in immediately obvious ways.


 * Many of Intel's CPUs support a technology which they call hyper-threading, which is where the CPU is actually viewed by the system as two logical processors.
 * Most Intel/AMD CPUs actually consist of multiple physical processors inside a single package, these are known as multi-core processors.
 * Some high-end computer systems actually have multiple physical processors installed on specialised motherboards to provide a significant performance increase over a uniprocessor system. You'll probably know if you have such a system, since they aren't cheap.

In all of these cases, you need to select the appropriate kernel options to obtain optimum performance from these setups.

x86 High Memory support
Due to limitations in the 32-bit address space of the x86 architecture, a kernel with default configuration can only support up to 896mb RAM. If your system has more memory, only the first 896mb will be visible, unless you enable high memory support.

High memory support is not enabled by default, because it introduces a small system overhead. Do not be distracted by this, the overhead is insignificant when compared to the performance increase of having more memory available!

Introduction
When you read about kernel configurations, you will often see that settings are described as. This short-hand notation is what the kernel configuration actually uses internally, and is what you will find in the kernel configuration file (be it or in the auto-generated  file). Of course, using short-hand notation wouldn't do much good if you cannot translate this to the real location in the kernel configuration. Luckily, the  tool allows you to do just that.

Translating CONFIG_FOO to the real configuration location
Suppose you need to enable, launch the kernel configuration menu  and type in. This will open the search box. In this search box, type  (you can even drop the  ). The next code listing shows the result of this search.

This output yields lots of interesting information.

With this information, you should be able to translate any  requirements tossed at you easily. In short, it means you


 * 1) need to enable the settings described in the Depends on field
 * 2) navigate where Location: points you towards
 * 3) toggle the value referred to by Prompt:

Other kernel configuration documentation
So far, we have only discussed general concepts and specific problems related to kernel configuration, without going into any precise details (such details are for you to discover!). However, other parts of the Gentoo documentation collection provide specialised details for the topics at hand.

You may find these documents helpful while configuring those specific areas, but if you are new to kernel configuration, don't be too adventurous. Start by getting a basic system up and running, you can always come back later to add support for your audio, printing, etc.


 * The ALSA article details the configuration options required for sound card support. Note that ALSA is one exception to the suggested scheme of not building things as modules: ALSA is actually much easier to configure when the components are modular.


 * The Bluetooth article details the options you need in order to use bluetooth devices on your system.


 * The IPv6 router guide describes how to configure your kernel for routing using the next generation network addressing scheme.


 * If you will be using the closed-source nVidia graphics drivers for improved 3D graphics performance, the nVidia Guide lists the options that should and should not be selected on such a system.


 * Amongst other things, the Power Management Guide explains how to configure your kernel for CPU frequency scaling, and for suspend and hibernate functionality.


 * If you are running a PowerPC system, the PPC FAQ has a few sections about kernel configuration.


 * The Printing HOWTO lists the kernel options needed to support printing in Linux.


 * The USB Guide details the configuration required to use common USB devices such as keyboards/mice, storage devices, and printers.

Configuration changes do not take effect
It is very common for users to make a configuration change, but then make a small mistake in the process following on from that point. They reboot into a kernel image that is not the one they just reconfigured, observe that whatever problem they were trying to solve is still present, and conclude that the configuration change does not solve the problem.

The process of compiling and installing kernels is outside the scope of this document, you should refer to the Kernel Upgrade Guide for general guidance. In short, the process is: configure, compile, mount (if not already mounted), copy new kernel image over, reboot. If you miss out any of those final stages, your changes will not take effect!

It is possible to verify if the kernel you are booted from matches the kernel compiled on your hard disk by examining the date and time of compilation. Assuming your architecture is x86 and your kernel sources are installed at :

The above command displays the date and time that the kernel you are currently booted from was compiled.

The above command displays the date and time that the kernel image on your hard disk was last compiled.

If the two times from the above commands differ by more than 2 minutes, it indicates that you have made a mistake during kernel reinstallation and you are not booted from the kernel image that you thought you were!

Modules do not get loaded automatically
As mentioned earlier in this document, the kernel configuration system hides a large behavioural change when selecting a kernel component as a module (M) rather than built-in (Y). It is worth repeating this again because so many users fall into this trap.

When you select a component as built-in, the code is built into the kernel image (bzImage). When the kernel needs to use that component, it can initialise and load it automatically, without any user intervention.

When you select a component as a module, the code is built into a kernel module file and installed on your filesystem. In general, when the kernel needs to use that component, it can't! With some exceptions, the kernel makes no effort to actually load these modules - this task is left up to the user.

So, if you build support for your network card as a module, and you then find that you cannot access your network, it is probably because the module is not loaded - you must either do this manually or configure your system to autoload it at boot time.

Unless you have reasons to do otherwise, save yourself some time by building these components directly into the kernel image, so that the kernel can automatically set these things up for you.

Acknowledgements
We would like to thank the following authors and editors for their contributions to this guide:


 * Daniel Drake
 * Curtis Napier
 * Justin Robinson
 * Åukasz Damentko
 * Jonathan Smith
 * nightmorph