Ядро/Конфигурация

From Gentoo Wiki
< Kernel
Jump to:navigation Jump to:search
This page is a translated version of the page Kernel/Configuration and the translation is 57% complete.
Outdated translations are marked like this.

Эта статья описывает ручную конфигурацию и настройку ядра Linux.

An alternative to manual configuration that uses 'safe defaults' to build a generic kernel are the distribution kernels.

Установка символьной ссылки

Символьная ссылка /usr/src/linux всегда должна указывать на исходный код используемого в настоящий момент ядра. Это может быть сделано одним из трех способов:

1. Установите исходный код ядра с включенным symlink USE-флагом. Это заставит /usr/src/linux указывать на исходный код только что установленного ядра. Если необходимо, символьная ссылка может быть изменена позже двумя следующими методами:

2. Настройка символьной ссылки с помощью eselect утилиты:

root #eselect kernel list
Available kernel symlink targets:
[1] linux-3.3.8-gentoo
[2] linux-3.4.9-gentoo

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

root #eselect kernel set 2

3. Установка символьной ссылки вручную:

root #ln -sf /usr/src/linux-3.4.9-gentoo /usr/src/linux
root #ls -l /usr/src/linux
lrwxrwxrwx 1 root root 11 Aug 29 22:10 /usr/src/linux -> /usr/src/linux-3.4.9-gentoo

Конфигурация

Инструменты

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

Команда Описание
make config Text based configuration. The options are prompted one after another. All options need to be answered, and out-of-order access to former options is not possible.
make menuconfig An ncurses-based pseudo-graphical menu (only text input). Navigate through the menu to modify the desired options.
make defconfig Generates a new config with default from the ARCH supplied defconfig file. Use this option to get back the default configuration file that came with the sources.
make nconfig Pseudo-graphical menu based on ncurses. Requires sys-libs/ncurses to be installed.
make xconfig Graphical menu using Qt5. Requires dev-qt/qtwidgets to be installed.
make gconfig Graphical menu using GTK. Requires x11-libs/gtk+ , dev-libs/glib , and gnome-base/libglade to be installed.
make oldconfig Review changes between kernel versions and update to create a new .config for the kernel.
make olddefconfig Generates a new configuration with default values from the ARCH supplied defconfig file while, at the same time, maintaining all the previous options set in the .config file found at /usr/src/linux/.config. This is a fast and safe method for upgrading a config file that has all the configuration options it needs for hardware support while at the same time gaining bug fixes and security patches.
make localmodconfig Creates a config based on the current config and the currently loaded modules, as viewable via the lsmod command.
make allyesconfig Enables all configuration options in the kernel. It will set all kernel options to *. Make sure a backup of the current kernel configuration is acquired before using this option!
make allmodconfig Enables all modules in kernel. Note that this operation will consume quite a bit of disk space.

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

root #make help

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

root #cd /usr/src/linux
root #make menuconfig

Использование меню

В отображенном меню позиция курсора отмечена синей строкой. С помощью клавиш и можно изменять позицию курсора. Клавиши и проходят по меню внизу и определяют, что произойдет при нажатии клавиши Enter. В меню внизу Select выбирает подменю — пункты меню оканчивающиеся с --->, в то время как Exit выходит из подменю. В качестве альтернативы, можно выйти из подменю, диалога или всего приложения двойным нажатием клавиши Esc.

Нажатие клавиш A-Z переместит курсор к пункту меню у которого эта буква выделена жирным шрифтом. Буквы Y, M, N не используются для такой навигации; они нужны для других целей. Если пункт меню начинается с букв Y, M, или N, обычно используется следующая буква для выделения. Например для такого пункта меню "Network Device Support --->" нужно нажать клавишу E.

Могут быть следующие символы перед пунктом меню:

Символ Описание
[ ], [*] Options in square brackets can be activated or deactivated. The asterisk marks the menu entry as activated. The value can be changed with the space key. It is also possible to press Y key (Yes) to activate or N key (No) to deactivate the selected entry.


If the option is activated, the selected feature/driver will be built into the kernel and will always be available at boot time.

< >, <M>, <*> Options in angle brackets can be activated or deactivated, but also activated as module (indicated by a M). The values can be modified by pressing Y/N keys as before or by pressing the M key to activate the feature/driver as a module.


See the Kernel Modules article for differentiation.

{M}, {*} Options in curly brackets can be activated or activated as module but not be deactivated. This happens because another feature/driver is dependent on this feature.
-M-, -*- Options between hyphens are activated in the shown way by another feature/driver. There is no choice.

Кроме того, некоторые пункты меню имеют метки в конце:

Tag Description
(NEW) This driver is new in the kernel and is maybe not stable enough.
(EXPERIMENTAL) This driver is experimental and most likely not stable enough.
(DEPRECATED) This driver is deprecated and not needed for most systems.
(OBSOLETE) This driver is obsolete and should not be activated.

Большинство параметров имеют описание, которое можно посмотреть нажимая клавишу H или набрав Help в строке меню.

Выбор драйверов

Смотрите статью hardware detection, а также статьи в категории [[::Category:Hardware/ru|Hardware]].

Поиск модулей

Внутри make menuconfig можно использовать / для поиска модулей и параметров конфигурации по имени.

Как будет показано ниже, результат поиска покажет число перед совпадениями. Нажатие клавиши 1, в примере ниже, заставит make menuconfig перейти прямо к параметру Bluetooth device drivers в структуре меню.

ЯДРО Пример вывода после поиска HCIBTUSB
Symbol: BT_HCIBTUSB [=m] 
Type : tristate 
Prompt: HCI USB driver 
 Location: 
 -> Networking support (NET [=y]) 
 -> Bluetooth subsystem support (BT [=y]) 
(1) -> Bluetooth device drivers 
 Defined at drivers/bluetooth/Kconfig:5 
 Depends on: NET [=y] && BT [=y] && USB [=m]

Включение общих настроек Gentoo Linux

Существует параметр конфигурации ядра, называемый CONFIG_GENTOO_LINUX, который находится только в sys-kernel/gentoo-sources и других ядрах, поддерживаемых проектом ядра. Он ничего не делает сам по себе, но устанавливает различные необходимые параметры конфигурации, необходимые для распространённых видов установок.

Пока данная настройка автоматически выбирает поддержку tmpfs и devtmpfs, которые нужны для работы с /dev в Gentoo Linux, но в будущем эта настройка может включать и другие обязательные опции для системы на Gentoo Linux. Для более детальной информации, прочитайте информацию, которую можно получить через систему конфигурации ядра (как было описано выше в данной статье).

Kbuild

Предупреждение
Be very careful of changing environment variables as it may break the kernel in unexpected ways. DO NOT MIX GNU binutils and LLVM binutils!!! For example make CC=gcc LD=ld.lld AR=llvm-ar will not work because LLVM's ar and ld is not compatible with GCC.

The Kernel build system can be used to change how Kernel builds in a more advanced way than make *config, similar to GNU Make. Kbuild also support Environment Variables like LLVM=1. For example, the kernel will be build with LLVM and with aggressive optimization flags:

root #make LLVM=1 KCFLAGS="-O3 -march=native -pipe"
Заметка
Additional variables are explained in Clang/LLVM.

Сборка

После успешной конфигурации ядра скомпилируйте его:

root #make -j$(nproc)

-j$(nproc) tells make to use all available CPU cores to speed up compiling.

Установка

Если драйверы включены в виде модулей, необходимо их установить:

root #make modules_install

Модули будут скопированы в подкаталог /lib/modules.

Заметка
If you have enabled the dracut USE flag on sys-kernel/installkernel to automate initramfs generation during make install, it is recommended to run
root #emerge --ask @module-rebuild
before installing the kernel. This ensures that all external kernel modules (e.g., NVIDIA, ZFS) are rebuilt and included in the initramfs, preventing potential boot issues or missing functionality. Otherwise (if the flag isn't set), you can rebuild external modules later, but before regenerating the initramfs (e.g., using dracut --force). This ensures that the updated modules are included in the initramfs.

Для того, чтобы установить само ядро:

root #make install

Эта команда запускает сценарий /sbin/installkernel, который является частью пакета sys-kernel/installkernel . См. installkernel для дополнительной информации о возможностях конфигурации данного сценария.

Загрузчик

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

После завершения этапа с загрузчиком, перезагрузите систему с новым ядром.

Сравнение текущей конфигурации ядра с конфигурацией по умолчанию

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

root #cd /usr/src/linux
root #cp -p .config ../.config.working
root #make defconfig
root #mv .config ../.config.default
root #cp -p ../.config.working .config
root #cd ..
root #/usr/src/linux/scripts/diffconfig .config.working .config.default > .config.diff

Функцию поиска из make menuconfig можно использовать для поиска обозначения (symbols) и их описание. Когда вы закончите очистите:

root #cd /usr/src/
root #rm .config.working .config.default .config.diff

Theming Menuconfig

It is possible to select different color schemes for menuconfig using the variable MENUCONFIG_COLOR. To select a theme use:

root #make MENUCONFIG_COLOR=<theme> menuconfig

Available themes are as follows:

Theme Description
mono Colors suitable for monochrome displays
blackbg A color scheme with black background
classic A color scheme with blue background. The classic look
bluetitle An LCD friendly version of classic. (default)

Смотрите также

  • Genkernel — утилита созданная Gentoo, которая используется для автоматизации процесса сборки ядра и initramfs.
  • Kernel
  • Kernel/Gentoo Kernel Configuration Guide — является ознакомление с понятием ручной конфигурации ядра и разбор наиболее распространённых проблем.
  • Project:Distribution Kernel — maintains sys-kernel/*-kernel packages.

Внешние ресурсы