Linux kernel processor family

Kernel/Traditional compilation

This article is an introduction to building custom kernels from kernel.org sources. This method of compiling kernels is the traditional method common to all distributions. It can be, depending on your background, more complicated than using the Kernels/Arch Build System. Consider the Arch Build System tools are developed and maintained to make repeatable compilation tasks efficient and safe.

Contents

Preparation

It is not necessary (or recommended) to use the root account or root privileges (i.e. via Sudo) for kernel preparation.

Install the core packages

Install the base-devel package group, which contains necessary packages such as make and gcc . It is also recommended to install the following packages, as listed in the default Arch kernel PKGBUILD: xmlto , kmod , inetutils , bc , libelf , git , cpio , perl , tar , xz .

Create a kernel compilation directory

It is recommended to create a separate build directory for your kernel(s). In this example, the directory kernelbuild will be created in the home directory:

Download the kernel source

Download the kernel source from https://www.kernel.org. This should be the tarball ( tar.xz ) file for your chosen kernel.

It can be downloaded by simply right-clicking the tar.xz link in your browser and selecting Save Link As. , or any other number of ways via alternative graphical or command-line tools that utilise HTTP, TFTP, Rsync, or Git.

In the following command-line example, wget has been installed and is used inside the

/kernelbuild directory to obtain kernel 4.8.6:

You should also verify the correctness of the download before trusting it. First grab the signature, then use that to grab the fingerprint of the signing key, then use the fingerprint to obtain the actual signing key:

Note the signature was generated for the tar archive (i.e. extension .tar ), not the compressed .tar.xz file that you have downloaded. You need to decompress the latter without untarring it. Verify that you have xz installed, then you can proceed like so:

Do not proceed if this does not result in output that includes the string «Good signature».

If wget was not used inside the build directory, it will be necessary to move the tarball into it, e.g.

Unpack the kernel source

Within the build directory, unpack the kernel tarball:

To finalise the preparation, ensure that the kernel tree is absolutely clean; do not rely on the source tree being clean after unpacking. To do so, first change into the new kernel source directory created, and then run the make mrproper command:

Kernel configuration

This is the most crucial step in customizing the default kernel to reflect your computer’s precise specifications. Kernel configuration is set in its .config file, which includes the use of Kernel modules. By setting the options in .config properly, your kernel and computer will function most efficiently.

You can do a mixture of two things:

  • Use the default Arch settings from an official kernel (recommended)
  • Manually configure the kernel options (optional, advanced and not recommended)

Default Arch configuration

This method will create a .config file for the custom kernel using the default Arch kernel settings. If a stock Arch kernel is running, you can use the following command inside the custom kernel source directory:

Otherwise, the default configuration can be found online in the official Arch Linux kernel package.

Advanced configuration

There are several tools available to fine-tune the kernel configuration, which provide an alternative to otherwise spending hours manually configuring each and every one of the options available during compilation.

Those tools are:

  • make menuconfig : Command-line ncurses interface superseded by nconfig
  • make nconfig : Newer ncurses interface for the command-line
  • make xconfig : User-friendly graphical interface that requires packagekit-qt5 to be installed as a dependency. This is the recommended method — especially for less experienced users — as it is easier to navigate, and information about each option is also displayed.
  • make gconfig : Graphical configuration similar to xconfig but using gtk. This requires gtk2 , glib2 and libgladeAUR .

The chosen method should be run inside the kernel source directory, and all will either create a new .config file, or overwrite an existing one where present. All optional configurations will be automatically enabled, although any newer configuration options (i.e. with an older kernel .config ) may not be automatically selected.

Читайте также:  При переустановке windows использовал

Once the changes have been made save the .config file. It is a good idea to make a backup copy outside the source directory. You may need to do this multiple times before you get all the options right.

If unsure, only change a few options between compilations. If you cannot boot your newly built kernel, see the list of necessary config items here.

Running lspci -k # from liveCD lists names of kernel modules in use. Most importantly, you must maintain cgroups support. This is necessary for systemd. For more detailed information, see Gentoo:Kernel/Gentoo Kernel Configuration Guide and Gentoo:Intel#Kernel or Gentoo:Ryzen#Kernel for Intel or AMD Ryzen processors.

Compilation

Compilation time will vary from as little as fifteen minutes to over an hour, depending on your kernel configuration and processor capability. Once the .config file has been set for the custom kernel, within the source directory run the following command to compile:

Installation

Install the modules

Once the kernel has been compiled, the modules for it must follow. First build the modules:

Then install the modules. As root or with root privileges, run the following command to do so:

This will copy the compiled modules into /lib/modules/ — . For example, for kernel version 4.8 installed above, they would be copied to /lib/modules/4.8.6-ARCH . This keeps the modules for individual kernels used separated.

Copy the kernel to /boot directory

The kernel compilation process will generate a compressed bzImage (big zImage) of that kernel, which must be copied to the /boot directory and renamed in the process. Provided the name is prefixed with vmlinuz- , you may name the kernel as you wish. In the examples below, the installed and compiled 4.8 kernel has been copied over and renamed to vmlinuz-linux48 :

Make initial RAM disk

If you do not know what making an initial RAM disk is, see Initramfs on Wikipedia and mkinitcpio.

Automated preset method

An existing mkinitcpio preset can be copied and modified so that the custom kernel initramfs images can be generated in the same way as for an official kernel. This is useful where intending to recompile the kernel (e.g. where updated). In the example below, the preset file for the stock Arch kernel will be copied and modified for kernel 4.8, installed above.

First, copy the existing preset file, renaming it to match the name of the custom kernel specified as a suffix to /boot/vmlinuz- when copying the bzImage (in this case, linux48 ):

Second, edit the file and amend for the custom kernel. Note (again) that the ALL_kver= parameter also matches the name of the custom kernel specified when copying the bzImage :

Finally, generate the initramfs images for the custom kernel in the same way as for an official kernel:

Manual method

Rather than use a preset file, mkinitcpio can also be used to generate an initramfs file manually. The syntax of the command is:

  • -k ( —kernel ): Specifies the modules to use when generating the initramfs image. The name will be the same as the name of the custom kernel source directory (and the modules directory for it, located in /usr/lib/modules/ ).
  • -g ( —generate ): Specifies the name of the initramfs file to generate in the /boot directory. Again, using the naming convention mentioned above is recommended.

For example, the command for the 4.8 custom kernel installed above would be:

Copy System.map

The System.map file is not required for booting Linux. It is a type of «phone directory» list of functions in a particular build of a kernel. The System.map contains a list of kernel symbols (i.e function names, variable names etc) and their corresponding addresses. This «symbol-name to address mapping» is used by:

  • Some processes like klogd, ksymoops, etc.
  • By OOPS handler when information has to be dumped to the screen during a kernel crash (i.e info like in which function it has crashed).

If your /boot is on a filesystem which supports symlinks (i.e., not FAT32), copy System.map to /boot , appending your kernel’s name to the destination file. Then create a symlink from /boot/System.map to point to /boot/System.map- :

After completing all steps above, you should have the following 3 files and 1 soft symlink in your /boot directory along with any other previously existing files:

  • Kernel: vmlinuz-
  • Initramfs: Initramfs- .img
  • System Map: System.map-
  • System Map kernel symlink

Bootloader configuration

Add an entry for your new kernel in your bootloader’s configuration file. See Arch boot process#Feature comparison for possible boot loaders, their wiki articles and other information.

Читайте также:  Свернуть все окна горячие клавиши mac os

Источник

Настройка ядра Linux

Contents

Установка исходного кода

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

Для систем, основанных на amd64 архитектуре, рекомендуется пакет sys-kernel/gentoo-sources.

Выберем подходящий исходный код ядра и установим его с помощью emerge :

Данная команда установит исходный код ядра Linux в /usr/src/ , в котором символьная ссылка linux будет указывать на установленную версию:

Теперь следует сконфигурировать и собрать ядро. Существует два основных подхода:

  1. Ядро конфигурируется и собирается вручную.
  2. Ядро автоматически собирается и устанавливается с помощью genkernel .

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

По умолчанию: Ручное конфигурирование

Введение

Согласно расхожему мнению, настройка ядра — наиболее сложная процедура, с которой может столкнуться пользователь Linux. Это далеко не так — после нескольких сборок ядра, не всякий вспомнит, что это было сложно ;).

Однако одна вещь является истиной: при ручной конфигурации ядра очень важно понимать свою систему. Большую часть сведений можно почерпнуть, установив пакет sys-apps/pciutils, который содержит в команду lspci :

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

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

В конфигурации ядра Linux есть много-много разделов. Сначала пройдёмся по пунктам, которые должны быть обязательно включены (иначе Gentoo будет работать неправильно или же вовсе не запустится). Также в вики есть Руководство по настройке ядра Gentoo, которое поможет понять более тонкие детали.

Включение обязательных параметров

If you are using sys-kernel/gentoo-sources, we strongly recommend you enable the Gentoo-specific configuration options. These ensure that a minimum of kernel features required for proper functioning is available:

Naturally your choice in the last two lines depends on your choice of init system (OpenRC vs. Systemd).

If you are using sys-kernel/vanilla-sources, you will have to find the required options on your own.

Убедитесь, что все драйверы, необходимые для загрузки системы (например, контроллер SCSI) собраны прямо в ядре, а не в виде модуля. В противном случае, система может не загрузиться.

Далее следует выбрать тип процессора. Также рекомендуется включить возможности MCE (если они доступны), чтобы пользователи системы могли получать оповещение о любых проблемах с оборудованием. На некоторых архитектурах (например, x86_64) подобные ошибки выводятся не в dmesg , а в /dev/mcelog . А для него понадобится пакет app-admin/mcelog.

Также включите Maintain a devtmpfs file system to mount at /dev, чтобы критически важные файлы устройств были доступны на самом раннем этапе загрузки ( CONFIG_DEVTMPFS и CONFIG_DEVTMPFS_MOUNT ):

Убедитесь, что поддержка SCSI-дисков включена ( CONFIG_BLK_DEV_SD ):

Теперь перейдите в раздел File Systems и выберите те файловые системы, которые планируете использовать. Файловая система, используемая в качестве корневой должна быть включена в ядро, иначе Gentoo не сможет примонтировать данный раздел. Также включите Virtual memory и /proc file system. По необходимости выберете один или несколько элементов из списка ( CONFIG_EXT2_FS , CONFIG_EXT3_FS , CONFIG_EXT4_FS , CONFIG_MSDOS_FS , CONFIG_VFAT_FS , CONFIG_PROC_FS и CONFIG_TMPFS ):

Если для подключения к Интернету используется PPPoE или модемное соединение, то включите следующие параметры ( CONFIG_PPP , CONFIG_PPP_ASYNC и CONFIG_PPP_SYNC_TTY ):

Два параметра сжатия не повредят, но и не являются обязательными, как и PPP over Ethernet. Фактически, последний используется в случае, если ppp сконфигурирован на использование ядерный PPPoE режим.

Не забудьте настроить поддержку сетевых карт (Ethernet или беспроводных).

Поскольку большинство современных систем являются многоядерными, важно включить Symmetric multi-processing support ( CONFIG_SMP ):

Если используются USB-устройства ввода (например клавиатура и мышь) или другие устройства, то не забудьте включить и эти параметры ( CONFIG_HID_GENERIC , CONFIG_USB_HID , CONFIG_USB_SUPPORT , CONFIG_USB_XHCI_HCD , CONFIG_USB_EHCI_HCD , CONFIG_USB_OHCI_HCD ):

Настройка ядра, специфичная для архитектуры

Если необходимо поддерживать 32-битные программы, убедитесь, что выбран пункт IA32 Emulation ( CONFIG_IA32_EMULATION ). Gentoo устанавливает систему multilib (смешанные 32/64 битные вычисления) по умолчанию, поэтому данная опция необходима, если конечно не выбран профиль no-multilib.

Включите поддержку меток GPT, если использовали их ранее при разбиении диска ( CONFIG_PARTITION_ADVANCED и CONFIG_EFI_PARTITION ):

Включите поддержку EFI stub и EFI variables в ядре Linux, если для загрузки системы используется UEFI ( CONFIG_EFI , CONFIG_EFI_STUB , CONFIG_EFI_MIXED и CONFIG_EFI_VARS ):

Компиляция и установка

Когда настройка закончена, настало время скомпилировать и установить ядро. Выйдите из настройки и запустите процесс компиляции:

По завершении компиляции, скопируйте образ ядра в каталог /boot/ . Это делается командой make install :

Данная команда скопирует образ ядра в каталог /boot/ вместе с файлом System.map и файлом настройки ядра.

Необязательно: Сборка initramfs

В некоторых случаях необходимо собрать initramfs — файловую систему инициализации, размещаемую в оперативной памяти. Одна из необходимых причин для этого — когда важные части системных путей (например, /usr/ или /var/ ) находятся на отдельных разделах. Эти разделы могут быть смонтированы средствами, расположенными внутри initramfs.

Читайте также:  Синие полосы при загрузке windows

Без initramfs есть большой риск того, что система не загрузится правильно, так как программы или информация о разделах, необходимые для монтирования таких разделов, находятся непосредственно в этих разделах. initramfs вытянет все необходимые файлы в архив, который будет загружен в память сразу же после загрузки ядра, но до того, как управление будет передано системе инициализации. Сценарии initramfs выполнят все необходимые операции для правильного монтирования разделов до того, как продолжится загрузка системы.

Для установки initramfs, сперва нужен sys-kernel/genkernel, который его создаст:

Если необходима особая поддержка в initramfs, например LVM или RAID, то следует указать это через соответствующий параметр genkernel . Для более подробной информации см. genkernel —help . В следующем примере включена поддержка LVM и программного RAID ( mdadm ):

initramfs будет сохранён в /boot/ под названием, начинающимся с «initramfs»:

Теперь продолжите с раздела Модули ядра.

Альтернатива: Использование genkernel

Если ручная установка кажется слишком сложной, то можно воспользоваться утилитой genkernel , которая сконфигурирует и соберёт ядро автоматически.

genkernel конфигурирует ядро примерно так же, как это делается для установочного носителя. Это значит, что ядро, собранное genkernel , постарается определить всё оборудование в процессе загрузки. Поскольку genkernel не требует ручной конфигурации ядра, он идеально подходит для тех пользователей, кто не готов собирать собственное ядро.

Приступим. Сперва нужно установить sys-kernel/genkernel:

Далее отредактируйте файл /etc/fstab , где следует указать в строке /boot/ правильное устройство во втором поле. Если вы следовали примеру разбиения разделов из данного Руководста, то, скорее всего, это будет устройство /dev/sda1 с файловой системой ext2. Тогда строка должна выглядеть следующим образом:

Осталось скомпилировать ядро, выполнив genkernel all . Учтите, что поскольку genkernel включает поддержку как можно большего диапазона оборудования, процесс сборки может занять некоторое время!

По завершению работы genkernel будут сформированы ядро, полный набор модулей и файловая система инициализации (initramfs). Ядро и initrd нам понадобятся позднее. Запишите название файлов ядра и initrd, так как они нам понадобятся при настройке загрузчика. Initrd запускается сразу после ядра для определения оборудования (как при загрузке установочного CD), перед запуском самой системы.

Alternative: Using distribution kernels

Distribution Kernels are ebuilds that cover the complete process of unpacking, configuring, compiling, and installing the kernel. The primary advantage of this method is that the kernels are upgraded to new versions as part of @world upgrade without a need for manual action. Distribution kernels default to a configuration supporting the majority of hardware but they can be customized via /etc/portage/savedconfig .

There are other methods available to customize the kernel config such as config snippets.

Installing correct installkernel

Before using the distribution kernels, please verify that the correct installkernel package for the system is installed. When using systemd-boot (formerly gummiboot), install:

When using a traditional /boot layout (e.g. GRUB, LILO, etc.), the gentoo variant should be installed by default. If in doubt:

Installing a distribution kernel

To build a kernel with Gentoo patches from source, type:

System administrators who want to avoid compiling the kernel sources locally can instead use precompiled kernel images:

Upgrading and cleaning up

Once the kernel is installed, the package manager will automatically upgrade it to newer versions. The previous versions will be kept until the package manager is requested to clean up stale packages. Please remember to periodically run:

to save space. Alternatively, to specifically clean up old kernel versions:

Post-install/upgrade tasks

Distribution kernels are now capable of rebuilding kernel modules installed by other packages. linux-mod.eclass provides USE=dist-kernel which controls a subslot dependency on virtual/dist-kernel.

Enabling this on packages like sys-fs/zfs and sys-fs/zfs-kmod allows them to automatically be rebuilt against the new kernel and re-generate the initramfs if applicable accordingly!

Manually rebuilding the initramfs

If required, manually trigger such rebuilds by, after a kernel upgrade, executing:

If any of these modules (e.g. ZFS) are needed at early boot, rebuild the initramfs afterward:

Модули ядра

Конфигурация модулей

Укажите модули, которые должны загружаться автоматически в файлах /etc/modules-load.d/*.conf , по одному модулю в строке. Дополнительные параметры для модулей при необходимости можно указывать в файлах /etc/modprobe.d/*.conf .

Чтобы посмотреть доступные модули, выполните команду find , не забыв заменить « » на собранную в предыдущем шаге версию:

Например, чтобы автоматически загрузить модуль 3c59x.ko (драйвер для определённого семейства сетевых карт от 3Com), отредактируйте файл /etc/modules-load.d/network.conf , добавив туда имя модуля. Фактическое имя файла несущественно для загрузчика.

Продолжите установку с раздела Настройка системы.

Необязательно: Установка файлов прошивки

Для корректной работы некоторых драйверов требуется установка дополнительных файлов прошивки. Часто подобное требуется для сетевых интерфейсов, особенно беспроводных. Также, современные видеочипы от AMD, NVidia и Intel, при использовании отрытых драйверов, часто нуждаются во внешних файлах firmware. Большинство файлов прошивки поставляется в пакете sys-kernel/linux-firmware:

Источник

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