Genkernel/ru

is a tool created by Gentoo used to automate the build process of the kernel and initramfs. Some of the general features include:


 * Configuring the kernel sources.
 * Building the compressed kernel and copying it to.
 * Creating an initramfs and copying it to.
 * Creating symlinks in.
 * Adding custom content to the initramfs such as encryption related files, boot splash images, extra modules, and more.
 * Compressing the initramfs.
 * Configuring the bootloader to boot the newly created kernel and initramfs.

Emerge
Initiate the installation of genkernel:

Usage
Основная форма вызова команды genkernel выглядит следующим образом:

Параметры
The actual behavior of genkernel depends on a large variety of options, the majority of which can be set/unset in the file or passed via the  command on each invocation. Options passed over the command line take precedence over options defined in. The configuration file is very well documented, however some of the most commonly used options will be explored in this article. The goal is for the reader to be familiar with common genkernel invocations. For a more complete set of explanations refer to the comments in itself or to the output of.

Options acting on user interactivity
The configuration options listed below help the user decide how to interact with the configuration process. Users can even choose whether or not the configuration file created in the process should be saved. The following are considered primary configuration options:

Options acting on the resulting system
The configuration options listed here defines which features will or will not be enabled in the resulting kernel and initrd.

Options acting on the choice of the tools used for building
The following options are supported by genkernel, and are passed to the relevant applications while the kernel is being assembled. These options affect the compiling tools used for the kernel compilation process, albeit at a much lower level.

Options acting on the compilation process
The following options usually take effect during the actual compilation:

Debugging options
The use of debugging options during the kernel compilation process controls the amount of information reported, as well as the presentation of said data.

Actions
The action passed on the command line with the tells genkernel what action to perform. The following actions are supported:

Starting off
Although there are several ways to run genkernel, the least-intrusive approach recommended for most users is provided by. Here, a generic configuration which works well for most systems is used. As was mentioned earlier, this approach is not without drawbacks; most of the modules created are useless to the average user and may increase compile time. Below is an illustration of a more efficient approach, achieved by passing certain options to genkernel as root:

The above operation causes genkernel to create a framebuffer splash-enabled kernel that will have to be manually installed. While preparing the kernel source tree, genkernel will refrain from cleaning out any preexisting object files present in the source tree. A menu-driven kernel configuration utility will be displayed that allows the user to select which modules will be built for the system.

Replacing  with the   option allows genkernel to automatically install the new kernel in the  directory, and will create symlinks if   is specified. Using the  option allows genkernel to mount the  partition automatically, if necessary.

Changing the kernel
The first thing that should be done is to allow the triggering of in the  file:

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

Source files
After an, whenever new sources are available, a new kernel source directory is created under to host them. Normally, the active kernel sources directory is pointed to by the symlink.

Каталог может выглядеть так:

The symlink can be changed in different ways.


 * If the  USE is set the  symlink is automatically updated to point to the newly emerged sources.


 * If the  USE is not set, the user can change the destination of the symlink using the  followed by the  command.

genkernel will always (exclusively) use the sources pointed by the symlink.

Kernel configuration file
If a kernel compilation has already been run with the active kernel sources, there might be a file inside the directory that contains the kernel configuration that has been applied while creating the last bzimage of the kernel. This file is named, for example where   might be substituted with the system's architecture,   might be substituted with the version of the sources used, and   with the release of the sources.

It is this file that is used as a starting configuration when running .

If it is the first time that genkernel is run with the new kernel sources, or if the previous result has not been saved, this file is substituted with a default configuration file that resides at where x86_64 is substituted with the actual architecture.

Сохранение скомпилированной конфигурации
If the  genkernel option is activated, either from the command line or inside, the compiled kernel configuration is saved (with the name given above) into the  directory. At the same time, the configuration is saved in the file in  directory but this file is not reused on the next  run.

Installing the kernel and initramfs into the directory
Specifying the  option when invoking genkernel, will ask genkernel to install the kernel image and the initramfs into the  directory. In order to run  a convenient manner, set the following in the  file:


 * The first parameter speaks for itself.


 * Второй параметр сообщает genkernel, чтобы конфигурация скомпилированного ядра была сохранена в.


 * The last two options tell genkernel to automatically update the grub configuration. In practice, the following happens:
 * If a previous kernel image with the same name already exist, it is renamed by appending to its name. A symlink  is automatically created that points to it.
 * The new kernel takes the place of any kernel with the same name into . If it is the first time a kernel is compiled, a symlink kernel is automatically created that points to the new kernel.

After running, the directory might look like this:

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

To allow the kernel and intird provided by genkernel to run correctly, provide a minimum information in bootloader's configuration file:


 * Add  to the kernel parameters passed to the kernel image, where  points to the root partition (  is the number of the partition if a partition exists).
 * If splash is used, add a suitable mode line such as  to the parameters passed to the kernel and also add   or   depending on the verboseness required through the boot process.
 * Add the initrd information as required by the bootloader. Consult the Bootloader Configuration Chapter of the Gentoo Handbook for details on how to make the bootloader initrd-aware.

Ниже приведено то, как может выглядеть файл.

Preserving the working files
Приложение genrkernel автоматически сохраняет новые изменения в файлах. Если требуется сохранить предыдущие изменения, то должны быть предприняты следующие меры.


 * The first file to preserve is the kernel configuration file in If the source has not changed prior to the recompilation of the kernel, the previously used name for this file will be used. So copying the previous configuration file under a different name helps in preserving the information while keeping the file available as a starting point for a new configuration.


 * The second important thing is to preserve the already bootable kernel and initramfs images. The way to accomplish this depends on the context:
 * If the last kernel compiled is bootable, running will rename this kernel (and similarly initramfs) image to  and create a new . This mean that even if the new kernel is not bootable, users will always be able to boot the old one.
 * If the last kernel compiled is not bootable and sources haven't changed since the user compiled a bootable one, prior to running, first delete the new kernel image and remove the suffix from the last bootable one. Without this, if the newly compiled kernel is not bootable for the second time, the bootable  will be kicked out by the renaming of the non bootable , giving the user an unbootable system. Use the same reasoning for initramfs.

Using previous kernel configuration while changing the sources
The previous configuration can be used through the MENUCONFIG variable in as follows:

From an installation CD
The utility can build kernel and initrd images that provide support for network booting, or netbooting. With any luck, users should be able to netboot any recent computer into the environment provided by the Installation CD.

Волшебство заключается в сценарии linuxrc утилиты genkernel: он попытается смонтировать загрузочный диск по сети используя NFS. Оттуда, сценарии инициализации загрузочного CD смогут получить контроль, как если бы CD присутствовал локально.

Building the kernel and initramfs with netboot support
Для разрешения поддержки загрузки по сети, включите следующие параметры при конфигурации ядра:

First, the kernel image must include the drivers for the system's Network Interface Cards (NIC). Normally, drivers for such devices will be compiled as modules. However, it is essential (for netbooting) that such drivers are compiled directly into the kernel image and not as modules.

Во-вторых, предполагается что включен параметр "IP: kernel level autoconfiguration", также как и "IP: DHCP support options". Это позволяет избежать лишних сложностей, так как IP-адрес и путь NFS к установочному CD могут быть сконфигурированы на DHCP-сервере. Определенно, это означает, что командная строка ядра будет оставаться постоянной для любой машины - что очень важно для etherbooting.

Эти параметры сообщают ядру, чтобы оно отправило DHCP-запрос при загрузке.

Additionally, enable SquashFS because most modern Gentoo Installation CDs require it. Support for SquashFS is not included with the generic kernel source tree. To enable SquashFS, apply the necessary patches to the generic kernel source or install gentoo-sources.

Как только процесс компиляции завершен, создайте сжатый архив tar (tarball - tar.gz), который содержит модули ядра. Этот шаг требуется только если версия ядра не соответствует версии образа ядра на установочном CD.

Чтобы создать архив содержащий все модули:

В зависимости от механизма загрузки по сети, необходимо последовать одному из следующих шагов:

Для создания образа etherboot:

Для создания образа OpenBoot / SPARC64 TFTP:

Файл является образом ядра.

Finally, copy this kernel to the TFTP server. The details are architecture-dependent and are beyond the scope of this guide. Please refer to the documentation for the specific platform of interest.

NFS setup
Для настройки общего ресурса NFS, который содержит установочный CD, используйте loop-устройство, чтобы примонтировать образ ISO и затем скопировать содержимое CD в общий ресурс NFS. В качестве приятного дополнения, сценарии initrd утилиты genkernel извлекут все файлы tar.gz, расположенные в каталоге. Все, что требуется здесь сделать, это скопировать архив в каталог.

Следующее предполагает что является экспортируемым общим сетевым ресурсом NFS:

Теперь, скопируйте файл в :

DHCP setup
The netboot images will ask the DHCP server on the network for an IP as well as a  option. Both can be specified per host using a MAC address to identify machines:

Netbooting instructions
Напомним, что загрузка по сети является очень платформо-зависимой. Важной деталью является указать параметры  и   в командной строке ядра, так как это вызовет сетевой интерфейс и сообщит сценариям initrd о том, что необходимо примонтировать установочный CD через NFS. Здесь приведены несколько платформо-зависимых советов:

For etherboot, insert the etherboot disk into the drive and reboot. The kernel command line was specified when the image was constructed. With Sparc64, press + at the boot prompt and then enter:

Для PXE, настройте pxelinux (часть пакета syslinux), затем создайте подобно тому как:

Introduction
Если initramfs установлена с помощью genkernel, то присмотритесь к следующим параметрам загрузки которые могут (или должны) быть определены в конфигурации загрузчика. Наиболее общие добавлены в это руководство.

Loading LVM or software-RAID
If the system uses LVM or software-RAID, the initramfs has to be built using the  and   options. Do not forget to enable support during boot as well. This can be done using the dolvm and domdadm options.

Booting in single-user mode
Если по какой-то причине загрузка не происходит, все еще возможно восстановление системы с помощью загрузки в однопользовательском режиме. Это загрузит только действительно необходимые службы и затем перебросит пользователя в (root) оболочку восстановления.

compile failed: Kernel not found
This failure can be experienced when attempting to compile a kernel for one architecture with a kernel file that has a target of a different architecture than the target. This could be as simple as a machine running an kernel attempting to compile for a  target.

This can be experienced when booting from a x86_64 LiveCD on a system that is capable of operating in 64-bits, however the target to be installed or repaired is 32-bits. After the compilation process begins, will attempt to automatically detect the architecture for the target based on the currently running kernel. If the currently running kernel is 64-bit, then, unless it is told otherwise, will presume it should be looking for a 64-bit kernel.

Suppose then that the kernel's file has x64 disabled. The command will execute and the resulting kernel binary will be placed in the associated  directory. When goes to install (move and rename) the kernel it cannot find the kernel because it expected a 64-bit kernel.

The solution to this failure is to set 's  option to, in this case, the  architecture. The final command could look like this:

To override the architecture choice permanently, modify the ARCH_OVERRIDE variable in the file.