Manual:X86/Instalação/Kernel

From Gentoo Wiki
Jump to:navigation Jump to:search
This page is a translated version of the page Handbook:X86/Installation/Kernel and the translation is 100% complete.
X86 Manual
Installation
Sobre a instalação
Escolhendo a mídia
Configurando a rede
Preparando os discos
Instalando o stage3
Instalando o sistema base
Configurando o kernel
Configurando o sistema
Instalando as ferramentas
Configurando o gerenciador de boot
Finalizando
Trabalhando com o Gentoo
Introdução ao Portage
USE flags
Recursos do Portage
Sistema initscript
Variáveis de ambiente
Trabalhando com o portage
Arquivos e diretórios
Variáveis
Misturando ramos de software
Ferramentas adicionais
Árvore customizada do Portage
Recursos avançados
Configuração de rede
Iniciando
Configuração avançada
Uso de rede modular
Rede sem fio
Adicionando funcionalidade
Gerenciamento dinâmico

Firmware

Alguns drivers requerem que firmware adicionais sejam instalados no sistema antes para funcionarem. Isso ocorre normalmente com interfaces de rede, especialmente as interfaces de rede sem fio. Também placas de vídeo modernas de fabricantes como AMD, NVidia e Intel, quando usando drivers open source, frequentemente precisam de arquivos de firmware externos. A maioria dos firmwares estão empacotados em sys-kernel/linux-firmware:

It is recommended to have the sys-kernel/linux-firmware package installed before the initial system reboot in order to have the firmware available in the event that it is necessary:

root #emerge --ask sys-kernel/linux-firmware
Nota
Installing certain firmware packages often requires accepting the associated firmware licenses. If necessary, visit the license handling section of the Handbook for help on accepting licenses.

It is important to note that kernel symbols that are built as modules (M) will load their associated firmware files from the filesystem when they are loaded by the kernel. It is not necessary to include the device's firmware files into the kernel's binary image for symbols loaded as modules.

Microcode

In addition to discrete graphics hardware and network interfaces, CPUs also can require firmware updates. Typically this kind of firmware is referred to as microcode. Newer revisions of microcode are sometimes necessary to patch instability, security concerns, or other miscellaneous bugs in CPU hardware.

Microcode updates for AMD CPUs are distributed within the aforementioned sys-kernel/linux-firmware package. Microcode for Intel CPUs can be found within the sys-firmware/intel-microcode package, which will need to be installed separately. See the Microcode article for more information on how to apply microcode updates.

Kernel configuration and compilation

É chegada a hora de configurar e compilar os fontes do kernel. Há duas formas de se fazer isso:

Ranked from least involved to most involved:

  1. O kernel é manualmente configurado e compilado, ou
  2. é usada uma ferramenta chamada genkernel para automaticamente compilar e instalar o kernel Linux

O núcleo em torno do qual todas as distribuições são criadas é o kernel Linux. Ele é a camada entre os programas de usuários e o hardware do sistema. O Gentoo provê aos seus usuários diversos possíveis fontes do kernel. Uma listagem completa está disponível na Página de visão geral do kernel.

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 updated to new versions by the package manager as part of @world upgrade. This requires no more involvement than running an emerge command. Distribution kernels default to a configuration supporting the majority of hardware, however two mechanisms are offered for customization: savedconfig and config snippets. See the project page for more details on configuration.

Installing the correct installkernel package

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

root #emerge --ask sys-kernel/installkernel-systemd-boot

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

root #emerge --ask sys-kernel/installkernel-gentoo

If using GRUB with installkernel-gentoo, users may want to enable USE=grub for it to automatically run grub-mkconfig for new kernels with dist kernels.

Installing a distribution kernel

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

root #emerge --ask sys-kernel/gentoo-kernel

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

root #emerge --ask sys-kernel/gentoo-kernel-bin

Upgrading and cleaning up

Once the kernel is installed, the package manager will automatically update it to newer versions. The previous versions will be kept until the package manager is requested to clean up stale packages. To reclaim disk space, stale packages can be trimmed by periodically running emerge with the --depclean option:

root #emerge --depclean

Alternatively, to specifically clean up old kernel versions:

root #emerge --prune sys-kernel/gentoo-kernel sys-kernel/gentoo-kernel-bin

Post-install/upgrade tasks

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

Enabling this USE flag on packages like sys-fs/zfs and sys-fs/zfs-kmod allows them to automatically be rebuilt against a newly updated kernel and, if applicable, will re-generate the initramfs accordingly.

Manually rebuilding the initramfs

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

root #emerge --ask @module-rebuild

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

root #emerge --config sys-kernel/gentoo-kernel
root #emerge --config sys-kernel/gentoo-kernel-bin

Instalando os fontes

Nota
This section is only relevant when using the following genkernel (hybrid) or manual kernel management approach.

When installing and compiling the kernel for x86-based systems, Gentoo recommends the sys-kernel/gentoo-sources package.

Choose an appropriate kernel source and install it using emerge:

root #emerge --ask sys-kernel/gentoo-sources

Isso irá instalar os fontes do kernel Linux em /usr/src/ no qual um link simbólico chamado linux estará apontando para o fonte do kernel instalado:

It is conventional for a /usr/src/linux symlink to be maintained, such that it refers to whichever sources correspond with the currently running kernel. However, this symbolic link will not be created by default. An easy way to create the symbolic link is to utilize eselect's kernel module.

For further information regarding the purpose of the symlink, and how to manage it, please refer to Kernel/Upgrade.

First, list all installed kernels:

root #eselect kernel list
Available kernel symlink targets:
  [1]   linux-5.15.52-gentoo

In order to create a symbolic link called linux, use:

root #eselect kernel set 1
root #ls -l /usr/src/linux
lrwxrwxrwx    1 root   root    12 Oct 13 11:04 /usr/src/linux -> linux-5.15.52-gentoo

Alternativa: Usando o genkernel

Se a configuração manual parecer muito difícil, então é recomendado o uso do genkernel. Ele irá configurar e construir o kernel automaticamente.

Genkernel provides a generic kernel configuration file and will compile the kernel and initramfs, then install the resulting binaries to the appropriate locations. This results in minimal and generic hardware support for the system's first boot, and allows for additional update control and customization of the kernel's configuration in the future.

Be informed: while using genkernel to maintain the kernel provides system administrators with more update control over the system's kernel, initramfs, and other options, it will require a time and effort commitment to perform future kernel updates as new sources are released. Those looking for a hands-off approach to kernel maintenance should use a distribution kernel.

For additional clarity, it is a misconception to believe genkernel automatically generates a custom kernel configuration for the hardware on which it is run; it uses a predetermined kernel configuration that supports most generic hardware and automatically handles the make commands necessary to assemble and install the kernel, the associate modules, and the initramfs file.

Binary redistributable software license group

If the linux-firmware package has been previously installed, then skip onward to the to the installation section.

As a prerequisite, due to the firwmare USE flag being enabled by default for the sys-kernel/genkernel package, the package manager will also attempt to pull in the sys-kernel/linux-firmware package. The binary redistributable software licenses are required to be accepted before the linux-firmware will install.

This license group can be accepted system-wide for any package by adding the @BINARY-REDISTRIBUTABLE as an ACCEPT_LICENSE value in the /etc/portage/make.conf file. It can be exclusively accepted for the linux-firmware package by adding a specific inclusion via a /etc/portage/package.license/linux-firmware file.

If necessary, review the methods of accepting software licenses available in the Installing the base system chapter of the handbook, then make some changes for acceptable software licenses.

If in analysis paralysis, the following will do the trick:

root #mkdir /etc/portage/package.license
FILE /etc/portage/package.license/linux-firmwareAccept binary redistributable licenses for the linux-firmware package
sys-kernel/linux-firmware @BINARY-REDISTRIBUTABLE

Installation

Agora vamos ver como usar o genkernel. Primeiro faça emerge do pacote sys-kernel/genkernel:

root #emerge --ask sys-kernel/genkernel

Generation

Agora, compile os fontes do kernel executando genkernel all. Note que, como genkernel all compila um kernel com suporte para quase todo tipo de hardware, a compilação pode demorar para terminar!

Nota
Se a partição de boot não usa ext2 ou ext3 como sistema de arquivos, pode ser necessário configurar manualmente o kernel usando genkernel --menuconfig all e adicionar suporte para esse sistema de arquivo em particular no kernel (não como módulo). Usuários de LVM2 provavelmente irão querer adicionar --lvm como argumento também.
Nota
Users of LVM2 should add --lvm as an argument to the genkernel command below.
root #genkernel all

Quando o genkernel terminar, estarão criados um kernel, um conjunto completo de módulos e um ramdisk inicial (initrd). Usaremos o kernel e o initrd quando configurarmos o gerenciador de boot mais tarde neste documento. Anote os nomes do kernel e do initrd pois essas informações são utilizadas quando o arquivo de configuração do gerenciador de boot for editado. O initrd será executado imediatamente após o boot para fazer a autodetecção de hardware (como no CD de instalação) antes do sistema "real" inicializar.

root #ls /boot/kernel* /boot/initramfs*

Padrão: Configuração manual

Introdução

Configurar manualmente um kernel é geralmente visto como o procedimento mais difícil que um usuário Linux pode fazer. Nada mais falso -- depois de configurar algumas vezes o kernel ninguém irá se lembrar que era difícil.

Porém, uma coisa é verdade: é vital conhecer o sistema quando um kernel é configurado manualmente. A maioria das informações pode ser coletada fazendo emerge no sys-apps/pciutils que contém o comando lspci:

root #emerge --ask sys-apps/pciutils
Nota
Dentro do chroot, é seguro ignorar qualquer aviso da pcilib (como pcilib: cannot open /sys/bus/pci/devices) que o lspci possa emitir.

Uma outra fonte de informação do sistema é executar o lsmod para ver quais módulos do kernel o CD de instalação usa pois isso pode dar dicas sobre o que habilitar.

Agora vá para o diretório dos fontes do kernel e execute make menuconfig. Isso irá mostrar uma tela de configuração baseada em menus.

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

A configuração do kernel do Linux tem muitas, muitas seções. Vamos primeiro mostrar algumas opções que devem ser ativadas (ou senão o Gentoo não irá funcionar, ou não funcionar adequadamente sem alguns ajustes). Existe também o Guia de configuração do kernel do Gentoo no wiki do Gentoo que poderá também ajudar.

Ativando as opções necessárias

When using sys-kernel/gentoo-sources, it is strongly recommend the Gentoo-specific configuration options be enabled. These ensure that a minimum of kernel features required for proper functioning is available:

KERNEL Enabling Gentoo-specific options
Gentoo Linux --->
  Generic Driver Options --->
    [*] Gentoo Linux support
    [*]   Linux dynamic and persistent device naming (userspace devfs) support
    [*]   Select options required by Portage features
        Support for init systems, system and service managers  --->
          [*] OpenRC, runit and other script based systems and managers
          [*] systemd

Naturally the choice in the last two lines depends on the selected init system (OpenRC vs. systemd). It does not hurt to have support for both init systems enabled.

When using sys-kernel/vanilla-sources, the additional selections for init systems will be unavailable. Enabling support is possible, but goes beyond the scope of the handbook.

Enabling support for typical system components

Certifique-se de que todos os drivers que forem vitais para a inicialização do sistema (tais como controladores SCSI etc) são compilados no kernel e não como módulos, ou senão o sistema não será capaz de inicializar completamente.

Em seguida selecione o tipo exato do processador. É também recomendado habilitar os recursos MCE (se disponíveis) de modo que os usuários possam ser notificados sobre quaisquer problemas de hardware. Em algumas arquiteturas (tais como a x86_64), esses erros não são impressos pelo dmesg, mas em /dev/mcelog. Isso requer o pacote app-admin/mcelog.

Selecione também Maintain a devtmpfs file system to mount at /dev assim os arquivos de dispositivos críticos estarão disponíveis logo durante o processo de inicialização (CONFIG_DEVTMPFS and CONFIG_DEVTMPFS_MOUNT):

KERNEL Habilitando suporte ao devtmpfs
Device Drivers --->
  Generic Driver Options --->
    [*] Maintain a devtmpfs filesystem to mount at /dev
    [ ]   Automount devtmpfs at /dev, after the kernel mounted the rootfs

Verifique se o suporte a discos SCSI foi ativado (CONFIG_BLK_DEV_SD):

KERNEL Habilitando suporte a discos SCSI
Device Drivers --->
   SCSI device support  --->
      <*> SCSI disk support
KERNEL Enabling basic SATA and PATA support (CONFIG_ATA_ACPI, CONFIG_SATA_PMP, CONFIG_SATA_AHCI, CONFIG_ATA_BMDMA, CONFIG_ATA_SFF, CONFIG_ATA_PIIX)
Device Drivers --->
  <*> Serial ATA and Parallel ATA drivers (libata)  --->
    [*] ATA ACPI Support
    [*] SATA Port Multiplier support
    <*> AHCI SATA support (ahci)
    [*] ATA BMDMA support
    [*] ATA SFF support (for legacy IDE and PATA)
    <*> Intel ESB, ICH, PIIX3, PIIX4 PATA/SATA support (ata_piix)

Verify basic NVMe support has been enabled:

KERNEL Enable basic NVMe support for Linux 4.4.x (CONFIG_BLK_DEV_NVME)
Device Drivers  --->
  <*> NVM Express block device
KERNEL Enable basic NVMe support for Linux 5.x.x (CONFIG_DEVTMPFS)
Device Drivers --->
  NVME Support --->
    <*> NVM Express block device

It does not hurt to enable the following additional NVMe support:

KERNEL Enabling additional NVMe support (CONFIG_NVME_MULTIPATH, CONFIG_NVME_MULTIPATH, CONFIG_NVME_HWMON, CONFIG_NVME_FC, CONFIG_NVME_TCP, CONFIG_NVME_TARGET, CONFIG_NVME_TARGET_PASSTHRU, CONFIG_NVME_TARGET_LOOP, CONFIG_NVME_TARGET_FC, CONFIG_NVME_TARGET_FCLOOP, CONFIG_NVME_TARGET_TCP
[*] NVMe multipath support
[*] NVMe hardware monitoring
<M> NVM Express over Fabrics FC host driver
<M> NVM Express over Fabrics TCP host driver
<M> NVMe Target support
  [*]   NVMe Target Passthrough support
  <M>   NVMe loopback device support
  <M>   NVMe over Fabrics FC target driver
  < >     NVMe over Fabrics FC Transport Loopback Test driver (NEW)
  <M>   NVMe over Fabrics TCP target support

Vá agora para File Systems (Sistemas de Arquivos) e selecione suporte para os sistemas de arquivos que você usa. Não compile o sistema de arquivo que é usado como sistema de arquivo raiz como módulo, ou senão o sistema Gentoo não será capaz de montar a partição. Selecione também "Virtual memory" (Memória virtual) e "/proc file system" (sistema de arquivo /proc). Selecione uma ou mais das seguintes opções segundo as necessidades do sistema: (CONFIG_EXT2_FS, CONFIG_EXT3_FS, CONFIG_EXT4_FS, CONFIG_MSDOS_FS, CONFIG_VFAT_FS, CONFIG_PROC_FS, and CONFIG_TMPFS):

KERNEL Selecionando os sistemas de arquivos necessários
File systems --->
  <*> Second extended fs support
  <*> The Extended 3 (ext3) filesystem
  <*> The Extended 4 (ext4) filesystem
  <*> Reiserfs support
  <*> JFS filesystem support
  <*> XFS filesystem support
  <*> Btrfs filesystem support
  DOS/FAT/NT Filesystems  --->
   <*> MSDOS fs support
   <*> VFAT (Windows-95) fs support

  Pseudo Filesystems --->
    [*] /proc file system support
    [*] Tmpfs virtual memory file system support (former shm fs)

Se for usado PPPoE para conectar à Internet, ou um modem com discagem foi usado, então habilite as seguintes opções (CONFIG_PPP, CONFIG_PPP_ASYNC, e CONFIG_PPP_SYNC_TTY):

KERNEL Selecionando os drivers PPPoE necessários
Device Drivers --->
  Network device support --->
    <*> PPP (point-to-point protocol) support
    <*>   PPP support for async serial ports
    <*>   PPP support for sync tty ports

As duas opções de compactação não vão atrapalhar mas definitivamente não são necessárias, assim como a opção de PPP sobre Ethernet (PPP over Ethernet), que pode apenas ser usada pelo ppp quando configurado para usar PPPoE em modo kernel.

Não se esqueça de incluir suporte no kernel para as placas de rede (ethernet ou sem fio).

A maioria dos sistemas tem múltiplos núcleos à disposição, então é importante ativar a opção "Symmetric multi-processing support" (suporte a multi-processamento simétrico) (CONFIG_SMP):

KERNEL Ativando suporte a SMP
Processor type and features  --->
  [*] Symmetric multi-processing support
Nota
Em sistemas com vários núcleos, cada núcleo conta como um processador.

Se forem usados dispositivos de entrada USB (como teclado ou mouse) ou outros dispositivos USB, não se esqueça de habilitá-los também (CONFIG_HID_GENERIC and CONFIG_USB_HID, CONFIG_USB_SUPPORT, CONFIG_USB_XHCI_HCD, CONFIG_USB_EHCI_HCD, CONFIG_USB_OHCI_HCD):

KERNEL Ativando suporte a dispositivos de entrada USB
Device Drivers --->
  HID support  --->
  -*- HID bus support
  <*>  Generic HID driver
  [*]  Battery level reporting for HID devices
     USB HID support --->
        <*> USB HID transport layer
  [*] USB support  --->
  <*>    xHCI HCD (USB 3.0) support
  <*>    EHCI HCD (USB 2.0) support
  <*>    OHCI HCD (USB 1.1) support


For x86 architectures, verify the 64-bit kernel option is unset/deactivated (CONFIG_64BIT=N), and then select the processor family as appropriate for the system's processor(s).

The processor family can be determined by reviewing output from the following two commands:

user $cat /proc/cpuinfo | grep -i vendor | uniq
user $cat /proc/cpuinfo | grep -i 'model name' | uniq
KERNEL Unset the 64-bit kernel and select processor family
[ ] 64-bit kernel
Processor type and features  --->
    Processor family (Core 2/newer Xeon)  --->
        ( ) 486
        ( ) 586/K5/5x86/6x86/6x86MX
        ( ) Pentium-Classic
        ( ) Pentium-MMX
        ( ) Pentium-Pro
        ( ) Pentium-II/Celeron(pre-Coppermine)
        ( ) Pentium-III/Celeron(Coppermine)/Pentium-III Xeon
        ( ) Pentium M
        ( ) Pentium-4/Celeron(P4-based)/Pentium-4 M/Xeon
        ( ) K6/K6-II/K6-III
        ( ) Athlon/Duron/K7
        ( ) Opteron/Athlon64/Hammer/K8
        ( ) Crusoe
        ( ) Efficeon
        ( ) Winchip-C6
        ( ) Winchip-2/Winchip-2A/Winchip-3
        ( ) AMD Elan
        ( ) GeodeGX1
        ( ) Geode GX/LX
        ( ) CyrixIII/VIA-C3
        ( ) VIA C3-2 (Nehemiah)
        ( ) VIA C7
        (*) Core 2/newer Xeon
        ( ) Intel Atom

Compiling and installing

With the configuration now done, it is time to compile and install the kernel. Exit the configuration and start the compilation process:

root #make && make modules_install
Nota
It is possible to enable parallel builds using make -jX with X being an integer number of parallel tasks that the build process is allowed to launch. This is similar to the instructions about /etc/portage/make.conf earlier, with the MAKEOPTS variable.

When the kernel has finished compiling, copy the kernel image to /boot/. This is handled by the make install command:

root #make install

This will copy the kernel image into /boot/ together with the System.map file and the kernel configuration file.


Opcional: Criando um initramfs

Em certos casos, é necessário construir um initramfs - um sistema inicial de arquivos em RAM. A razão mais comum é quando os locais importantes do sistema de arquivos (como /usr/ ou /var/) estão em partições separadas. Com um initramfs, essas partições podem ser montadas usando as ferramentas disponíveis dentro do initramfs.

Sem um initramfs, há um enorme risco de o sistema não inicializar correctamente porque as ferramentas que são responsáveis pela montagem dos sistemas de arquivos precisam de informação que reside nesses sistemas de arquivos. Um initramfs irá puxar os arquivos necessários em um arquivo que é usado logo após o kernel inicializa, mas antes que o controle é entregue para a ferramenta de init. Os scripts do initramfs, então, certificam-se de que as partições estejam devidamente montadas antes do sistema continuar a inicialização.

Importante
If using genkernel, it should be used for both building the kernel and the initramfs. When using genkernel only for generating an initramfs, it is crucial to pass --kernel-config=/path/to/kernel.config to genkernel or the generated initramfs may not work with a manually built kernel. Note that manually built kernels go beyond the scope of support for the handbook. See the kernel configuration article for more information.

Para instalar um initramfs, primeiramente instale o pacote sys-kernel/genkernel, e em seguida, use-o para gerar um initramfs:

root #emerge --ask sys-kernel/genkernel
root #genkernel --install initramfs

O initramfs será armazenado em /boot/. O arquivo resultante pode ser encontrado listando os arquivos iniciando com "initramfs":

root #ls /boot/initramfs*

Continue agora com os Módulos do kernel

Módulos do kernel

Configurando os módulos

Nota
É opcional listar manualmente os módulos de hardware. udev irá normalmente carregar todos os módulos de hardware que forem detectados ou conectados na maioria dos casos. Entretanto, não causa problema que módulos carregados automaticamente sejam listados. As vezes, algum hardware mais exótico requer alguma ajuda para carregar seus drivers.

Liste os módulos que precisem ser carregados no arquivo /etc/modules-load.d/*.conf, um módulo por linha. Opções extra para os módulos, se necessárias, devem ser configuradas nos arquivos /etc/modprobe.d/*.conf.

Para visualizar todos os módulos disponíveis, execute o seguinte comando find. Não se esqueça de substituir "<kernel version>" pela versão do kernel recém compilada:

root #find /lib/modules/<kernel version>/ -type f -iname '*.o' -or -iname '*.ko' | less

Force loading particular kernel modules

Por exemplo, para carregar automaticamente o módulo 3c59x.ko (que é o driver para uma placa de rede específica da família 3Com), edite o arquivo /etc/modules-load.d/network.conf e entre com o nome do módulo nele. O nome real do arquivo não é significativo para o carregador.

root #mkdir -p /etc/modules-load.d
root #nano -w /etc/modules-load.d/network.conf

Note that the module's .ko file suffix is insignificant to the loading mechanism and left out of the configuration file:

FILE /etc/modules-load.d/network.confForçar o carregamento do módulo 3c59x
3c59x

Continue a instalação em Configurando o sistema.