mkinitcpio (简体中文)

From ArchWiki
Revision as of 04:13, 26 December 2011 by Cuihao (Talk | contribs)

Jump to: navigation, search

This template has only maintenance purposes. For linking to local translations please use interlanguage links, see Help:i18n#Interlanguage links.


Local languages: Català – Dansk – English – Español – Esperanto – Hrvatski – Indonesia – Italiano – Lietuviškai – Magyar – Nederlands – Norsk Bokmål – Polski – Português – Slovenský – Česky – Ελληνικά – Български – Русский – Српски – Українська – עברית – العربية – ไทย – 日本語 – 正體中文 – 简体中文 – 한국어


External languages (all articles in these languages should be moved to the external wiki): Deutsch – Français – Română – Suomi – Svenska – Tiếng Việt – Türkçe – فارسی

Summary help replacing me
介绍Arch的initramfs创建工具。
Overview
Template:Boot process overview (简体中文)

mkinitcpio是新一代initramfs创建工具。

概览

mkinitcpio是一个用来创建初始化内存盘(initial ramdisk,简称initrd)的bash脚本。摘自mkinitcpio手册页

初始化内存盘本质上是一个很小的运行环境(早期用户空间,early userspace),用于加载一些核心模块,并在init接管启动过程之前准备一些必须的东西,比如加密的根文件系统、在RAID上的根文件系统。使用mkinicpio可以方便地使用自定义的钩子扩展(hooks)、运行时自动检测、以及其他功能。

从前,内核在启动过程早期(挂载根目录和启动init之前)处理一切硬件的检测和初始化。然而,但随着技术的演进,这种做法变得十分繁琐。

如今,根文件系统可能位于各种硬件上,如SCSI设备、SATA设备、U盘,而这些硬件受控于形形色色的厂家所提供的五花八门的驱动之下。另外,根系统可以加密、压缩,可存放在RAID阵列中,或者一个逻辑卷组上。为了简化这复杂的过程,可以把管理权转入一个用户空间:初始化内存盘。

另见:/dev/brain0 » Blog Archive » Early Userspace in Arch Linux

用模块化的mkinitcpio构建初始化内存盘镜像(init ramfs cpio image),较之其他方法有诸多优势:

  • 使用轻量的busybox作为早期用户空间的基础(早在0.6版本时,使用的是klibc)。
  • 支持udev运行时硬件探测,避免加载不需要的模块。
  • 由于使用了支持钩子扩展的init脚本,可以方便的使用pacman软件包安装自定义钩子扩展。
  • 同时支持传统和LUKS卷上的lvm2dm-crypt,以及从U盘启动所需的mdadmswsuspsuspend2
  • 支持通过启动参数配置内核功能,无需重新编译。
  • Support for the inclusion of the image in a kernel, thus making a self-contained kernel image possible.

mkinitcpio最初由phrakturetpowabrain0以及部分社区人士开发。最近,falconindy接手了开发工作。

安装

mkinitcpio软件包被收录于官方软件仓库。作为base软件包组的一部分,应该已经自动安装了。

从git获取mkinitcpio的最新开发版本:

$ git clone git://projects.archlinux.org/mkinitcpio.git
注意: 若要使用git开发版本,严重建议同时加入arch-projects列表!

创建和启用镜像

每次升级内核,mkinitcpio都会默认创建两个内存盘镜像:默认镜像/boot/initramfs-linux.imgfallback镜像/boot/initramfs-linux-fallback.imgfallback镜像和默认镜像只有一个区别,就是创建时跳过了autodetect钩子扩展,因而它包含更多的内核模块。autodetect扩展会探测硬件信息,针对硬件向镜像添加需要的模块,因此缩小了镜像。

在创建初始化内存盘镜像时,可以使用很多不同配置。创建完成后,在启动引导器菜单文件(如GRUB/boot/grub/menu.lst)中添加启动项目,即可使用新镜像。更改mkinitcpio配置后,需要手动重新生成镜像。以Arch默认的内核linux为例:

# mkinitcpio -p linux

-p选项定义了要使用的预配置(preset);多数内核软件包都会提供一套mkinitcpio预配置文件,放在/etc/mkinitcpio.d目录(比如,linux内核是/etc/mkinitcpio.d/linux.preset)。预配置文件中包含内存盘镜像的基本配置。

警告: 每次升级内核,系统都会自动使用预配置文件重新生成内存盘镜像。不要轻易编辑这些文件。

使用其他配置文件创建镜像:

# mkinitcpio -c /etc/mkinitcpio-custom.conf -g /boot/linux-custom.img

这将为当前内核创建一个新的内存盘镜像,存储于/boot/linux-custom.img

为其他内核创建镜像:

# mkinitcpio -g /boot/linux.img -k 3.0.0-ARCH

配置

The primary configuration file for mkinitcpio is /etc/mkinitcpio.conf. Additionally, preset definitions are provided by kernel packages in the /etc/mkinitcpio.d directory (e.g. /etc/mkinitcpio.d/linux.preset).

Warning: lvm2, mdadm, and encrypt are NOT enabled by default. Please read this section carefully for instructions if these hooks are required.
Note: Users with multiple hardware disk controllers that use the same node names but different kernel modules (e.g. two SCSI/SATA or two IDE controllers) should ensure the correct order of modules is specified in /etc/mkinitcpio.conf. Otherwise, the root device location may change between boots, resulting in kernel panics. A more elegant alternative is to use persistent block device naming to ensure that the right devices are mounted.

Users can modify six variables within the configuration file:

MODULES
Kernel modules to be loaded before any boot hooks are run.
BINARIES
Additional binaries to be included in the initramfs image.
FILES
Additional files to be included in the initramfs image.
HOOKS
Hooks are scripts that execute in the initial ramdisk.
COMPRESSION
Used to compress the initramfs image.
COMPRESSION_OPTIONS
Command line options to pass to the COMPRESSION program.

模块(MODULES)

The MODULES array is used to specify modules to load before anything else is done. To accelerate the boot process, users may opt to disable the udev hook and list required modules here instead:

MODULES="piix ide_disk reiserfs"

[...]

HOOKS="base autodetect ide filesystems"

Modules suffixed with a '?' will not throw errors if they are not found. This might be useful for custom kernels that compile in modules which are listed explicitly in a hook or config file.

Note: If using reiser4, it must be added to the modules list. Additionally, if you'll be needing any filesystem during the boot process that isn't live when you run mkinitcpio---for example, if your LUKS encryption key file is on an ext2 filesystem but no ext2 filesystems are mounted when you run mkinitcpio---that filesystem module must also be added to the MODULES list. See here for more details.

Tango-view-fullscreen.pngThis article or section needs expansion.Tango-view-fullscreen.png

Reason: please use the first argument of the template to provide a brief explanation. (Discuss in Talk:Mkinitcpio (简体中文)#)
Template:Box YELLOW

Known modules that are not autoloaded during boot process (status stock kernel 2.6.18): scsi_transport_sas, ultrastor, qlogicfas, eata, BusLogic, pas16, wd7000, sym53c416, g_NCR5380_mmio, fdomain, u14-34f, dtc, initio, in2000, imm, t128, aha1542, aha152x, atp870u, g_NCR5380, NCR53c406a, qlogicfas408, megaraid_mm, advansys.

If one of the above modules are required for the root device, consider explicitly adding it to /etc/mkinitcpio.conf to avoid kernel panics.

附加文件(BINARIES、FILES)

These options allow users to add files to the image. Both BINARIES and FILES are added before hooks are run, and may be used to override files used or provided by a hook. BINARIES are auto-located within a standard PATH and dependency-parsed, meaning any required libraries will also be added. FILES are added as-is. For example:

FILES="/etc/modprobe.d/modprobe.conf"
BINARIES="fsck fsck.ext4"

钩子扩展(HOOKS)

A hook is a script that executes in the initial ramdisk. Hooks are found within the /lib/initcpio/install directory; for a list of available hooks:

$ ls -1 /lib/initcpio/install

Use mkinitcpio's -H option to output help for a specific hook. For example, to display information about the base hook:

$ mkinitcpio -H base

Hooks are listed in order of execution, and are used to add files or modules to the image. Thus, hooks can affect installation – when mkinitcpio is run to generate the image – and/or runtime – via an included script that is run during boot. Scripts can be found within the /lib/initcpio/hooks directory.

The default configuration will work for most users with a standard setup:

HOOKS="base udev autodetect pata scsi sata filesystems"

If using the image on more than one machine, remove the autodetect hook, which tailors the image to the build machine:

HOOKS="base udev pata scsi sata filesystems"

For support for encrypted volumes on LVM2 volume groups:

HOOKS="base udev autodetect pata scsi sata lvm2 encrypt filesystems"

A table of common hooks and their function follows. Note that this table is not complete, as packages can provide custom hooks.

Common hooks
Hook Installation Runtime
base Sets up all initial directories and installs base utilities and libraries. Always add this hook unless you know what you are doing. --
udev Adds udevd, udevadm, and a small subset of udev rules to your image. Starts the udev daemon and processes uevents from the kernel; creating device nodes. As it simplifies the boot process by not requiring the user to explicitly specify necessary modules, using the udev hook is recommended.
autodetect Shrinks your initramfs to a smaller size by creating a whitelist of modules from a scan of sysfs. Be sure to verify included modules are correct and none are missing. This hook must be run before other subsystem hooks in order to take advantage of auto-detection. Any hooks placed before 'autodetect' will be installed in full. --
pata Adds the new libata/PATA IDE modules to the image. Use this if your root device is on a IDE disk. Also use the autodetect hook if you want to minimize your image size --
sata Adds serial ATA modules to the image. Use this if your root device is on a SATA disk. Also use the autodetect hook if you want to minimize your image size. --
scsi Adds SCSI modules to the image. Use this if your root device is on a SCSI disk. Also use the autodetect hook if you want to minimize your image size. --
usb Adds USB modules to the image. Use this if your root device is on a USB mass storage device or if your USB mass storage device needs to be accessed otherwise (checked, mounted, etc.) at boot time. --
usbinput Adds USB HID modules to the image. Use this if you have an USB keyboard and need it in early userspace (either for entering encryption passphrases or for use in an interactive shell). --
fw Adds FireWire modules to the image. Use this if your root device is on a FW mass storage device. --
net Adds the necessary modules for a network device. For PCMCIA net devices please add the pcmcia hook too. Provides handling for an NFS based root filesystem.
pcmcia Adds the necessary modules for PCMCIA devices. You need to have pcmciautils installed to use this. --
dsdt Loads a custom ACPI DSDT file during boot. Place your custom DSDT file for inclusion at /lib/initcpio/custom.dsdt The custom DSDT file is automatically used by the kernel if it is present in initramfs.
filesystems This includes necessary filesystem modules into your image. This hook is required unless you specify your filesystem modules in MODULES. --
lvm2 Adds the device mapper kernel module and the lvm tool to the image. You need to have the lvm2 package installed to use this. Enables all LVM2 volume groups. This is necessary if you have your root filesystem on LVM.
mdadm Provides support for assembling the arrays from /etc/mdadm.conf, or autodetection during boot. Locates and assembles software RAID block devices using mdassemble.
mdadm_udev Provides support for assembling the arrays via udev. Locates and assembles software RAID block devices using udev and mdadm incremental assembly.
encrypt Adds the dm-crypt kernel module and the cryptsetup tool to the image. You need to have the cryptsetup package installed to use this. Detects and unlocks an encrypted root partition. See #Runtime customization for further configuration.
resume -- This tries to resume from the "suspend to disk" state. Works with both swsusp and suspend2. See #Runtime customization for further configuration.
keymap Adds keymap and consolefonts from rc.conf. Loads the specified keymap and consolefont from rc.conf during early userspace.
fsck Adds the fsck binary and filesystem specific helpers. If added after the autodetect hook, only the helper specific to your root filesystem will be added. Runs fsck against your root device prior to mounting.

编写钩子扩展

An initcpio hook is just another shell script containing necessary information pointing mkinitcpio which executables should be loaded and with what options. It can be useful in some rare occasions when something is needed in early or late userspace, when not provided by other already installed scripts.

First create the actual script:

/lib/initcpio/install/hook
 #!/bin/bash
 
 build() {
     SCRIPT="hook" #the name of the hook
     add_binary /bin/bash  #/bin/bash is given as an example, you can type your desired executable here
 }
 
 help() {
     cat <<HELPEOF
     Line used as help information #Typing mkinitcpio -H hook will display this information
 HELPEOF
 }

Now create the actual hook:

/lib/initcpio/hooks/hook
 run_hook ()
 {
     msg -n ":: This is an example hook"
     bash #your executable example
     msg "done."
 }
Note: It is not necessary to make either of the two scripts executable, nor is it advised.

Now edit /etc/mkinitcpio.conf accordingly to include your custom hook. You can also include it in /etc/rc.sysinit to load it in late userspace.

压缩方式(COMPRESSION)

The kernel supports several formats for compression of the initramfs - gzip, bzip2, lzma, xz (also known as lzma2), and lzo. For most use cases, gzip or lzop provide the best balance of compressed image size and decompression speed.

COMPRESSION="gzip"
COMPRESSION="bzip2"     # requires kernel 2.6.30
COMPRESSION="lzma"      # requires kernel 2.6.30
COMPRESSION="lzop"      # requires kernel 2.6.34
COMPRESSION="xz"        # requires kernel 2.6.38

Specifying no COMPRESSION will result in a gzip compressed initramfs file. To create an uncompressed image, specify COMPRESSION=cat in the config or use -z cat on the command line.

压缩选项(COMPRESSION_OPTIONS)

These are additional flags passed to the program specified by COMPRESSION, such as:

COMPRESSION_OPTIONS='-9'

In general these should never be needed as mkinitcpio will make sure that any supported compression method has the necessary flags to produce a working image.

运行时配置

Runtime configuration options can be passed to init and certain hooks via the kernel command line. Kernel command line parameters are often supplied by the bootloader. For example, a typical Arch Linux GRUB entry:

/boot/grub/menu.lst
...

# (0) Arch Linux
title  Arch Linux  [/boot/vmlinuz-linux]
root   (hd0,0)
kernel /vmlinuz-linux root=/dev/sda3 ro
initrd /initramfs-linux.img

...

In this case, root=/dev/sda3 and ro are kernel command line parameters. The options discussed below can be appended to the kernel command line to alter default behavior. See Arch Boot Process for more information.

init

Note: The following options alter the default behavior of init in the initramfs environment. See /lib/initcpio/init for details.
root
This is the most important parameter specified on the kernel command line, as it determines what device will be mounted as your proper root device. mkinitcpio is flexible enough to allow a wide variety of formats, for example:
root=/dev/sda1                                                # /dev node
root=LABEL=CorsairF80                                         # label
root=UUID=ea1c4959-406c-45d0-a144-912f4e86b207                # UUID
root=/dev/disk/by-path/pci-0000:00:1f.2-scsi-0:0:0:0-part1    # udev symlink (requires the udev hook)
root=801                                                      # hex-encoded major/minor number
break
If break or break=premount is specified, init pauses the boot process (after loading hooks, but before mounting the root filesystem) and launches an interactive shell which can be used for troubleshooting purposes. This shell can be launched after the root has been mounted by specifying break=postmount. Normal boot continues after exiting from the shell.
disablehooks
Disable hooks at runtime by adding disablehooks=hook1{,hook2,...}. For example:
disablehooks=resume
earlymodules
Alter the order in which modules are loaded by specifying modules to load early via earlymodules=mod1{,mod2,...}. (This may be used, for example, to ensure the correct ordering of multiple network interfaces.)
rootdelay
Pause for ten seconds before mounting the root file system by appending rootdelay. (This may be used, for example, if booting from a USB hard drive that takes longer to initialize.)

使用 RAID 磁盘阵列

First, add the mdadm hook to the HOOKS array and any required RAID modules to the MODULES array in /etc/mkinitcpio.conf.

Kernel Parameters: Using the mdadm hook, you no longer need to configure your RAID array in the GRUB parameters. The mdadm hook will either use your /etc/mdadm.conf file or automatically detect the array(s) during the init phase of boot.

Assembly via udev is also possible using the mdadm_udev hook. Upstream prefers this method of assembly. /etc/mdadm.conf will still be read for purposes of naming the assembled devices if it exists.

Using net

Required Packages:

net requires the mkinitcpio-nfs-utils package from the official repositories.

Kernel Parameters:

ip=

An interface spec can be either short form, which is just the name of an interface (eth0 or whatever), or long form. The long form consists of up to seven elements, separated by colons:

 ip=<client-ip>:<server-ip>:<gw-ip>:<netmask>:<hostname>:<device>:<autoconf>
 nfsaddrs= is an alias to ip= and can be used too.

Parameter explanation:

 <client-ip>   IP address of the client. If empty, the address will
               either be determined by RARP/BOOTP/DHCP. What protocol
               is used depends on the <autoconf> parameter. If this
               parameter is not empty, autoconf will be used.
 
 <server-ip>   IP address of the NFS server. If RARP is used to
               determine the client address and this parameter is NOT
               empty only replies from the specified server are
               accepted. To use different RARP and NFS server,
               specify your RARP server here (or leave it blank), and
               specify your NFS server in the `nfsroot' parameter
               (see above). If this entry is blank the address of the
               server is used which answered the RARP/BOOTP/DHCP
               request.
 
 <gw-ip>       IP address of a gateway if the server is on a different
               subnet. If this entry is empty no gateway is used and the
               server is assumed to be on the local network, unless a
               value has been received by BOOTP/DHCP.
 
 <netmask>     Netmask for local network interface. If this is empty,
               the netmask is derived from the client IP address assuming
               classful addressing, unless overridden in BOOTP/DHCP reply.
 
 <hostname>    Name of the client. If empty, the client IP address is
               used in ASCII notation, or the value received by
               BOOTP/DHCP.
 
 <device>      Name of network device to use. If this is empty, all
               devices are used for RARP/BOOTP/DHCP requests, and the
               first one we receive a reply on is configured. If you
               have only one device, you can safely leave this blank.
 
 <autoconf>	Method to use for autoconfiguration. If this is either
               'rarp', 'bootp', or 'dhcp' the specified protocol is
               used.  If the value is 'both', 'all' or empty, all
               protocols are used.  'off', 'static' or 'none' means
               no autoconfiguration.

Examples:

 ip=127.0.0.1:::::lo:none  --> Enable the loopback interface.
 ip=192.168.1.1:::::eth2:none --> Enable static eth2 interface.
 ip=:::::eth0:dhcp --> Enable dhcp protocol for eth0 configuration.

nfsroot=

If the nfsroot parameter is NOT given on the command line, the default /tftpboot/%s will be used.

 nfsroot=[<server-ip>:]<root-dir>[,<nfs-options>]

Parameter explanation:

 <server-ip>   Specifies the IP address of the NFS server. If this field
               is not given, the default address as determined by the
               `ip' variable (see below) is used. One use of this
               parameter is for example to allow using different servers
               for RARP and NFS. Usually you can leave this blank.
 
 <root-dir>    Name of the directory on the server to mount as root. If
               there is a "%s" token in the string, the token will be
               replaced by the ASCII-representation of the client's IP
               address.
 
 <nfs-options> Standard NFS options. All options are separated by commas.
               If the options field is not given, the following defaults
               will be used:
                       port            = as given by server portmap daemon
                       rsize           = 1024
                       wsize           = 1024
                       timeo           = 7
                       retrans         = 3
                       acregmin        = 3
                       acregmax        = 60
                       acdirmin        = 30
                       acdirmax        = 60
                       flags           = hard, nointr, noposix, cto, ac

root=/dev/nfs

If you do not use the nfsroot parameter, you need to set root=/dev/nfs to boot from an NFS root by autoconfiguration.

使用 lvm

If your root device is on lvm, you have to add the lvm2 hook. You have to pass your root device on the kernel command line in the format

root=/dev/mapper/<volume group name>-<logical volume name>

for example

root=/dev/mapper/myvg-root

使用加密根目录

If your root volume is encrypted, you need to add the encrypt hook. Then specify your root device on the kernel command line, just as if it was unencrypted.

For an encrypted partition on a SATA or SCSI disk:

root=/dev/sda5

For an encrypted LVM volume:

root=/dev/mapper/myvg-root

The root device will be automatically changed to /dev/mapper/root.

使用 LUKS 卷

If you use LUKS for hard disk encryption, the init script will detect the encryption automatically if the encrypt hook is enabled. It will then ask for a passphrase and try to unlock the volume.

If this fails, try to add your filesystem-module to the module list in /etc/mkinitcpio.conf, if it is not compiled into your kernel.

Using a key-file

You can use a key-file to encrypt your root filesystem. Use the following format:

cryptkey=device:fs-type:path

device is the device-file representing the device your key is stored on (e.g. /dev/sda1), fs-type is the filesystem type of this device (e.g. ext3) and path is the path to the key-file inside the filesystem of this device.

Using legacy cryptsetup volumes

If you are using a legacy cryptsetup volume, you have to specify all cryptsetup options necessary to unlock it on the kernel command line. The option format is

crypto=hash:cipher:keysize:offset:skip

representing cryptsetup's --hash, --cipher, --keysize, --offset, and --skip options. If you omit an option, cryptsetup's default value is used, so you could just specify the following if you created your volume with the default settings:

crypto=::::
Note: For technical reasons, it is not possible to verify the correctness of your passphrase with legacy cryptsetup volumes. If you typed it wrong, mounting will simply fail. It is recommended that you use LUKS instead.

Using loop-aes volumes

mkinitcpio does not support loop-aes yet.

疑难解答

解压缩镜像

If you are curious about what is inside the initrd image, you can extract it and poke at the files inside of it.

The initrd image is an SVR4 CPIO archive, generated via the find and bsdcpio commands, optionally compressed with a compression scheme understood by the kernel: namely gzip, bzip2, lzma, lzo, or xz.

mkinitcpio includes a utility called lsinitcpio which will list and extract the contents of initramfs images.

You can list the files in the image with:

$ lsinitcpio /boot/initramfs-linux.img

And to extract them all in the current directory:

$ lsinitcpio -x /boot/initramfs-linux.img

You can also get a more human-friendly listing of the important parts in the image:

$ lsinitcpio -a /boot/initramfs-linux.img

参考资料

  1. Linux Kernel documentation on initramfs
  2. Linux Kernel documentation on initrd
  3. Wikipedia article on initrd