Installation via chroot (x86/x86_64/aarch64)
This guide details the process of manually installing Void via a chroot on an x86, x86_64 or aarch64 architecture. It is assumed that you have a familiarity with Linux, but not necessarily with installing a Linux system via a chroot. This guide can be used to create a "typical" setup, using a single partition on a single SATA/IDE/USB disk. Each step may be modified to create less typical setups, such as full disk encryption.
Void provides two options for bootstrapping the new installation. The XBPS method uses the XBPS Package Manager running on a host operating system to install the base system. The ROOTFS method installs the base system by unpacking a ROOTFS tarball.
The XBPS method requires that the host operating system have XBPS installed. This may be an existing installation of Void, an official live image, or any Linux installation running a statically linked XBPS.
The ROOTFS method requires only a host operating system that can enter a Linux chroot and that has both tar(1) and xz(1) installed. This method may be preferable if you wish to install Void using a different Linux distribution.
Prepare Filesystems
Partition your disks and format them using mke2fs(8), mkfs.xfs(8), mkfs.btrfs(8) or whatever tools are necessary for your filesystem(s) of choice.
mkfs.vfat(8) is also available to create FAT32 partitions. However, due to restrictions associated with FAT filesystems, it should only be used when no other filesystem is suitable (such as for the EFI System Partition).
cfdisk(8) and fdisk(8) are available on the live images for partitioning, but you may wish to use gdisk(8) (from the package gptfdisk ) or parted(8) instead.
For a UEFI booting system, make sure to create an EFI System Partition (ESP). The ESP should have the partition type "EFI System" (code EF00 ) and be formatted as FAT32 using mkfs.vfat(8).
If you’re unsure what partitions to create, create a 1GB partition of type "EFI System" (code EF00 ), then create a second partition of type "Linux Filesystem" (code 8300 ) using the remainder of the drive.
Format these partitions as FAT32 and ext4, respectively:
Create a New Root and Mount Filesystems
This guide will assume the new root filesystem is mounted on /mnt . You may wish to mount it elsewhere.
If using UEFI, mount the EFI System Partition as /mnt/boot/efi .
For example, if /dev/sda2 is to be mounted as / and dev/sda1 is the EFI System Partition:
Initialize swap space, if desired, using mkswap(8).
Base Installation
Follow only one of the two following subsections.
If on aarch64, it will be necessary to install a kernel package in addition to base-system . For example, linux is a kernel package that points to the latest stable kernel packaged by Void.
The XBPS Method
Select a mirror and use the appropriate URL for the type of system you wish to install. For simplicity, save this URL to a shell variable. A glibc installation, for example, would use:
XBPS also needs to know what architecture is being installed. Available options are x86_64 , x86_64-musl , i686 for PC architecture computers and aarch64 . For example:
This architecture must be compatible with your current operating system, but does not need to be the same. If your host is running an x86_64 operating system, any of the three architectures can be installed (whether the host is musl or glibc), but an i686 host can only install i686 distributions.
Copy the RSA keys from the installation medium to the target root directory:
Use xbps-install(1) to bootstrap the installation by installing the base-system metapackage:
The ROOTFS Method
Unpack the tarball into the newly configured filesystems:
Configuration
With the exception of the section "Install base-system (ROOTFS method only)", the remainder of this guide is common to both the XBPS and ROOTFS installation methods.
Entering the Chroot
xchroot(1) (from xtools ) can be used to set up and enter the chroot. Alternatively, this can be done manually.
Install base-system (ROOTFS method only)
ROOTFS images generally contain out of date software, due to being a snapshot of the time when they were built, and do not come with a complete base-system . Update the package manager and install base-system :
Installation Configuration
Specify the hostname in /etc/hostname . Go through the options in /etc/rc.conf . If installing a glibc distribution, edit /etc/default/libc-locales , uncommenting desired locales.
nvi(1) is available in the chroot, but you may wish to install your preferred text editor at this time.
For glibc builds, generate locale files with:
Set a Root Password
Configure at least one super user account. Other user accounts can be configured later, but there should either be a root password, or a new user account with sudo(8) privileges.
To set a root password, run:
Configure fstab
The fstab(5) file can be automatically generated from currently mounted filesystems by copying the file /proc/mounts :
Remove lines in /etc/fstab that refer to proc , sys , devtmpfs and pts .
Replace references to /dev/sdXX , /dev/nvmeXnYpZ , etc. with their respective UUID, which can be found by running blkid(8). Referring to filesystems by their UUID guarantees they will be found even if they are assigned a different name at a later time. In some situations, such as booting from USB, this is absolutely essential. In other situations, disks will always have the same name unless drives are physically added or removed. Therefore, this step may not be strictly necessary, but is almost always recommended.
Change the last zero of the entry for / to 1 , and the last zero of every other line to 2 . These values configure the behaviour of fsck(8).
For example, the partition scheme used throughout previous examples yields the following fstab :
The information from blkid results in the following /etc/fstab :
Note: The output of /proc/mounts will have a single space between each field. The columns are aligned here for readability.
Add an entry to mount /tmp in RAM:
If using swap space, add an entry for any swap partitions:
Installing GRUB
Use grub-install to install GRUB onto your boot disk.
On a BIOS computer, install the package grub , then run grub-install /dev/sdX , where /dev/sdX is the drive (not partition) that you wish to install GRUB to. For example:
On a UEFI computer, install either grub-x86_64-efi , grub-i386-efi or grub-arm64-efi , depending on your architecture, then run grub-install , optionally specifying a bootloader label (this label may be used by your computer’s firmware when manually selecting a boot device):
Troubleshooting GRUB installation
If EFI variables are not available, add the option —no-nvram to the grub-install command.
Installing on removable media or non-compliant UEFI systems
Unfortunately, not all systems have a fully standards compliant UEFI implementation. In some cases, it is necessary to "trick" the firmware into booting by using the default fallback location for the bootloader instead of a custom one. In that case, or if installing onto a removable disk (such as USB), add the option —removable to the grub-install command.
Alternatively, use mkdir(1) to create the /boot/efi/EFI/boot directory and copy the installed GRUB executable, usually located in /boot/efi/EFI/Void/grubx64.efi (its location can be found using efibootmgr(8)), into the new folder:
Finalization
Use xbps-reconfigure(1) to ensure all installed packages are configured properly:
This will make dracut(8) generate an initramfs, and will make GRUB generate a working configuration.
At this point, the installation is complete. Exit the chroot and reboot your computer:
After booting into your Void installation for the first time, perform a system update.
Русские Блоги
Файловая подсистема — (rootfs) процесс монтирования корневой файловой системы 03
NO1.Загрузка ядра Linux + подробное объяснение процесса загрузки системы Android
https://blog.csdn.net/ahaochina/article/details/72533442
NO2. Конфигурация ядра, компиляция и анализ кода (1)
https://blog.csdn.net/kakasingle/article/details/12851963?utm_source=jiancool
Механизм initrd механизма initrd в NO3.linux и механизм initramfs
http://blog.chinaunix.net/uid-20279362-id-4924898.html
http://cukdd.blog.chinaunix.net/uid-29431466-id-4834509.html
NO4.android запускает процесс с файловой системой initrd
https://blog.csdn.net/wangcong02345/article/details/51659201
Поток обработки ядра NO5.initrd (ramdisk)
https://blog.csdn.net/yiyeguzhou100/article/details/78318100
Процесс монтирования файловой системы Linux и корневой файловой системы (rootfs)
Создание файловой системы .
Анализ процесса монтажа Rootfs
Корневой каталог по умолчанию смонтирован, а вот конкретная файловая система смонтирована.
linux/init
Разбираем разные типы креплений:
image-initrd & cpio-initrd описание процесса
Создание образа initrd

rest_init
Отвечает за загрузку файла initrd, расширение дерева VFS и создание базовой топологии каталогов файловой системы;
initrd — это временная файловая система, загружаемая в память при загрузке и содержащая основные исполняемые программы и драйверы. На начальном этапе инициализации Linux он предоставляет базовую операционную среду. Когда файловая система диска успешно загружена, система переключится на файловую систему диска и удалит initrd.
kernel_init
kernel_init_freeable
Завершите настройку корневого каталога здесь
do_basic_setup();
// Инициализируем драйвер устройства, загружаем статический модуль ядра; освобождаем Initramfs в rootfs
Вызов функции инициализации всех модулей, включая функцию инициализации populate_rootfs initramfs,
Здесь выполняется populate_rootfs, который определяет тип initrd и отправляет его в каталог.
do_initcalls();
- do_initcalls () извлечет начальные адреса этих функций инициализации в модуле драйвера, скомпилированном в ядро, в виде указателей на функции из раздела, начинающегося с __initcall_start и заканчивающегося __initcall_end, чтобы в свою очередь завершить соответствующую инициализацию. Эти функции инициализации получают инструкции от __define_initcall (level, fn), чтобы указать компилятору поместить значения начальных адресов этих функций инициализации в этом разделе в определенном порядке при компиляции
Введение в initcall
Linux определяет специальный сегмент initcall в сегменте кода, в котором хранятся указатели на функции; фаза инициализации linux вызывает do_initcalls () для выполнения функций этого сегмента по очереди. Для получения подробной информации об этом разделе, пожалуйста, обратитесь к скрипту ссылки vmlinux.lds.S.
https://www.cnblogs.com/downey-blog/p/10486653.html
https://blog.csdn.net/mcsbary/article/details/90644101
1. Проанализируйте определение макроса __define_initcall (level, fn).
2. Выполнение do_initcalls ()
do_initcall_level
do_initcalls
3. Вызов vmlinux.lds.h
4. INIT_CALLS vmlinux.lds.S
- Пользователи могут легко регистрировать указатели функций в коде Linux, используя макросы initcall с разными приоритетами; сохранять эти указатели функций в соответствующем разделе initcall; наконец, do_initcalls () выполняет функции в разделе в порядке, соответствующем приоритету.
5. Примеры механизма initcall
populate_rootfs
rootfs_initcall(populate_rootfs)
populate_rootfs в основном завершает обнаружение Initrd и проверяет, является ли это CPIO Initrd или Initramfs или Image-Initrd
- Один из них — это initramfs, интегрированный с ядром. При компиляции ядра сохраните его в области от __initramfs_start до __initramfs_end с помощью сценария связывания и напрямую вызовите unpack_to_rootfs, чтобы передать его в корневой каталог. Если его нет в этой форме, то есть значения __initramfs_start и __initramfs_end равны, а длина равна нулю. Не буду ничего делать
А. Проверьте, существует ли файловая система формата initram, и если она существует, она будет перенесена непосредственно в исходный каталог rootfs "/".
б. Проверьте, является ли это cpio-initrd или image-initrd, и рассмотрите их отдельно.
c. Если это cpio-init, отпустите его непосредственно в каталог «/», в противном случае сохраните image-initrd в initrd.image.
г. Завершите шаг c и освободите место в памяти, занимаемое Initrd.
unpack_to_rootfs(char *buf, unsigned long len)
Если initramfs не существует, значения __initramfs_start и __initramfs_end равны, то есть параметр len = 0, unpack_to_rootfs ничего не сделает.
- Он обращается к файлу XXX.cpio.gz через указатель __initramfs_start и указатель __initramfs_end,
вызвать функцию unpack_to_rootfs, чтобы извлечь исходный файл в rootfs
root_dev_setup
root используется для указания устройства хранения, на котором расположена корневая файловая система, и сохранения имени устройства в статической переменной saved_root_name
__setup ("root =", root_dev_setup); механизм
static char __initdata saved_root_name[64];
static int __init root_dev_setup(char *line)
<
strlcpy(saved_root_name, line, sizeof(saved_root_name));
return 1;
>
__setup(“root=”, root_dev_setup);
fs_names_setup
rootfstype указывает тип файловой системы и сохраняет тип файловой системы в статической переменной root_fs_names.
static char * __initdata root_fs_names;
static int __init fs_names_setup(char *str)
<
root_fs_names = str;
return 1;
>
__setup(“rootfstype=”, fs_names_setup);
// Поскольку я ранее переключался в корневой каталог новой файловой системы, шаги в теге out в основном должны следовать за новым корневым каталогом файловой системы
Замените rootfs, чтобы сделать его корневым каталогом Linux vfs.
// Процесс без использования initrd, устройство файловой системы смонтировано и заменено rootfs, чтобы стать корнем vfs,
Остальные задачи оставлены программе / sbin / init в корневой файловой системе.
prepare_namespace();
- Если тип cpio initrd не используется, ядро выполнит prepare_namespace ()
Путь к функции: kernel / kernel4.14 / init / do_mounts.c
- ** Смонтируйте фактическую корневую файловую систему **
a. Для image-initrd существует два устройства монтирования, одно — root = / dev / mtdblockxx, а другое — root = / dev / ram device
Во-первых, пользователь может использовать root = для указания корневой файловой системы. Его значение хранится в файле saved_root_name. Если пользователь указывает строку, начинающуюся с mtd в качестве корневой файловой системы. Он будет монтироваться напрямую. Этот файл является файлом устройства mtdblock, в противном случае файл узла устройства будет преобразован в ROOT_DEV, который является номером узла устройства. Затем перейдите к initrd_load (), чтобы выполнить предварительную обработку initrd, а затем смонтируйте определенную корневую файловую систему. В конце функции будет вызвана sys_mount (), чтобы переместить текущую точку монтирования файловой системы в каталог «/», а затем переключить корневой каталог в текущий каталог. Точка монтирования корневой файловой системы становится тем, что мы видим в пространстве пользователя. "/".
- initrd_load создает узел устройства / dev / ram0 типа Root_RAM0 (то есть узел устройства ramdisk)
- Вызовите rd_load_image, чтобы загрузить файл /initrd.image в / dev / ram0, а затем удалите файл initrd.image.
- Затем вызовите handle_initrd, чтобы смонтировать узел ramdisk / dev / ram0 в корневой каталог /, введите каталог / root, смонтируйте текущий каталог как корневой каталог,
- Наконец, переключите текущий каталог в положение корневого каталога, на которое ссылается выполнение программы.
Знания для анализа
_setup извлекать save_root_name
initrd_load
а. Вызовите create_dev, чтобы создать узел устройства / dev / ram
б. Вызовите rd_load_image, чтобы освободить initrd.image для / dev / ram0, и определите, указал ли пользователь окончательное имя устройства корневого файла.
c. Если это не Root_ram0, который не указан, он будет передан в функцию handle_initrd для обработки.
Подробный анализ кода выглядит следующим образом:
rd_load_image
А. Откройте (узел устройства / dev / ram0, созданный initrd_load в rootfs) и (образ ramdisk ("initrd.image")) соответственно.
b. nblocks = identify_ramdisk_image(in_fd, rd_image_start, &decompressor);?
c. Вызовите crd_load, чтобы загрузить содержимое initrd.image в узел устройства / dev / ram0.
handle_initrd()
Если ROOT_DEV! = Root_RAM0, вызовите handle_init, чтобы запустить пользовательский режим через linuxrc. (То есть initrd = 0Xxxx, но root = / dev / metdblock2 вызван противоречием)
mount_root()
mount_block_root
do_mount_root () для монтирования корневой файловой системы
do_mount_root
В основном монтировать корневую файловую систему
Подключите устройство, содержащее корневую файловую систему, в корневой каталог / rootfs.
Rootfs linux что это
Creating the root filesystem involves selecting files necessary for the system to run. In this section we describe how to build a compressed root filesystem . A less common option is to build an uncompressed filesystem on a diskette that is directly mounted as root; this alternative is described in Section 9.1 .
A root filesystem must contain everything needed to support a full Linux system. To be able to do this, the disk must include the minimum requirements for a Linux system:
The basic file system structure,
Minimum set of directories: /dev , /proc , /bin , /etc , /lib , /usr , /tmp ,
Basic set of utilities: sh , ls , cp , mv , etc.,
Minimum set of config files: rc, inittab, fstab , etc.,
Devices: /dev/hd*, /dev/tty*, /dev/fd0 , etc.,
Runtime library to provide basic functions used by utilities.
Of course, any system only becomes useful when you can run something on it, and a root diskette usually only becomes useful when you can do something like:
Check a file system on another drive, for example to check your root file system on your hard drive, you need to be able to boot Linux from another drive, as you can with a root diskette system. Then you can run fsck on your original root drive while it is not mounted.
Restore all or part of your original root drive from backup using archive and compression utilities such as cpio , tar , gzip and ftape .
We describe how to build a compressed filesystem, so called because it is compressed on disk and, when booted, is uncompressed onto a ramdisk. With a compressed filesystem you can fit many files (approximately six megabytes) onto a standard 1440K diskette. Because the filesystem is much larger than a diskette, it cannot be built on the diskette. We have to build it elsewhere, compress it, then copy it to the diskette.
In order to build such a root filesystem, you need a spare device that is large enough to hold all the files before compression. You will need a device capable of holding about four megabytes. There are several choices:
Use a ramdisk ( DEVICE = /dev/ram0 ). In this case, memory is used to simulate a disk drive. The ramdisk must be large enough to hold a filesystem of the appropriate size. If you use LILO, check your configuration file ( /etc/lilo.conf ) for a line like RAMDISK = nnn which determines the maximum RAM that can be allocated to a ramdisk. The default is 4096K, which should be sufficient. You should probably not try to use such a ramdisk on a machine with less than 8MB of RAM. Check to make sure you have a device like /dev/ram0, /dev/ram or /dev/ramdisk . If not, create /dev/ram0 with mknod (major number 1, minor 0).
If you have an unused hard disk partition that is large enough (several megabytes), this is acceptable.
Use a loopback device , which allows a disk file to be treated as a device. Using a loopback device you can create a three megabyte file on your hard disk and build the filesystem on it.
Type man losetup for instructions on using loopback devices. If you don’t have losetup , you can get it along with compatible versions of mount and unmount from the util-linux package in the directory ftp://ftp.win.tue.nl/pub/linux/utils/util-linux/ .
If you do not have a loop device ( /dev/loop0 , /dev/loop1 , etc.) on your system, you will have to create one with « mknod /dev/loop0 b 7 0 ». Once you’ve installed these special mount and umount binaries, create a temporary file on a hard disk with enough capacity (eg, /tmp/fsfile ). You can use a command like:
Use the file name in place of DEVICE below. When you issue a mount command you must include the option -o loop to tell mount to use a loopback device.
After you’ve chosen one of these options, prepare the DEVICE with:
Here is a reasonable minimum set of directories for your root filesystem [1] :
/dev — Device files, required to perform I/O
/proc — Directory stub required by the proc filesystem
/etc — System configuration files
/sbin — Critical system binaries
/bin — Essential binaries considered part of the system
/lib — Shared libraries to provide run-time support
/mnt — A mount point for maintenance on other disks
/usr — Additional utilities and applications
Three of these directories will be empty on the root filesystem, so they only need to be created with mkdir . The /proc directory is basically a stub under which the proc filesystem is placed. The directories /mnt and /usr are only mount points for use after the boot/root system is running. Hence again, these directories only need to be created.
The remaining four directories are described in the following sections.
A /dev directory containing a special file for all devices to be used by the system is mandatory for any Linux system. The directory itself is a normal directory, and can be created with mkdir in the normal way. The device special files, however, must be created in a special way, using the mknod command.
There is a shortcut, though — copy devices files from your existing hard disk /dev directory. The only requirement is that you copy the device special files using -R option. This will copy the directory without attempting to copy the contents of the files. Be sure to use an upper case R . For example:
If you want to do it the hard way, use ls -l to display the major and minor device numbers for the devices you want, and create them on the diskette using mknod .
However the devices files are created, check that any special devices you need have been placed on the rescue diskette. For example, ftape uses tape devices, so you will need to copy all of these if you intend to access your floppy tape drive from the bootdisk.
Note that one inode is required for each device special file, and inodes can at times be a scarce resource, especially on diskette filesystems. You’ll need to be selective about the device files you include. For example, if you do not have SCSI disks you can safely ignore /dev/sd* ; if you don’t intend to use serial ports you can ignore /dev/ttyS* .
If, in building your root filesystem, you get the error No space left on device but a df command shows space still available, you have probably run out of inodes. A df -i will display inode usage.
Be sure to include the following files from this directory: console , kmem , mem , null , ram0 and tty1 .
The /etc directory contains configuration files. What it should contain depends on what programs you intend to run. On most systems, these can be divided into three groups:
Required at all times, e.g. rc , fstab , passwd .
May be required, but no one is too sure.
Junk that crept in.
This lists files in reverse order of date last accessed, so if any files are not being accessed, they can be omitted from a root diskette.
On my root diskettes, I have the number of config files down to 15. This reduces my work to dealing with three sets of files:
The ones I must configure for a boot/root system:
rc.d/* — system startup and run level change scripts
fstab — list of file systems to be mounted
inittab — parameters for the init process, the first process started at boot time.
gettydefs — parameters for the init process, the first process started at boot time.
The ones I should tidy up for a boot/root system:
passwd — Critical list of users, home directories, etc.
group — user groups.
shadow — passwords of users. You may not have this.
termcap — the terminal capability database.
If security is important, passwd and shadow should be pruned to avoid copying user passwords off the system, and so that unwanted logins are rejected when you boot from diskette.
Be sure that passwd contains at least root . If you intend other users to login, be sure their home directories and shells exist.
termcap , the terminal database, is typically several hundred kilobytes. The version on your boot/root diskette should be pruned down to contain only the terminal(s) you use, which is usually just the linux or linux-console entry.
The rest. They work at the moment, so I leave them alone.
Out of this, I only really have to configure two files, and what they should contain is surprisingly small.
#!/bin/sh /bin/mount -av /bin/hostname Kangaroo
Be sure it is executable, be sure it has a «#!» line at the top, and be sure any absolute filenames are correct. You don’t really need to run hostname — it just looks nicer if you do.
/dev/ram0 / ext2 defaults /dev/fd0 / ext2 defaults /proc /proc proc defaults
You can copy entries from your existing fstab , but you should not automatically mount any of your hard disk partitions; use the noauto keyword with them. Your hard disk may be damaged or dead when the bootdisk is used.
Your inittab should be changed so that its sysinit line runs rc or whatever basic boot script will be used. Also, if you want to ensure that users on serial ports cannot login, comment out all the entries for getty which include a ttys or ttyS device at the end of the line. Leave in the tty ports so that you can login at the console.
id:2:initdefault: si::sysinit:/etc/rc 1:2345:respawn:/sbin/getty 9600 tty1 2:23:respawn:/sbin/getty 9600 tty2
The inittab file defines what the system will run in various states including startup, move to multi-user mode, etc. Check carefully the filenames mentioned in inittab ; if init cannot find the program mentioned the bootdisk will hang, and you may not even get an error message.
Note that some programs cannot be moved elsewhere because other programs have hardcoded their locations. For example, on my system, /etc/shutdown has hardcoded in it /etc/reboot . If I move reboot to /bin/reboot , and then issue a shutdown command, it will fail because it cannot find the reboot file.
Most systems now use an /etc/rc.d/ directory containing shell scripts for different run levels. The minimum is a single rc script, but it may be simpler just to copy inittab and the /etc/rc.d directory from your existing system, and prune the shell scripts in the rc.d directory to remove processing not relevent to a diskette system environment.
Be sure to include the following programs: init , getty or equivalent, login , mount , some shell capable of running your rc scripts, a link from sh to the shell.
In /lib you place necessary shared libraries and loaders. If the necessary libraries are not found in your /lib directory then the system will be unable to boot. If you’re lucky you may see an error message telling you why.
Nearly every program requires at least the libc library, libc.so. N , where N is the current version number. Check your /lib directory. The file libc.so.N is usually a symlink to a filename with a complete version number:
% ls -l /lib/libc* -rwxr-xr-x 1 root root 4016683 Apr 16 18:48 libc-2.1.1.so* lrwxrwxrwx 1 root root 13 Apr 10 12:25 libc.so.6 -> libc-2.1.1.so*
In this case, you want libc-2.1.1.so . To find other libraries you should go through all the binaries you plan to include and check their dependencies with ldd . For example:
Note that some libraries are quite large and will not fit easily on your root filesystem. For example, the libc.so listed above is about 4 meg. You will probably need to strip libraries when copying them to your root filesystem. See Section 8 for instructions.
In /lib you must also include a loader for the libraries. The loader will be either ld.so (for A.OUT libraries, which are no longer common) or ld-linux.so (for ELF libraries). Newer versions of ldd tell you exactly which loader is needed, as in the example above, but older versions may not. If you’re unsure which you need, run the file command on the library. For example:
Copy the specific loader(s) you need to the root filesystem you’re building. Libraries and loaders should be checked carefully against the included binaries. If the kernel cannot load a necessary library, the kernel may hang with no error message.
Your system may require dynamically loaded libraries that are not visible to ldd . If you don’t provide for these, you may have trouble logging in or using your bootdisk.
If your system uses PAM (Pluggable Authentication Modules), you must make some provision for it on your bootdisk. Briefly, PAM is a sophisticated modular method for authenticating users and controlling their access to services. An easy way to determine if your system uses PAM is run ldd on your login executable; if the output includes libpam.so , you need PAM.
Fortunately, security is usually of no concern with bootdisks since anyone who has physical access to a machine can usually do anything they want anyway. Therefore, you can effectively disable PAM by creating a simple /etc/pam.conf file in your root filesystem that looks like this:
This configuration allows anyone complete access to the files and services on your machine. If you care about security on your bootdisk for some reason, you’ll have to copy some or all of your hard disk’s PAM setup to your root filesystem. Be sure to read the PAM documentation carefully, and copy any libraries needed in /lib/security onto your root filesystem.
You must also include /lib/libpam.so on your bootdisk. But you already know this since you ran ldd on /bin/login , which showed this dependency.
If you are using glibc (aka libc6), you will have to make provisions for name services or you will not be able to login. The file /etc/nsswitch.conf controls database lookups for various servies. If you don’t plan to access services from the network (eg, DNS or NIS lookups), you need only prepare a simple nsswitch.conf file that looks like this:
If you plan to access the network from your bootdisk, you may want to create a more elaborate nsswitch.conf file. See the nsswitch man page for details. You must include a file /lib/libnss_ service .so.1 for each service you specify.
If you have a modular kernel, you must consider which modules you may want to load from your bootdisk after booting. You might want to include ftape and zftape modules if your backup tapes are on floppy tape, modules for SCSI devices if you have them, and possibly modules for PPP or SLIP support if you want to access the net in an emergency.
These modules may be placed in /lib/modules . You should also include insmod , rmmod and lsmod . Depending on whether you want to load modules automatically, you might also include modprobe , depmod and swapout . If you use kerneld , include it along with /etc/conf.modules .
However, the main advantage to using modules is that you can move non-critical modules to a utility disk and load them when needed, thus using less space on your root disk. If you may have to deal with many different devices, this approach is preferable to building one huge kernel with many drivers built in.
In order to boot a compressed ext2 filesystem, you must have ramdisk and ext2 support built-in. They cannot be supplied as modules.
Some system programs, such as login , complain if the file /var/run/utmp and the directory /var/log do not exist. So:
mkdir -p /mnt/var/
Finally, after you have set up all the libraries you need, run ldconfig to remake /etc/ld.so.cache on the root filesystem. The cache tells the loader where to find the libraries. You can do this with:
Notes
| [1] |
| Опция | Описание |
|---|---|
| —disklabel | Включить поддержку LABEL= настроек в файл /etc/fstab |
| —dmraid | Включить поддержку fake hardware RAID |
| —firmware | Включить firmware code, найденный на системе |
| —gpg | Включить поддержку GnuPG |
| —iscsi | Включить поддержку iSCSI |
| —luks | Включить поддержку зашифрованных контейнеров luks |
| —lvm | Включить поддержку LVM |
| —mdadm | Включить поддержку программного (software) RAID |
| —multipath | Включить поддержку множественного I/O-доступа к SAN |
| —zfs | Включить поддержку ZFS |
По завершении, файл initramfs, полученный в результате, будет сохранен в каталоге /boot .
Использование dracut
Утилита dracut создана с единственной целью управления файлами initramfs. Она использует весьма модульный подход в плане выбора поддержки; что требуется включить, а что нет.