Translations:Handbook:X86/Blocks/Bootloader/2/pt-br

From Gentoo Wiki
Jump to:navigation Jump to:search

Existem algumas poucas pequenas exceções para essa regra do firmware UEFI, a saber alguns dos primeiros Apple Macs e alguns Dell tablet PCs com Intel Atom tinham suporte para firmware UEFI de 32 bits. A grande maioria dos leitores nunca irá encontrar firmware UEFI de 32 bits em uso. Por essa razão, firmware UEFI de 32 bits não é explicado no manual da arquitetura .


Com o kernel do Linux configurado, as ferramentas do sistema instaladas e os arquivos de configuração editados, é hora de instalar a última parte importante de uma instalação Linux: o gerenciador de boot.

O gerenciador de boot é responsável por carregar o kernel do Linux no momento do boot - sem ele, o sistema não saberia como proceder quando fosse apertado o botão de ligar.

Para o , documentamos como configurar o GRUB2 ou LILO para sistemas baseados em BIOS e o GRUB2 ou efibootmgr para sistemas UEFI.

Nesta seção do Manual foi feita uma separação entre "fazer o emerge" do pacote do carregador de boot e "instalar" um carregador de boot em um disco do sistema. Aqui o termo "emerge" será usado para solicitar ao Portage tornar o pacote de software disponível ao sistema. O termo "instalar" irá significar fazer a cópia dos arquivos do carregador de boot ou fisicamente modificar as seções apropriadas do drive de disco do sistema de maneira a tornar o carregador de boot "ativo e pronto para operação" no na próxima reinicialização.

Default: GRUB2

Por padrão, a maioria dos sistemas Gentoo agora tende a usar GRUB2 (encontrado no pacote sys-boot/grub), que é o sucessor direto do GRUB Legacy. Com nenhuma configuração adicional, o GRUB2 felizmente suporta sistemas mais antigos com BIOS ("pc"). Com um pouco de configuração, necessário antes da compilação, o GRUB2 pode suportar mais de meia dúzia de plataformas adicionais. Para mais informação, consulte a Seção de prerequisitos do artigo GRUB2.

Emerge

Quando usando um sistema de BIOS antiga que suporta apenas tabelas de partições MBR, nenhuma configuração adicional é necessária para emerge o GRUB:

root #emerge --ask --verbose sys-boot/grub:2

Uma nota para os usuários UEFI: executar o comando acima irá mostrar os valores GRUB_PLATFORMS habilitados antes de se fazer o emerge. Quando usarem sistemas UEFI, os usuários irão precisar ter certeza que GRUB_PLATFORMS="" está habilitado (como é o caso por padrão). Se isso não for necessário para a configuração, GRUB_PLATFORMS="" precisa ser adicionado ao arquivo /etc/portage/make.conf antes de fazer o emerge do GRUB2 para que este pacote seja compilado com a funcionalidade EFI:

root #echo 'GRUB_PLATFORMS=""' >> /etc/portage/make.conf
root #emerge --ask sys-boot/grub:2

Se por alguma razão foi feito emerge do GRUB2 sem habilitar GRUB_PLATFORMS="", a linha (como mostrada acima) pode ser adicionada ao make.conf e então as dependências do conjunto de pacotes world recalculadas passando-se as opções --update --newuse ao emerge:

root #emerge --ask --update --newuse --verbose sys-boot/grub:2

O software GRUB2 está agora adicionado ao sistema, mas não está instalado ainda.

Instale

Em seguida, instale os arquivos do GRUB2 necessários no diretório /boot/grub/ com o comando grub-install. Assumindo que o primeiro disco (aquele do qual o sistema dá boot) é /dev/sda, um dos seguintes comandos fará isso:

  • Se usar BIOS:
root #grub-install /dev/sda

For DOS/Legacy BIOS systems:

root #grub-install /dev/sda
  • Se usar UEFI:
Important
Certifique-se que a partição do sistema EFI tenha sido montada antes de rodar o grub-install. É possível que o grub-install instale o arquivo do GRUB EFI () no diretório errado sem prover nenhuma indicação de que o diretório errado foi usado.

For UEFI systems:

root #grub-install --target= --efi-directory=/boot

Upon successful installation, the output should match the output of the previous command. If the output does not match exactly, then proceed to Debugging GRUB, otherwise jump to the Configure step.

Optional: Secure Boot

The sys-boot/grub package does not recognize the secureboot USE flag, this is because the GRUB EFI executable is not installed by the package but is instead built and installed by the grub-install command. GRUB must therefore be manually signed after installation to the boot partition. Additionally, GRUB is a modular bootloader but loading modules is prohibited when Secure Boot is enabled. Therefore all necessary modules must be compiled into the GRUB EFI executable, below an example is shown including some basic modules, this may have to be adjusted for more advanced configurations:

root #emerge --noreplace sbsigntools
root #export GRUB_MODULES="all_video boot btrfs cat chain configfile echo efifwsetup efinet ext2 fat font gettext gfxmenu gfxterm gfxterm_background gzio halt help hfsplus iso9660 jpeg keystatus loadenv loopback linux ls lsefi lsefimmap lsefisystab lssal memdisk minicmd normal ntfs part_apple part_msdos part_gpt password_pbkdf2 png probe reboot regexp search search_fs_uuid search_fs_file search_label sleep smbios squash4 test true video xfs zfs zfscrypt zfsinfo"
root #grub-install --target= --efi-directory= --modules=${GRUB_MODULES} --sbat /usr/share/grub/sbat.csv
root #sbsign /EFI/GRUB/grubx64.efi --key /path/to/kernel_key.pem --cert /path/to/kernel_key.pem --out /EFI/GRUB/grubx64.efi

To successfully boot with secure boot enabled the used certificate must either be accepted by the UEFI firmware, or shim must be used as a pre-loader. Shim is pre-signed with the third-party Microsoft Certificate, accepted by default by most UEFI motherboards.

How to configure the UEFI firmware to accept custom keys depends on the firmware vendor, which is beyond the scope of the handbook. Below is shown how to setup shim instead:

root #emerge sys-boot/shim sys-boot/mokutil sys-boot/efibootmgr
root #cp /usr/share/shim/BOOTX64.EFI /EFI/GRUB/shimx64.efi
root #cp /usr/share/shim/mmx64.efi /EFI/GRUB/mmx64.efi

Shims MOKlist requires keys in the DER format, since the OpenSSL key generated in the example here is in the PEM format, the key must be converted first:

root #openssl x509 -in /path/to/kernel_key.pem -inform PEM -out /path/to/kernel_key.der -outform DER
Note
The path used here must be the path to the pem file containing the certificate belonging to the generated key. In this example both key and certificate are in the same pem file.

Then the converted certificate can be imported into Shims MOKlist:

root #mokutil --import /path/to/kernel_key.der

And finally we register Shim with the UEFI firmware. In the following command, boot-disk and boot-partition-id must be replaced with the disk and partition identifier of the EFI system partition:

root #efibootmgr --create --disk /dev/boot-disk --part boot-partition-id --loader '\EFI\GRUB\shimx64.efi' --label 'shim' --unicode
Debugging GRUB

When debugging GRUB, there are a couple of quick fixes that may result in a bootable installation without having to reboot to a new live image environment.

In the event that "EFI variables are not supported on this system" is displayed somewhere in the output, it is likely the live image was not booted in EFI mode and is presently in Legacy BIOS boot mode. The solution is to try the removable GRUB step mentioned below. This will overwrite the executable EFI file located at /EFI/BOOT/BOOTX64.EFI. Upon rebooting in EFI mode, the motherboard firmware may execute this default boot entry and execute GRUB.

Important
Se o comando grub-install returnar erro como Could not prepare Boot variable: Read-only file system, pode ser necessário remontar o ponto de montagem especial efivars como de leitura e escrita de modo que o comando tenha sucesso:
root #mount -o remount,rw /sys/firmware/efi/efivars
root #mount -o remount,rw,nosuid,nodev,noexec --types efivarfs efivarfs /sys/firmware/efi/efivars

This is caused by certain non-official Gentoo environments not mounting the special EFI filesystem by default. If the previous command does not run, then reboot using an official Gentoo live image environment in EFI mode.

Alguns fabricantes de placas-mãe parecem suportar apenas o diretório /efi/boot/ como local para o arquivo .EFI na partição de Sistema EFI (ESP). O instalador do GRUB pode executar essa operação automaticamente através da opção --removable. Verifique se a partição ESP está montada antes de executar os comandos a seguir. Presumindo que a ESP está montada em /boot/efi (como sugerido anteriormente), execute:

root #grub-install --target= --efi-directory=/boot --removable

Isso cria o diretório default definido pela especificação UEFI e então copia o arquivo para a localização EFI 'default' definida por essa especificação.

Configure

Em seguida, gere a configuração do GRUB2 baseada na configuração do usuário especificada no arquivo /etc/default/grub e nos scripts /etc/grub.d. Na maioria dos casos, nenhuma configuração é necessária pois o GRUB2 irá detectar automaticamente qual kernel dar boot (o mais recente disponível em /boot/) e qual é o sistema de arquivos raiz. É possível também acrescentar parâmetros para o kernel em /etc/default/grub usando a variável GRUB_CMDLINE_LINUX.

Para gerar a configuração final do GRUB2, execute o comando grub-mkconfig:

root #grub-mkconfig -o /boot/grub/grub.cfg
Generating grub.cfg ...
Found linux image: /boot/vmlinuz-
Found initrd image: /boot/initramfs-genkernel--
done

A saída do comando deve mostrar que pelo menos uma imagem do Linux foi encontrada, já que são necessárias para inicializar o sistema. Se foi criado um initramfs ou o genkernel foi usado para criar o kernel, a imagem correta do initrd deve ser detectada também. Se não for o caso, vá para o diretório /boot/ e cheque seu conteúdo usando ls. Se os arquivos estiverem realmente ausentes, retorne às instruções de configuração e instalação do kernel.

Tip
O utilitário os-prober pode ser usado em conjunto com o GRUB2 para detectar outros sistemas operacionais no drives conectados. Windows 7, 8.1, 10 e outras distribuições Linux são detectáveis. Quem desejar sistemas dual boot devem fazer emerge do pacote sys-boot/os-prober e então executar novamente o comando grub-mkconfig (como visto acima). Se problemas de detecção forem encontrados tenha certeza de ler o artigo GRUB2 inteiramente antes de procurar suporte da comunidade Gentoo.

Alternativa 1: LILO

Emerge

LILO, o LInuxLOader, é o mais testado e verdadeiro "cavalo puxador de arado" dos gerenciadores de boot. Entretanto, lhe faltam alguns recursos comparado ao GRUB. O LILO ainda é usado porque, em alguns sistemas, o GRUB não funciona e o LILO sim. É claro, ele também é usado porque algumas pessoas conhecem o LILO e querem continuar com ele. De qualquer forma, o Gentoo suporta ambos.

Instalar o LILO é muito fácil; apenas use o emerge.

root #emerge --ask sys-boot/lilo

Configure

Para configurar o LILO, primeiro crie o arquivo /etc/lilo.conf:

root #nano -w /etc/lilo.conf

No arquivo de configuração são usadas seções para fazer referência ao kernel inicializável. Certifique-se que os arquivos do kernel (com a versão do kernel) e os arquivos initramfs são conhecidos pois eles serão referenciados no arquivo de configuração.

Note
Se o sistema de arquivo raiz for JFS, adicione uma linha append="ro" depois de cada item de boot uma vez que o JFS precisa refazer seu log antes de permitir a montagem com leitura e escrita.
FILE /etc/lilo.confExemplo de configuração do LILO
'"`UNIQ--pre-00000005-QINU`"'
Note
Se for usado um esquema de particionamento diferente e/ou imagem de kernel, ajuste de acordo.

Se um initramfs é necessário, mude a configuração fazendo referência a esse initramfs e dizendo ao initramfs onde o dispositivo real da partição root se encontra:

FILE /etc/lilo.confAdicionando informação do initramfs à entrada de boot
'"`UNIQ--pre-00000008-QINU`"'

Se opções adicionais precisarem ser passadas ao kernel, use uma declaração append. Por exemplo, para adicionar uma declaração video para habilitar o framebuffer:

FILE /etc/lilo.confAdicionando o parâmetro video às opções de boot
'"`UNIQ--pre-0000000B-QINU`"'

Usuários que usaram o genkernel devem saber que seus kernels usam as mesmas opções de boot que o CD de instalação. Por exemplo, se for necessário suporte a dispositivos SCSI, adicione doscsi como uma opção do kernel.

Agora salve o arquivo e saia.

Instale

Para terminar, execute o /sbin/lilo de modo que o LILO possa aplicar as configurações em /etc/lilo.conf ao sistema (isto é, instalar a si mesmo no disco). Tenha em mente que o /sbin/lilo deve ser executado cada vez que um novo kernel é instalado ou forem feitas mudanças no arquivo lilo.conf de modo a fazer o sistema dar boot se o nome de arquivo do kernel foi alterado.

root #/sbin/lilo

Alternativa 2: Usando o efibootmgr

Em sistemas baseados em UEFI, o firmware UEFI no sistema (ou seja, o gerenciador de boot primário) pode ser instruído diretamente para procurar entradas de boot UEFI. Tais sistemas não precisam de gerenciadores de boot adicionais (também conhecidos como secundários) tais como o GRUB2 para ajudar a inicializar o sistema. Dito isso, a razão para existirem gerenciadores de boot baseados em EFI tais como o GRUB2 é "estender" as funcionalidades dos sistemas UEFI durante o processo de boot. Usar o efibootmgr é na verdade para aqueles que desejam usar uma abordagem minimalista (e mais rígida) para dar boot no sistema; usar o GRUB2 (ver acima) é mais fácil para a maioria dos usuários porque oferece uma forma mais flexível de dar boot em sistemas UEFI.

System administrators who desire to take a minimalist, although more rigid, approach to booting the system can avoid secondary bootloaders and boot the Linux kernel as an EFI stub.

Lembre-se que o pacote sys-boot/efibootmgr não é um gerenciador de boot, mas uma ferramenta para interagir com o firmware UEFI e atualizar suas configurações, assim o kernel Linux que foi previamente instalado pode ser inicializado com opções adicionais (se necessário), ou para permitir múltiplas entradas de boot. Essa interação é feita através das variáveis EFI (por isso a necessidade do suporte do kernel às variáveis EFI).

Certifique-se de ler completamente o artigo EFI stub kernel antes de continuar. O kernel deve ter habilitadas opções específicas para ser bootável pelo firmware UEFI do sistema. Pode ser necessário recompilar o kernel. É também uma boa ideia dar uma olhada no artigo sobre o efibootmgr.

It is also a good idea to take a look at the efibootmgr article for additional information.

Note
Reiterando, o efibootmgr não é requerido para inicializar um sistema UEFI. O kernel do Linux pode (e é) inicializado imediatamente, e opções de linha de comando do kernel adicionais podem ser embutidas pelo kernel do Linux em si (existe uma configuração do kernel que permite ao usuário especificar os parâmetros de boot). Mesmo um initramfs pode ser feito parte do próprio kernel.

Aqueles que decidiram por seguir este caminho necessitam instalar o software:

root #emerge --ask sys-boot/efibootmgr

Depois, crie o diretório /boot/efi/boot/ e então copie o kernel nesse local, chamando-o :

root #mkdir -p /boot/efi/boot
root #cp /boot/vmlinuz-* /boot/efi/boot/
Note
O uso da \ como separador de diretórios é obrigatório quando usamos as definições UEFI.

Depois, diga ao firmware UEFI que uma entrada de boot chamada "Gentoo" deve ser criada, que contém o pseudo kernel EFI recém instalado:

root #efibootmgr --create --disk /dev/sda --part 2 --label "Gentoo" --loader "\efi\boot\"

Se um sistema de arquivo inicial em RAM (initramfs) deve ser usado, adicione a opção de boot apropriada para ele:

root #efibootmgr -c -d /dev/sda -p 2 -L "Gentoo" -l "\efi\boot\" initrd='\initramfs-genkernel--'

Note that the above command presumes an initramfs file was copied into the ESP inside the same directory as the file.

Com essas alterações feitas, quando o sistema reiniciar, uma entrada de boot chamada "Gentoo" estará disponível.

Unified Kernel Image

If installkernel was configured to build and install unified kernel images. The unified kernel image should already be installed to the EFI/Linux directory on the EFI system partition, if this is not the case ensure the directory exists and then run the kernel installation again as described earlier in the handbook.

To add a direct boot entry for the installed unified kernel image:

root #efibootmgr --create --disk /dev/sda --part 1 --label "gentoo" --loader /EFI/Linux/gentoo-x.y.z.efi

Alternativa 3: Syslinux

O syslinux é mais uma alternativa de gerenciador de boot para a arquitetura . Ele suporta MBR e, a partir da versão 6.00, suporta também boot EFI. Boot de rede (PXE) e outras opções menos conhecidas são também suportadas. Apenas do syslinux ser um gerenciador de boot popular para muitos usuários, ele não é suportado por este manual. Leitores podem encontrar informações para fazer emerge e instalar este gerenciador de boot no artigo Syslinux.

Alternative 4: systemd-boot

Another option is systemd-boot, which works on both OpenRC and systemd machines. It is a thin chainloader and works well with secure boot.

To install systemd-boot:

root #bootctl install
Important
Make sure the EFI system partition has been mounted before running bootctl install.

When using this bootloader, before rebooting, verify that a new bootable entry exists using:

root #bootctl list

If no new entry exists, ensure the sys-kernel/installkernel package has been installed with the systemd-boot USE flag enabled, and re-run the kernel installation.

For the distribution kernels:

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

For a manually configured and compiled kernel:

root #make install
Important
When installing kernels for systemd-boot, no root= kernel command line argument is added by default. On systemd systems that are using an initramfs users may rely instead on systemd-gpt-auto-generator to automatically find the root partition at boot. Otherwise users should manually specify the location of the root partition by setting root= in /etc/kernel/cmdline as well as any other kernel command line arguments that should be used. And then reinstalling the kernel as described above.

Optional: Secure Boot

When the secureboot USE flag is enabled, the systemd-boot EFI executable will be signed automatically. bootctl install will automatically install the signed version.

To successfully boot with secure boot enabled the used certificate must either be accepted by the UEFI firmware, or shim must be used as a pre-loader. Shim is pre-signed with the third-party Microsoft Certificate, accepted by default by most UEFI motherboards.

How to configure the UEFI firmware to accept custom keys depends on the firmware vendor, which is beyond the scope of the handbook. A postinst hook to automatically update systemd-boot and set it up with shim instead is provided on the systemd-boot wiki page. However the first time this should be done manually by following the steps below:

root #emerge --ask sys-boot/shim sys-boot/mokutil sys-boot/efibootmgr
root #cp /usr/share/shim/BOOTX64.EFI /EFI/BOOT/BOOTX64.EFI
root #cp /usr/share/shim/mmx64.efi /EFI/BOOT/mmx64.efi
root #cp /EFI/systemd/systemd-bootx64.efi /EFI/BOOT/grubx64.efi
Note
Shim is hardcoded to load grubx64.efi. As such the systemd-boot bootloader must be named as if it were GRUB.

Shims MOKlist requires keys in the DER format, since the OpenSSL key generated in the example here is in the PEM format, the key must be converted first:

root #openssl x509 -in /path/to/kernel_key.pem -inform PEM -out /path/to/kernel_key.der -outform DER
Note
The path used here must be the path to the pem file containing the certificate belonging to the generated key. In this example both key and certificate are in the same pem file.

Then the converted certificate can be imported into Shims MOKlist:

root #mokutil --import /path/to/kernel_key.der

And finally we register Shim with the UEFI firmware. In the following command, boot-disk and boot-partition-id must be replaced with the disk and partition identifier of the EFI system partition:

root #efibootmgr --create --disk /dev/boot-disk --part boot-partition-id --loader '\EFI\BOOT\BOOTX64.EFI' --label 'shim' --unicode