bootup

package: systemd

title: bootup(7)

summary: System bootup process

text:
# bootup(7)

## NAME
bootup - System bootup process

## DESCRIPTION
A number of different components are involved in the boot of a Linux system. Immediately after power-up, the system firmware will do minimal hardware initialization, and hand control over to a boot loader (e.g. systemd-boot(7) or GRUB[1]) stored on a persistent storage device. This boot loader will then invoke an OS kernel from disk (or the network). On systems using EFI or other types of firmware, this firmware may also load the kernel directly.

The kernel (optionally) mounts an in-memory file system, which looks for the root file system. Nowadays this is implemented as an "initramfs" — a compressed CPIO archive that the kernel extracts into a tmpfs. In the past normal file systems using an in-memory block device (ramdisk) were used, and the name "initrd" is still used to describe both concepts. It's the boot loader or the firmware that loads both the kernel and initrd/initramfs images into memory, but the kernel which interprets it as a file system. systemd(1) may be used to manage services in the initrd, similarly to the real system.

After the root file system is found and mounted, the initrd hands over control to the host's system manager (such as systemd(1)) stored in the root file system, which is then responsible for probing all remaining hardware, mounting all necessary file systems and spawning all configured services.

On shutdown, the system manager stops all services, unmounts all non-busy file systems (detaching the storage technologies backing them), and then (optionally) jumps into the exitrd. The exitrd is backed by tmpfs and unmounts/detaches the remaining file systems, including the real root. As a last step, the system is powered down.

Additional information about the system boot process may be found in boot(7).

## SYSTEM MANAGER BOOTUP
At boot, the system manager on the OS image is responsible for initializing the required file systems, services and drivers that are necessary for operation of the system. On systemd(1) systems, this process is split up in various discrete steps which are exposed as target units. (See systemd.target(5) for detailed information about target units.) The boot-up process is highly parallelized so that the order in which specific target units are reached is not deterministic, but still adheres to a limited amount of ordering structure.

When systemd starts up the system, it will activate all units that are dependencies of default.target (as well as recursively all dependencies of these dependencies). Usually, default.target is simply an alias of graphical.target or multi-user.target, depending on whether the system is configured for a graphical UI or only for a text console. To enforce minimal ordering between the units pulled in, a number of well-known target units are available, as listed on systemd.special(7).

The following chart is a structural overview of these well-known units and their position in the boot-up logic. The arrows describe which units are pulled in and ordered before which other units. Units near the top are started before units nearer to the bottom of the chart.

```
                             cryptsetup-pre.target veritysetup-pre.target

                                                  |
(various low-level                                v

 API VFS mounts:             (various cryptsetup/veritysetup devices...)

 mqueue, configfs,                                |    |

 debugfs, ...)                                    v    |

 |                                  cryptsetup.target  |

 |  (various swap                                 |    |    remote-fs-pre.target

 |   devices...)                                  |    |     |        |

 |    |                                           |    |     |        v

 |    v                       local-fs-pre.target |    |     |  (network file systems)

 |  swap.target                       |           |    v     v                 |

 |    |                               v           |  remote-cryptsetup.target  |

 |    |  (various low-level  (various mounts and  |  remote-veritysetup.target |

 |    |   services: udevd,    fsck services...)   |             |              |

 |    |   tmpfiles, random            |           |             |    remote-fs.target

 |    |   seed, sysctl, ...)          v           |             |              |

 |    |      |                 local-fs.target    |             | _____________/

 |    |      |                        |           |             |/

 \____|______|_______________   ______|___________/             |

                             \ /                                |

                              v                                 |

                       sysinit.target                           |

                              |                                 |

       ______________________/|\_____________________           |

      /              |        |      |               \          |

      |              |        |      |               |          |

      v              v        |      v               |          |

 (various       (various      |  (various            |          |

  timers...)      paths...)   |   sockets...)        |          |

      |              |        |      |               |          |

      v              v        |      v               |          |
timers.target  paths.target   |  sockets.target      |          |

      |              |        |      |               v          |

      v              \_______ | _____/         rescue.service   |

                             \|/                     |          |

                              v                      v          |

                          basic.target         rescue.target    |

                              |                                 |

                      ________v____________________             |

                     /              |              \            |

                     |              |              |            |

                     v              v              v            |

                 display-    (various system   (various system  |

             manager.service     services        services)      |

                     |         required for        |            |

                     |        graphical UIs)       v            v

                     |              |            multi-user.target
emergency.service    |              |              |

        |            \_____________ | _____________/

        v                          \|/
emergency.target                    v

                              graphical.target
```

Target units that are commonly used as boot targets are emphasized. These units are good choices as goal targets, for example by passing them to the systemd.unit= kernel command line option (see systemd(1)) or by symlinking default.target to them.

timers.target is pulled-in by basic.target asynchronously. This allows timers units to depend on services which become only available later in boot.

## USER MANAGER STARTUP
The system manager starts the user@uid.service unit for each user, which launches a separate unprivileged instance of systemd for each user — the user manager. Similarly to the system manager, the user manager starts units which are pulled in by default.target. The following chart is a structural overview of the well-known user units. For non-graphical sessions, default.target is used. Whenever the user logs into a graphical session, the login manager will start the graphical-session.target target that is used to pull in units required for the graphical session. A number of targets (shown on the right side) are started when specific hardware is available to the user.

```
   (various           (various         (various

    timers...)         paths...)        sockets...)    (sound devices)

        |                  |                 |               |

        v                  v                 v               v

  timers.target      paths.target     sockets.target    sound.target

        |                  |                 |

        \______________   _|_________________/         (bluetooth devices)

                       \ /                                   |

                        V                                    v

                  basic.target                          bluetooth.target

                        |

             __________/ \_______                      (smartcard devices)

            /                    \                           |

            |                    |                           v

            |                    v                      smartcard.target

            v            graphical-session-pre.target
(various user services)          |                       (printers)

            |                    v                           |

            |       (services for the graphical session)     v

            |                    |                       printer.target

            v                    v

     default.target      graphical-session.target
```

## BOOTUP IN THE INITRD
Systemd can be used in the initrd as well. It detects the initrd environment by checking for the /etc/initrd-release file. The default target in the initrd is initrd.target. The bootup process is identical to the system manager bootup until the target basic.target. After that, systemd executes the special target initrd.target. Before any file systems are mounted, the manager will determine whether the system shall resume from hibernation or proceed with normal boot. This is accomplished by systemd-hibernate-resume.service which must be finished before local-fs-pre.target, so no filesystems can be mounted before the check is complete. When the root device becomes available, initrd-root-device.target is reached. If the root device can be mounted at /sysroot, the sysroot.mount unit becomes active and initrd-root-fs.target is reached. The service initrd-parse-etc.service scans /sysroot/etc/fstab for a possible /usr/ mount point and additional entries marked with the x-initrd.mount option. All entries found are mounted below /sysroot, and initrd-fs.target is reached. The service initrd-cleanup.service isolates to the initrd-switch-root.target, where cleanup services can run. As the very last step, the initrd-switch-root.service is activated, which will cause the system to switch its root to /sysroot.

```
                               : (beginning identical to above)

                               :

                               v

                         basic.target

                               |                       emergency.service

        ______________________/|                               |

       /                       |                               v

       |            initrd-root-device.target          emergency.target

       |                       |

       |                       v

       |                  sysroot.mount

       |                       |

       |                       v

       |             initrd-root-fs.target

       |                       |

       |                       v

       v            initrd-parse-etc.service
(custom initrd                 |

 services...)                  v

       |            (sysroot-usr.mount and

       |             various mounts marked

       |               with fstab option

       |              x-initrd.mount...)

       |                       |

       |                       v

       |                initrd-fs.target

       \______________________ |

                              \|

                               v

                          initrd.target

                               |

                               v

                     initrd-cleanup.service

                          isolates to

                    initrd-switch-root.target

                               |

                               v

        ______________________/|

       /                       v

       |        initrd-udevadm-cleanup-db.service

       v                       |
(custom initrd                 |

 services...)                  |

       \______________________ |

                              \|

                               v

                   initrd-switch-root.target

                               |

                               v

                   initrd-switch-root.service

                               |

                               v

                     Transition to Host OS
```

## SYSTEM MANAGER SHUTDOWN
System shutdown with systemd also consists of various target units with some minimal ordering structure applied:

```
                       (conflicts with  (conflicts with

                          all system     all file system

                           services)     mounts, swaps,

                               |           cryptsetup/

                               |           veritysetup

                               |          devices, ...)

                               |                |

                               v                v

                        shutdown.target    umount.target

                               |                |

                               \_______   ______/

                                       \ /

                                        v

                               (various low-level

                                    services)

                                        |

                                        v

                                  final.target

                                        |

            ___________________________/ \_________________________________

           /               |               |               |               \

           |               |               |               |               |

           v               |               |               |               |
systemd-reboot.service     |               |               |               |

           |               v               |               |               |

           |    systemd-poweroff.service   |               |               |

           v               |               v               |               |

     reboot.target         |      systemd-halt.service     |               |

                           v               |               v               |

                   poweroff.target         |    systemd-kexec.service      |

                                           v               |               |

                                      halt.target          |  systemd-soft-reboot.service

                                                           v               |

                                                     kexec.target          |

                                                                           v

                                                                   soft-reboot.target
```

Commonly used system shutdown targets are emphasized.

Note that systemd-halt.service(8), systemd-reboot.service, systemd-poweroff.service and systemd-kexec.service will transition the system and server manager (PID 1) into the second phase of system shutdown (implemented in the systemd-shutdown binary), which will unmount any remaining file systems, kill any remaining processes and release any other remaining resources, in a simple and robust fashion, without taking any service or unit concept into account anymore. At that point, regular applications and resources are generally terminated and released already, the second phase hence operates only as safety net for everything that could not be stopped or released for some reason during the primary, unit-based shutdown phase described above.

## THE EXITRD
The "exitrd" is a concept symmetrical to the initrd. When the system manager is shutting down and /run/initramfs/shutdown exists, it will switch root to /run/initramfs/ and execute /shutdown. This program runs from the tmpfs mounted on /run/, so it can unmount the old root file system and perform additional steps, for example dismantle complex storage or perform additional logging about the shutdown.

## SEE ALSO
systemd(1), boot(7), systemd.special(7), systemd.target(5), systemd-halt.service(8), systemd-soft-reboot.service(8)

## NOTES
1.

GRUB

https://www.gnu.org/software/grub/


daemon

title: daemon(7)

summary: Writing and packaging system daemons

text:
# daemon(7)

## NAME
daemon - Writing and packaging system daemons

## DESCRIPTION
A daemon is a service process that runs in the background and supervises the system or provides functionality to other processes. Traditionally, daemons are implemented following a scheme originating in SysV Unix. Modern daemons should follow a simpler yet more powerful scheme (here called "new-style" daemons), as implemented by systemd(1). This manual page covers both schemes, and in particular includes recommendations for daemons that shall be included in the systemd init system.

### SysV Daemons
When a traditional SysV daemon starts, it should execute the following steps as part of the initialization. Note that these steps are unnecessary for new-style daemons (see below), and should only be implemented if compatibility with SysV is essential.

1.Close all open file descriptors except standard input, output, and error (i.e. the first three file descriptors 0, 1, 2). This ensures that no accidentally passed file descriptor stays around in the daemon process. On Linux, this is best implemented by iterating through /proc/self/fd, with a fallback of iterating from file descriptor 3 to the value returned by getrlimit() for RLIMIT_NOFILE.

2.Reset all signal handlers to their default. This is best done by iterating through the available signals up to the limit of _NSIG and resetting them to SIG_DFL.

3.Reset the signal mask using sigprocmask().

4.Sanitize the environment block, removing or resetting environment variables that might negatively impact daemon runtime.

5.Call fork(), to create a background process.

6.In the child, call setsid() to detach from any terminal and create an independent session.

7.In the child, call fork() again, to ensure that the daemon can never re-acquire a terminal again. (This is relevant if the program — and all its dependencies — does not carefully specify `O_NOCTTY` on each and every single `open()` call that might potentially open a TTY device node.)

8.Call exit() in the first child, so that only the second child (the actual daemon process) stays around. This ensures that the daemon process is re-parented to init/PID 1, as all daemons should be.

9.In the daemon process, connect /dev/null to standard input, output, and error.

10.In the daemon process, reset the umask to 0, so that the file modes passed to open(), mkdir() and suchlike directly control the access mode of the created files and directories.

11.In the daemon process, change the current directory to the root directory (/), in order to avoid that the daemon involuntarily blocks mount points from being unmounted.

12.In the daemon process, write the daemon PID (as returned by getpid()) to a PID file, for example /run/foobar.pid (for a hypothetical daemon "foobar") to ensure that the daemon cannot be started more than once. This must be implemented in race-free fashion so that the PID file is only updated when it is verified at the same time that the PID previously stored in the PID file no longer exists or belongs to a foreign process.

13.In the daemon process, drop privileges, if possible and applicable.

14.From the daemon process, notify the original process started that initialization is complete. This can be implemented via an unnamed pipe or similar communication channel that is created before the first fork() and hence available in both the original and the daemon process.

15.Call exit() in the original process. The process that invoked the daemon must be able to rely on that this exit() happens after initialization is complete and all external communication channels are established and accessible.

The BSD daemon() function should not be used, as it implements only a subset of these steps.

A daemon that needs to provide compatibility with SysV systems should implement the scheme pointed out above. However, it is recommended to make this behavior optional and configurable via a command line argument to ease debugging as well as to simplify integration into systems using systemd.

### New-Style Daemons
Modern services for Linux should be implemented as new-style daemons. This makes it easier to supervise and control them at runtime and simplifies their implementation.

For developing a new-style daemon, none of the initialization steps recommended for SysV daemons need to be implemented. New-style init systems such as systemd make all of them redundant. Moreover, since some of these steps interfere with process monitoring, file descriptor passing, and other functionality of the service manager, it is recommended not to execute them when run as new-style service.

Note that new-style init systems guarantee execution of daemon processes in a clean process context: it is guaranteed that the environment block is sanitized, that the signal handlers and mask is reset and that no left-over file descriptors are passed. Daemons will be executed in their own session, with standard input connected to /dev/null and standard output/error connected to the systemd-journald.service(8) logging service, unless otherwise configured. The umask is reset.

It is recommended for new-style daemons to implement the following:

1.If applicable, the daemon should notify the service manager about startup completion or status updates via the sd_notify(3) interface, in particular READY=1 and STATUS=....

2.If SIGTERM is received, shut down the daemon and exit cleanly. A STOPPING=1 notification should be sent via sd_notify(3).

3.If SIGHUP is received, reload the configuration files, if this applies. This should be combined with notifications via sd_notify(3): RELOADING=1 and READY=1.

4.Provide a correct exit code from the main daemon process, as this is used by the service manager to detect service errors and problems. It is recommended to follow the exit code scheme as defined in the LSB recommendations for SysV init scripts[1].

5.If possible and applicable, expose the daemon's control interface via the D-Bus IPC system and grab a bus name as last step of initialization.

6.For integration in systemd, provide a .service unit file that carries information about starting, stopping and otherwise maintaining the daemon. See systemd.service(5) for details.

7.As much as possible, rely on the service manager's functionality to limit the access of the daemon to files, services, and other resources, i.e. in the case of systemd, rely on systemd's resource limit control instead of implementing your own, rely on systemd's privilege dropping code instead of implementing it in the daemon, and so on. See systemd.exec(5) for the available controls.

8.If D-Bus is used, make your daemon bus-activatable by supplying a D-Bus service activation configuration file. This has multiple advantages: your daemon may be started lazily on-demand; it may be started in parallel to other daemons requiring it — which maximizes parallelization and boot-up speed; your daemon can be restarted on failure without losing any bus requests, as the bus queues requests for activatable services. See below for details.

9.If your daemon provides services to other local processes or remote clients via a socket, it should be made socket-activatable following the scheme pointed out below. Like D-Bus activation, this enables on-demand starting of services as well as it allows improved parallelization of service start-up. Also, for state-less protocols (such as syslog, DNS), a daemon implementing socket-based activation can be restarted without losing a single request. See below for details.

10.If the service opens sockets or other files on it own, and those file descriptors shall survive a restart, the daemon should store them in the service manager via sd_notify(3) with FDSTORE=1.

11.Instead of using the syslog() call to log directly to the system syslog service, a new-style daemon may choose to simply log to standard error via fprintf(), which is then forwarded to syslog. If log levels are necessary, these can be encoded by prefixing individual log lines with strings like "<4>" (for log level 4 "WARNING" in the syslog priority scheme), following a similar style as the Linux kernel's printk() level system. For details, see sd-daemon(3) and systemd.exec(5).

12.As new-style daemons are invoked without a controlling TTY (but as their own session leaders) care should be taken to always specify O_NOCTTY on open(2) calls that possibly reference a TTY device node, so that no controlling TTY is accidentally acquired.

These recommendations are similar but not identical to the Apple MacOS X Daemon Requirements[2].

## ACTIVATION
New-style init systems provide multiple additional mechanisms to activate services, as detailed below. It is common that services are configured to be activated via more than one mechanism at the same time. An example for systemd: bluetoothd.service might get activated either when Bluetooth hardware is plugged in, or when an application accesses its programming interfaces via D-Bus. Or, a print server daemon might get activated when traffic arrives at an IPP port, or when a printer is plugged in, or when a file is queued in the printer spool directory. Even for services that are intended to be started on system bootup unconditionally, it is a good idea to implement some of the various activation schemes outlined below, in order to maximize parallelization. If a daemon implements a D-Bus service or listening socket, implementing the full bus and socket activation scheme allows starting of the daemon with its clients in parallel (which speeds up boot-up), since all its communication channels are established already, and no request is lost because client requests will be queued by the bus system (in case of D-Bus) or the kernel (in case of sockets) until the activation is completed.

### Activation on Boot
Old-style daemons are usually activated exclusively on boot (and manually by the administrator) via SysV init scripts, as detailed in the LSB Linux Standard Base Core Specification[1]. This method of activation is supported ubiquitously on Linux init systems, both old-style and new-style systems. Among other issues, SysV init scripts have the disadvantage of involving shell scripts in the boot process. New-style init systems generally use updated versions of activation, both during boot-up and during runtime and using more minimal service description files.

In systemd, if the developer or administrator wants to make sure that a service or other unit is activated automatically on boot, it is recommended to place a symlink to the unit file in the .wants/ directory of either multi-user.target or graphical.target, which are normally used as boot targets at system startup. See systemd.unit(5) for details about the .wants/ directories, and systemd.special(7) for details about the two boot targets.

### Socket-Based Activation
In order to maximize the possible parallelization and robustness and simplify configuration and development, it is recommended for all new-style daemons that communicate via listening sockets to use socket-based activation. In a socket-based activation scheme, the creation and binding of the listening socket as primary communication channel of daemons to local (and sometimes remote) clients is moved out of the daemon code and into the service manager. Based on per-daemon configuration, the service manager installs the sockets and then hands them off to the spawned process as soon as the respective daemon is to be started. Optionally, activation of the service can be delayed until the first inbound traffic arrives at the socket to implement on-demand activation of daemons. However, the primary advantage of this scheme is that all providers and all consumers of the sockets can be started in parallel as soon as all sockets are established. In addition to that, daemons can be restarted with losing only a minimal number of client transactions, or even any client request at all (the latter is particularly true for state-less protocols, such as DNS or syslog), because the socket stays bound and accessible during the restart, and all requests are queued while the daemon cannot process them.

New-style daemons which support socket activation must be able to receive their sockets from the service manager instead of creating and binding them themselves. For details about the programming interfaces for this scheme provided by systemd, see sd_listen_fds(3) and sd-daemon(3). For details about porting existing daemons to socket-based activation, see below. With minimal effort, it is possible to implement socket-based activation in addition to traditional internal socket creation in the same codebase in order to support both new-style and old-style init systems from the same daemon binary.

systemd implements socket-based activation via .socket units, which are described in systemd.socket(5). When configuring socket units for socket-based activation, it is essential that all listening sockets are pulled in by the special target unit sockets.target. It is recommended to place a WantedBy=sockets.target directive in the [Install] section to automatically add such a dependency on installation of a socket unit. Unless DefaultDependencies=no is set, the necessary ordering dependencies are implicitly created for all socket units. For more information about sockets.target, see systemd.special(7). It is not necessary or recommended to place any additional dependencies on socket units (for example from multi-user.target or suchlike) when one is installed in sockets.target.

### Bus-Based Activation
When the D-Bus IPC system is used for communication with clients, new-style daemons should use bus activation so that they are automatically activated when a client application accesses their IPC interfaces. This is configured in D-Bus service files (not to be confused with systemd service unit files!). To ensure that D-Bus uses systemd to start-up and maintain the daemon, use the SystemdService= directive in these service files to configure the matching systemd service for a D-Bus service. e.g.: For a D-Bus service whose D-Bus activation file is named org.freedesktop.RealtimeKit.service, make sure to set SystemdService=rtkit-daemon.service in that file to bind it to the systemd service rtkit-daemon.service. This is needed to make sure that the daemon is started in a race-free fashion when activated via multiple mechanisms simultaneously.

### Device-Based Activation
Often, daemons that manage a particular type of hardware should be activated only when the hardware of the respective kind is plugged in or otherwise becomes available. In a new-style init system, it is possible to bind activation to hardware plug/unplug events. In systemd, kernel devices appearing in the sysfs/udev device tree can be exposed as units if they are tagged with the string "systemd". Like any other kind of unit, they may then pull in other units when activated (i.e. plugged in) and thus implement device-based activation. systemd dependencies may be encoded in the udev database via the SYSTEMD_WANTS= property. See systemd.device(5) for details. Often, it is nicer to pull in services from devices only indirectly via dedicated targets. Example: Instead of pulling in bluetoothd.service from all the various bluetooth dongles and other hardware available, pull in bluetooth.target from them and bluetoothd.service from that target. This provides for nicer abstraction and gives administrators the option to enable bluetoothd.service via controlling a bluetooth.target.wants/ symlink uniformly with a command like enable of systemctl(1) instead of manipulating the udev ruleset.

### Path-Based Activation
Often, runtime of daemons processing spool files or directories (such as a printing system) can be delayed until these file system objects change state, or become non-empty. New-style init systems provide a way to bind service activation to file system changes. systemd implements this scheme via path-based activation configured in .path units, as outlined in systemd.path(5).

### Timer-Based Activation
Some daemons that implement clean-up jobs that are intended to be executed in regular intervals benefit from timer-based activation. In systemd, this is implemented via .timer units, as described in systemd.timer(5).

### Other Forms of Activation
Other forms of activation have been suggested and implemented in some systems. However, there are often simpler or better alternatives, or they can be put together of combinations of the schemes above. Example: Sometimes, it appears useful to start daemons or .socket units when a specific IP address is configured on a network interface, because network sockets shall be bound to the address. However, an alternative to implement this is by utilizing the Linux IP_FREEBIND/IPV6_FREEBIND socket option, as accessible via FreeBind=yes in systemd socket files (see systemd.socket(5) for details). This option, when enabled, allows sockets to be bound to a non-local, not configured IP address, and hence allows bindings to a particular IP address before it actually becomes available, making such an explicit dependency to the configured address redundant. Another often suggested trigger for service activation is low system load. However, here too, a more convincing approach might be to make proper use of features of the operating system, in particular, the CPU or I/O scheduler of Linux. Instead of scheduling jobs from userspace based on monitoring the OS scheduler, it is advisable to leave the scheduling of processes to the OS scheduler itself. systemd provides fine-grained access to the CPU and I/O schedulers. If a process executed by the service manager shall not negatively impact the amount of CPU or I/O bandwidth available to other processes, it should be configured with CPUSchedulingPolicy=idle and/or IOSchedulingClass=idle. Optionally, this may be combined with timer-based activation to schedule background jobs during runtime and with minimal impact on the system, and remove it from the boot phase itself.

## INTEGRATION WITH SYSTEMD

### Writing systemd Unit Files
When writing systemd unit files, it is recommended to consider the following suggestions:

1.If possible, do not use the Type=forking setting in service files. But if you do, make sure to set the PID file path using PIDFile=. See systemd.service(5) for details.

2.If your daemon registers a D-Bus name on the bus, make sure to use Type=dbus in the service file if possible.

3.Make sure to set a good human-readable description string with Description=.

4.Do not disable DefaultDependencies=, unless you really know what you do and your unit is involved in early boot or late system shutdown.

5.Normally, little if any dependencies should need to be defined explicitly. However, if you do configure explicit dependencies, only refer to unit names listed on systemd.special(7) or names introduced by your own package to keep the unit file operating system-independent.

6.Make sure to include an [Install] section including installation information for the unit file. See systemd.unit(5) for details. To activate your service on boot, make sure to add a WantedBy=multi-user.target or WantedBy=graphical.target directive. To activate your socket on boot, make sure to add WantedBy=sockets.target. Usually, you also want to make sure that when your service is installed, your socket is installed too, hence add Also=foo.socket in your service file foo.service, for a hypothetical program foo.

### Installing systemd Service Files
At the build installation time (e.g. make install during package build), packages are recommended to install their systemd unit files in the directory returned by pkg-config systemd --variable=systemdsystemunitdir (for system services) or pkg-config systemd --variable=systemduserunitdir (for user services). This will make the services available in the system on explicit request but not activate them automatically during boot. Optionally, during package installation (e.g. rpm -i by the administrator), symlinks should be created in the systemd configuration directories via the enable command of the systemctl(1) tool to activate them automatically on boot.

Packages using autoconf(1) are recommended to use a configure script excerpt like the following to determine the unit installation path during source configuration:

```
PKG_PROG_PKG_CONFIG()
AC_ARG_WITH([systemdsystemunitdir],

     [AS_HELP_STRING([--with-systemdsystemunitdir=DIR], [Directory for systemd service files])],,

     [with_systemdsystemunitdir=auto])
AS_IF([test "x$with_systemdsystemunitdir" = "xyes" -o "x$with_systemdsystemunitdir" = "xauto"], [

     def_systemdsystemunitdir=$($PKG_CONFIG --variable=systemdsystemunitdir systemd)

     AS_IF([test "x$def_systemdsystemunitdir" = "x"],

   [AS_IF([test "x$with_systemdsystemunitdir" = "xyes"],

    [AC_MSG_ERROR([systemd support requested but pkg-config unable to query systemd package])])

    with_systemdsystemunitdir=no],

   [with_systemdsystemunitdir="$def_systemdsystemunitdir"])])
AS_IF([test "x$with_systemdsystemunitdir" != "xno"],

      [AC_SUBST([systemdsystemunitdir], [$with_systemdsystemunitdir])])
AM_CONDITIONAL([HAVE_SYSTEMD], [test "x$with_systemdsystemunitdir" != "xno"])
```

This snippet allows automatic installation of the unit files on systemd machines, and optionally allows their installation even on machines lacking systemd. (Modification of this snippet for the user unit directory is left as an exercise for the reader.)

Additionally, to ensure that make distcheck continues to work, it is recommended to add the following to the top-level Makefile.am file in automake(1)-based projects:

```
AM_DISTCHECK_CONFIGURE_FLAGS = \

  --with-systemdsystemunitdir=$$dc_install_base/$(systemdsystemunitdir)
```

Finally, unit files should be installed in the system with an automake excerpt like the following:

```
if HAVE_SYSTEMD
systemdsystemunit_DATA = \

  foobar.socket \

  foobar.service
endif
```

In the rpm(8) .spec file, use snippets like the following to enable/disable the service during installation/deinstallation. This makes use of the RPM macros shipped along systemd. Consult the packaging guidelines of your distribution for details and the equivalent for other package managers.

At the top of the file:

```
BuildRequires: systemd
%{?systemd_requires}
```

And as scriptlets, further down:

```
%post
%systemd_post foobar.service foobar.socket
%preun
%systemd_preun foobar.service foobar.socket
%postun
%systemd_postun
```

If the service shall be restarted during upgrades, replace the "%postun" scriptlet above with the following:

```
%postun
%systemd_postun_with_restart foobar.service
```

Note that "%systemd_post" and "%systemd_preun" expect the names of all units that are installed/removed as arguments, separated by spaces. "%systemd_postun" expects no arguments. "%systemd_postun_with_restart" expects the units to restart as arguments.

To facilitate upgrades from a package version that shipped only SysV init scripts to a package version that ships both a SysV init script and a native systemd service file, use a fragment like the following:

```
%triggerun -- foobar < 0.47.11-1
if /sbin/chkconfig --level 5 foobar ; then

  /bin/systemctl --no-reload enable foobar.service foobar.socket >/dev/null 2>&1 || :
fi
```

Where 0.47.11-1 is the first package version that includes the native unit file. This fragment will ensure that the first time the unit file is installed, it will be enabled if and only if the SysV init script is enabled, thus making sure that the enable status is not changed. Note that chkconfig is a command specific to Fedora which can be used to check whether a SysV init script is enabled. Other operating systems will have to use different commands here.

## PORTING EXISTING DAEMONS
Since new-style init systems such as systemd are compatible with traditional SysV init systems, it is not strictly necessary to port existing daemons to the new style. However, doing so offers additional functionality to the daemons as well as simplifying integration into new-style init systems.

To port an existing SysV compatible daemon, the following steps are recommended:

1.If not already implemented, add an optional command line switch to the daemon to disable daemonization. This is useful not only for using the daemon in new-style init systems, but also to ease debugging.

2.If the daemon offers interfaces to other software running on the local system via local AF_UNIX sockets, consider implementing socket-based activation (see above). Usually, a minimal patch is sufficient to implement this: Extend the socket creation in the daemon code so that sd_listen_fds(3) is checked for already passed sockets first. If sockets are passed (i.e. when sd_listen_fds() returns a positive value), skip the socket creation step and use the passed sockets. Secondly, ensure that the file system socket nodes for local AF_UNIX sockets used in the socket-based activation are not removed when the daemon shuts down, if sockets have been passed. Third, if the daemon normally closes all remaining open file descriptors as part of its initialization, the sockets passed from the service manager must be spared. Since new-style init systems guarantee that no left-over file descriptors are passed to executed processes, it might be a good choice to simply skip the closing of all remaining open file descriptors if sockets are passed.

3.Write and install a systemd unit file for the service (and the sockets if socket-based activation is used, as well as a path unit file, if the daemon processes a spool directory), see above for details.

4.If the daemon exposes interfaces via D-Bus, write and install a D-Bus activation file for the service, see above for details.

## PLACING DAEMON DATA
It is recommended to follow the general guidelines for placing package files, as discussed in file-hierarchy(7).

## NOTES
All example codes in this page are licensed under "MIT No Attribution" (SPDX-License-Identifier: MIT-0).

## SEE ALSO
systemd(1), sd-daemon(3), sd_listen_fds(3), sd_notify(3), daemon(3), systemd.service(5), file-hierarchy(7)

## NOTES
1.

LSB recommendations for SysV init scripts

http://refspecs.linuxbase.org/LSB_3.1.1/LSB-Core-generic/LSB-Core-generic/iniscrptact.html

2.

Apple MacOS X Daemon Requirements

https://developer.apple.com/library/mac/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html

branch: sisyphus


file-hierarchy

title: file-hierarchy(7)

text:
# file-hierarchy(7)

## NAME
file-hierarchy - systemd file system hierarchy requirements

## DESCRIPTION
Operating systems using the systemd(1) system and service manager are organized based on a file system hierarchy inspired by UNIX, as described in Linux File System Hierarchy[1]. Additional requirements on when given parts of the hierarchy must be available during boot are listed in Mount Requirements[2].

Many of the paths described here can be queried with the systemd-path(1) tool.

## SEE ALSO
hier(7)

File System Hierarchy[3]

XDG Base Directory Specification[4]

XDG User Directories[5]

## NOTES
1.

Linux File System Hierarchy

https://uapi-group.org/specifications/specs/linux_file_system_hierarchy/

2.

Mount Requirements

https://systemd.io/MOUNT_REQUIREMENTS/

3.

File System Hierarchy

http://refspecs.linuxfoundation.org/FHS_3.0/fhs-3.0.html

4.

XDG Base Directory Specification

https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html

5.

XDG User Directories

https://www.freedesktop.org/wiki/Software/xdg-user-dirs


kernel-command-line

title: kernel-command-line(7)

summary: Kernel command line parameters

text:
# kernel-command-line(7)

## NAME
kernel-command-line - Kernel command line parameters

## SYNOPSIS
/proc/cmdline

## DESCRIPTION
The kernel, the programs running in the initrd and in the host system may be configured at boot via kernel command line arguments.

For command line parameters understood by the kernel, please see kernel-parameters.html[1] and bootparam(7).

For command line parameters understood by the initrd, see the documentation of the specific initrd implementation of your installation.

## CORE OS COMMAND LINE ARGUMENTS
systemd.unit=, rd.systemd.unit=, systemd.dump_core, systemd.crash_chvt, systemd.crash_shell, systemd.crash_action=, systemd.confirm_spawn, systemd.service_watchdogs, systemd.show_status, systemd.status_unit_format=, systemd.log_target=, systemd.log_level=, systemd.log_location=, systemd.log_color, systemd.log_ratelimit_kmsg, systemd.default_standard_output=, systemd.default_standard_error=, systemd.setenv=, systemd.machine_id=, systemd.set_credential=, systemd.set_credential_binary=, systemd.import_credentials=, systemd.reload_limit_interval_sec=, systemd.reload_limit_burst=

Parameters understood by the system and service manager to control system behavior. For details, see systemd(1). Added in version 186.

systemd.mask=, systemd.wants=, systemd.debug_shell, systemd.default_debug_tty=

Additional parameters understood by systemd-debug-generator(8), to mask or start specific units at boot, or invoke a debug shell on tty9. Added in version 215.

systemd.break=, rd.systemd.break=

Parameters understood by systemd-debug-generator(8), to pause the boot process at a certain point and spawn a debug shell. Added in version 258.

systemd.run=, systemd.run_success_action=, systemd.run_failure_action=

Additional parameters understood by systemd-run-generator(8), to run a command line specified on the kernel command line as system service after booting up. Added in version 240.

systemd.early_core_pattern=

During early boot, the generation of core dump files is disabled until a core dump handler (if any) takes over. This parameter allows specifying an absolute path where core dump files should be stored until a handler is installed. The path should be absolute and may contain specifiers, see core(5) for details. Added in version 240.

systemd.restore_state=

This parameter is understood by several system tools to control whether or not they should restore system state from the previous boot. For details, see systemd-backlight@.service(8) and systemd-rfkill.service(8). Added in version 209.

systemd.ssh_auto=, systemd.ssh_listen=

These parameters are interpreted by systemd-ssh-generator(8) and may be used to control SSH sockets the system shall be reachable on. Added in version 256.

systemd.volatile=

This parameter controls whether the system shall boot up in volatile mode. Takes a boolean argument, or the special values "state" or "overlay". If false (the default), normal boot mode is selected, the root directory and /var/ are mounted as specified on the kernel command line or /etc/fstab, or otherwise configured. If true, full state-less boot mode is selected. In this case, the root directory is mounted as volatile memory file system ("tmpfs"), and only /usr/ is mounted from the file system configured as root device, in read-only mode. This enables fully state-less boots were the vendor-supplied OS is used as shipped, with only default configuration and no stored state in effect, as /etc/ and /var/ (as well as all other resources shipped in the root file system) are reset at boot and lost on shutdown. If this setting is set to "state" the root file system is mounted read-only, however /var/ is mounted as a volatile memory file system ("tmpfs"), so that the system boots up with the normal configuration applied, but all state reset at boot and lost at shutdown. If this setting is set to "overlay" the root file system is set up as "overlayfs" mount combining the read-only root directory with a writable "tmpfs", so that no modifications are made to disk, but the file system may be modified nonetheless with all changes being lost at reboot. For details, see systemd-volatile-root.service(8) and systemd-fstab-generator(8). Added in version 233.

quiet

Parameter understood by both the kernel and the system and service manager to control console log verbosity. For details, see systemd(1). Added in version 186.

debug

Parameter understood by both the kernel and the system and service manager to control console log verbosity. For details, see systemd(1). Added in version 205.

-b, rd.emergency, emergency, rd.rescue, rescue, single, s, S, 1, 2, 3, 4, 5

Parameters understood by the system and service manager, as compatibility and convenience options. For details, see systemd(1). Added in version 186.

locale.LANG=, locale.LANGUAGE=, locale.LC_CTYPE=, locale.LC_NUMERIC=, locale.LC_TIME=, locale.LC_COLLATE=, locale.LC_MONETARY=, locale.LC_MESSAGES=, locale.LC_PAPER=, locale.LC_NAME=, locale.LC_ADDRESS=, locale.LC_TELEPHONE=, locale.LC_MEASUREMENT=, locale.LC_IDENTIFICATION=

Parameters understood by the system and service manager to control locale and language settings. For details, see systemd(1). Added in version 186.

fsck.mode=, fsck.repair=

Parameters understood by the file system checker services. For details, see systemd-fsck@.service(8). Added in version 186.

quotacheck.mode=

Parameter understood by the file quota checker service. For details, see systemd-quotacheck@.service(8). Added in version 186.

systemd.journald.forward_to_syslog=, systemd.journald.forward_to_kmsg=, systemd.journald.forward_to_console=, systemd.journald.forward_to_wall=

Parameters understood by the journal service. For details, see systemd-journald.service(8). Added in version 186.

vconsole.keymap=, vconsole.keymap_toggle=, vconsole.font=, vconsole.font_map=, vconsole.font_unimap=

Parameters understood by the virtual console setup logic. For details, see vconsole.conf(5). Added in version 186.

udev.log_level=, rd.udev.log_level=, udev.trace=, rd.udev.trace=, udev.children_max=, rd.udev.children_max=, udev.exec_delay=, rd.udev.exec_delay=, udev.event_timeout=, rd.udev.event_timeout=, udev.timeout_signal=, rd.udev.timeout_signal=, udev.blockdev_read_only, rd.udev.blockdev_read_only, net.ifnames=, net.naming_scheme=

Parameters understood by the device event managing daemon. For details, see systemd-udevd.service(8). Added in version 186.

plymouth.enable=

May be used to disable the Plymouth boot splash. For details, see plymouth(8). Added in version 186.

luks=, rd.luks=, luks.crypttab=, rd.luks.crypttab=, luks.name=, rd.luks.name=, luks.uuid=, rd.luks.uuid=, luks.options=, rd.luks.options=, luks.key=, rd.luks.key=

Configures the LUKS full-disk encryption logic at boot. For details, see systemd-cryptsetup-generator(8). Added in version 186.

fstab=, rd.fstab=

Configures the /etc/fstab logic at boot. For details, see systemd-fstab-generator(8). Added in version 186.

root=, rootfstype=, rootflags=, ro, rw

Configures the root file system and its file system type and mount options, as well as whether it shall be mounted read-only or read-write initially. For details, see systemd-fstab-generator(8). If root= is not set (or set to "gpt-auto") the automatic root partition discovery implemented by systemd-gpt-auto-generator(8) will be in effect. In this case, rootfstype=, rootflags=, ro, rw will be interpreted by systemd-gpt-auto-generator.

Added in version 215.

mount.usr=, mount.usrfstype=, mount.usrflags=

Configures the /usr file system (if required) and its file system type and mount options. For details, see systemd-fstab-generator(8). Added in version 235.

veritytab=, rd.veritytab=, roothash=, systemd.verity=, rd.systemd.verity=, systemd.verity_root_data=, systemd.verity_root_hash=, systemd.verity_root_options=, usrhash=, systemd.verity_usr_data=, systemd.verity_usr_hash=, systemd.verity_usr_options=

Configures the integrity protection root hash for the root and /usr file systems, and other related parameters. For details, see systemd-veritysetup-generator(8). Added in version 233.

systemd.getty_auto=

Configures whether the serial-getty@.service will run. For details, see systemd-getty-generator(8). Added in version 250.

systemd.gpt_auto=, rd.systemd.gpt_auto=

Configures whether GPT-based partition auto-discovery shall be attempted. For details, see systemd-gpt-auto-generator(8). Added in version 215.

systemd.image_policy=

When GPT-based partition auto-discovery is used, configures the image dissection policy string to apply, as per systemd.image-policy(7). For details see systemd-gpt-auto-generator(8). Added in version 254.

systemd.image_filter=

When GPT-based partition auto-discovery is used, configures the image dissection filter string to apply, as per systemd.image-filter(7). For details see systemd-gpt-auto-generator(8). Added in version 258.

systemd.default_timeout_start_sec=

Overrides the default start job timeout DefaultTimeoutStartSec= at boot. For details, see systemd-system.conf(5). Added in version 230.

systemd.default_device_timeout_sec=

Overrides the default device timeout DefaultDeviceTimeoutSec= at boot. For details, see systemd-system.conf(5). Added in version 254.

systemd.watchdog_device=

Overrides the watchdog device path WatchdogDevice=. For details, see systemd-system.conf(5). Added in version 236.

systemd.watchdog_sec=

Overrides the watchdog timeout settings otherwise configured with RuntimeWatchdog=, RebootWatchdog= and KExecWatchdogSec=. Takes a time value (if no unit is specified, seconds is the implicitly assumed time unit) or the special strings "off" or "default". For details, see systemd-system.conf(5). Added in version 250.

systemd.watchdog_pre_sec=

Overrides the watchdog pre-timeout settings otherwise configured with RuntimeWatchdogPreSec=. Takes a time value (if no unit is specified, seconds is the implicitly assumed time unit) or the special strings "off" or "default". For details, see systemd-system.conf(5). Added in version 251.

systemd.watchdog_pretimeout_governor=

Overrides the watchdog pre-timeout settings otherwise configured with RuntimeWatchdogPreGovernor=. Takes a string value. For details, see systemd-system.conf(5). Added in version 251.

systemd.cpu_affinity=

Overrides the CPU affinity mask for the service manager and the default for all child processes it forks. This takes precedence over CPUAffinity=, see systemd-system.conf(5) for details. Added in version 245.

modules_load=, rd.modules_load=

Load a specific kernel module early at boot. For details, see systemd-modules-load.service(8). Added in version 187.

nameserver=, domain=

Configures DNS server information and search domains, see systemd-resolved.service(8) for details. Added in version 253.

resume=, resumeflags=

Enable resume from hibernation using the specified device and timeout options. All fstab(5)-style device identifiers are supported. For details, see systemd-hibernate-resume-generator(8). Added in version 217.

resume_offset=

Configure the page offset of the swap space from the resume device. For details, see systemd-hibernate-resume-generator(8). Added in version 254.

systemd.firstboot=

Takes a boolean argument, defaults to on. If off, systemd-firstboot.service(8) and systemd-homed-firstboot.service(1) will not query the user for basic system settings, even if the system boots up for the first time and the relevant settings are not initialized yet. Not to be confused with systemd.condition_first_boot= (see below), which overrides the result of the ConditionFirstBoot= unit file condition, and thus controls more than just systemd-firstboot.service behaviour. Added in version 233.

systemd.condition_needs_update=

Takes a boolean argument. If specified, overrides the result of ConditionNeedsUpdate= unit condition checks. See systemd.unit(5) for details. Added in version 246.

systemd.condition_first_boot=

Takes a boolean argument. If specified, overrides the result of ConditionFirstBoot= unit condition checks. See systemd.unit(5) for details. Not to be confused with systemd.firstboot= which only controls behaviour of the systemd-firstboot.service system service but has no effect on the condition check (see above). Added in version 246.

systemd.clock_usec=

Takes a decimal, numeric timestamp in μs since January 1st 1970, 00:00am, to set the system clock to. The system time is set to the specified timestamp early during boot. It is not propagated to the hardware clock (RTC). Added in version 246.

systemd.random_seed=

Takes a base64 encoded random seed value to credit with full entropy to the kernel's random pool during early service manager initialization. This option is useful in testing environments where delays due to random pool initialization in entropy starved virtual machines shall be avoided. Note that if this option is used the seed is accessible to unprivileged programs from /proc/cmdline. This option is hence a security risk when used outside of test systems, since the (possibly) only seed used for initialization of the kernel's entropy pool might be easily acquired by unprivileged programs.

It is recommended to pass 512 bytes of randomized data (as that matches the Linux kernel pool size), which may be generated with a command like the following:

```
dd if=/dev/urandom bs=512 count=1 status=none | base64 -w 0
```

Again: do not use this option outside of testing environments, it is a security risk elsewhere, as secret key material derived from the entropy pool can possibly be reconstructed by unprivileged programs.

Added in version 246.

systemd.allow_userspace_verity=

Takes a boolean argument. Controls whether disk images that are Verity protected may be authenticated in userspace signature checks via /etc/verity.d/*.crt (and related directories) public key drop-ins, or whether in-kernel signature checking only. Defaults to on. Added in version 256.

systemd.hostname=

Accepts a hostname to set during early boot. If specified takes precedence over what is set in /etc/hostname. Note that this does not bar later runtime changes to the hostname, it simply controls the initial hostname set during early boot. Added in version 246.

systemd.tty.term.tty=, systemd.tty.rows.tty=, systemd.tty.columns.tty=

These arguments allow configuring default values for $TERM, TTYRows=, and TTYColumns= for tty tty. Additionally, systemd.tty.term.console will configure the $TERM value used by systemd if not set explicitly using TERM on the kernel command line. The tty name should be specified without the /dev/ prefix (e.g. "systemd.tty.rows.ttyS0=80"). Added in version 254.

systemd.battery_check=

Accepts a boolean argument. If false the boot-time battery charge check implemented by systemd-battery-check.service(8) is disabled. Added in version 254.

ifname=, net.ifname_policy=

Controls interface naming policies, implemented by systemd-network-generator.service(8). Added in version 245.

systemd.tpm2_allow_clear=

Controls whether to allow clearing of the TPM chip, implemented by systemd-tpm2-clear.service(8). Added in version 258.

systemd.tpm2_wait=

Controls whether to wait for a TPM2 device at boot, implemented by systemd-tpm2-generator(8). Added in version 256.

systemd.factory_reset=

Controls whether to to boot into factory reset mode, implemented by systemd-factory-reset-generator(8), systemd-repart(8), and other tools. Added in version 258.

## HISTORY
systemd 252

Kernel command-line arguments systemd.unified_cgroup_hierarchy and systemd.legacy_systemd_cgroup_controller were deprecated. Please switch to the unified cgroup hierarchy.

## SEE ALSO
systemd(1), systemd-system.conf(5), bootparam(7), systemd.system-credentials(7), smbios-type-11(7), systemd-debug-generator(8), systemd-fsck@.service(8), systemd-quotacheck@.service(8), systemd-journald.service(8), systemd-vconsole-setup.service(8), systemd-udevd.service(8), plymouth(8), systemd-cryptsetup-generator(8), systemd-veritysetup-generator(8), systemd-fstab-generator(8), systemd-getty-generator(8), systemd-gpt-auto-generator(8), systemd-volatile-root.service(8), systemd-modules-load.service(8), systemd-backlight@.service(8), systemd-rfkill.service(8), systemd-hibernate-resume-generator(8), systemd-firstboot.service(8), bootctl(1)

## NOTES
1.

kernel-parameters.html

https://docs.kernel.org/admin-guide/kernel-parameters.html


title: smbios-type-11(7)

summary: SMBIOS Type 11 strings

text:
# smbios-type-11(7)

## NAME
smbios-type-11 - SMBIOS Type 11 strings

## SYNOPSIS
/sys/firmware/dmi/entries/11-*/raw

## DESCRIPTION
Various OS components process SMBIOS Type 11 vendor strings that a virtual machine manager (VMM) may set and a virtual machine (VM) receives. SMBIOS Type 11 vendor strings may play a similar role as kernel-command-line(7) parameters but generally are under control of the VMM rather than the boot loader or UKI.

For details on SMBIOS Type 11 see the System Management BIOS[1] specifications.

## STRINGS
The following strings are supported:

io.systemd.credential:CREDENTIAL=VALUE, io.systemd.credential.binary:CREDENTIAL=VALUE

This allows passing additional system credentials into the system, in textual or binary (Base64) form. See systemd.exec(5) and System and Service Credentials[2] for details. Added in version 252.

io.systemd.stub.kernel-cmdline-extra=CMDLINE

This allows configuration of additional kernel command line options, and is read by the kernel UEFI stub. For details see systemd-stub(7). Added in version 254.

io.systemd.boot.kernel-cmdline-extra=CMDLINE

This allows configuration of additional kernel command line options for Boot Loader Specification Type 1 entries, and is read by systemd-boot. For details see systemd-boot(7). Added in version 256.

io.systemd.boot-entries.extra:ID=DEFINITION

This allows inserting additional entries into the systemd-boot menu. For details see systemd-boot(7) Added in version 258.

## SEE ALSO
systemd(1), kernel-command-line(7), systemd.system-credentials(7)

## NOTES
1.

System Management BIOS

https://www.dmtf.org/standards/smbios/

2.

System and Service Credentials

https://systemd.io/CREDENTIALS


systemd-stub

title: systemd-stub(7)

summary: A simple UEFI kernel boot stub

text:
# systemd-stub(7)

## NAME
systemd-stub, sd-stub, linuxx64.efi.stub, linuxia32.efi.stub, linuxaa64.efi.stub - A simple UEFI kernel boot stub

## SYNOPSIS
/usr/lib/systemd/boot/efi/linuxx64.efi.stub

/usr/lib/systemd/boot/efi/linuxia32.efi.stub

/usr/lib/systemd/boot/efi/linuxaa64.efi.stub

ESP/.../foo.efi.extra.d/*.addon.efi

ESP/.../foo.efi.extra.d/*.cred

ESP/.../foo.efi.extra.d/*.raw

ESP/.../foo.efi.extra.d/*.sysext.raw

ESP/.../foo.efi.extra.d/*.confext.raw

ESP/loader/addons/*.addon.efi

ESP/loader/credentials/*.cred

ESP/loader/extensions/*.raw

ESP/loader/extensions/*.sysext.raw

ESP/loader/extensions/*.confext.raw

## DESCRIPTION
systemd-stub (stored in per-architecture files linuxx64.efi.stub, linuxia32.efi.stub, linuxaa64.efi.stub on disk) is a simple UEFI boot stub. An UEFI boot stub is attached to a Linux kernel binary image, and is a piece of code that runs in the UEFI firmware environment before transitioning into the Linux kernel environment. The UEFI boot stub ensures a Linux kernel is executable as regular UEFI binary, and is able to do various preparations before switching the system into the Linux world.

The UEFI boot stub looks for various resources for the kernel invocation inside the UEFI PE binary itself. This allows combining various resources inside a single PE binary image (a "Unified Kernel Image" or "UKI" for short), which may then be signed via UEFI SecureBoot as a whole, covering all individual resources at once. Specifically it may include the following PE sections:

•A ".linux" section with the ELF Linux kernel image. This section is required.

•An optional ".osrel" section with OS release information, i.e. the contents of the os-release(5) file of the OS the kernel belongs to.

•An optional ".cmdline" section with the kernel command line to pass to the invoked kernel.

•An optional ".initrd" section with the initrd.

•An optional ".ucode" section with an initrd containing microcode, to be handed to the kernel before any other initrd. This initrd must not be compressed.

•An optional ".splash" section with an image (in the Windows .BMP format) to show on screen before invoking the kernel.

•An optional ".dtb" section with a compiled binary DeviceTree.

•Zero or more ".dtbauto" sections. systemd-stub will always use the first matching one. The match is performed by taking the first DeviceTree's "compatible" string supplied by the firmware in configuration tables and comparing it with the first "compatible" string from each of the ".dtbauto" sections. If the firmware does not provide a DeviceTree, the match is done using the ".hwids" section instead. After selecting the matching entry in the ".hwids" section (see the description below), the "compatible" string from that entry will be used to perform the same matching procedure. If a match is found, that ".dtbauto" section will be loaded and will override ".dtb" if present.

•Zero or more ".efifw" sections for the firmware image. It works in many ways similar to ".dtbauto" sections. systemd-stub will always use the first matching one. The match is performed by first selecting the most appropriate entry in the ".hwids" section based on the hardware IDs supplied by SMBIOS (see below). If a suitable entry is found, the "fwid" string from that entry will be used to perform the matching procedure for firmware blobs in ".efifw" section. The first matching firmware will be loaded.

•An optional ".hwids" section with hardware IDs of the machines to match DeviceTrees. systemd-stub will use the SMBIOS data to calculate hardware IDs of the machine (as per specification[1]), and then it will try to find any of them in the ".hwids" section. The first matching entry will be used.

•An optional ".uname" section with the kernel version information, i.e. the output of uname -r for the kernel included in the ".linux" section.

•An optional ".sbat" section with SBAT[2] revocation metadata.

•An optional ".pcrsig" section with a set of cryptographic signatures for the expected TPM2 PCR values after the kernel has been booted, in JSON format. This is useful for implementing TPM2 policies that bind disk encryption and similar to kernels that are signed by a specific key.

•An optional ".pcrpkey" section with a public key in the PEM format matching the signature data in the ".pcrsig" section.

In a basic UKI, the sections listed above appear at most once, with the exception of ".dtbauto" and ".efifw" sections. In a multi-profile UKI, multiple sets of these sections are present in a single file and form "profiles", one of which can be selected at boot. For this, the PE section ".profile" is defined to be used as the separator between sets of sections. The ".profile" section itself may contain meta-information about the section, and follows a similar structure as the contents of the ".osrel" section. For further details about multi-profile UKIs, see below.

If UEFI SecureBoot is enabled and the ".cmdline" section is present in the executed image, any attempts to override the kernel command line by passing one as invocation parameters to the EFI binary are ignored. Thus, in order to allow overriding the kernel command line, either disable UEFI SecureBoot, or do not include a kernel command line PE section in the kernel image file. If a command line is accepted via EFI invocation parameters to the EFI binary it is measured into TPM PCR 12 (if a TPM is present).

If a DeviceTree is embedded in the ".dtb" section, it replaces an existing DeviceTree in the corresponding EFI configuration table. systemd-stub will ask the firmware via the "EFI_DT_FIXUP_PROTOCOL" for hardware specific fixups to the DeviceTree.

The contents of 11 of these 12 sections are measured into TPM PCR 11. It is otherwise not used and thus the result can be pre-calculated without too much effort. The ".pcrsig" section is not included in this PCR measurement, since it is supposed to contain signatures for the output of the measurement operation, and thus cannot also be input to it. If an UKI contains multiple profiles, only the PE sections of the selected profile (and those of the base profile, except if overridden) are measured.

If non-zero, the selected numeric profile is measured into PCR 12.

When ".pcrsig" and/or ".pcrpkey" sections are present in a unified kernel image their contents are passed to the booted kernel in an synthetic initrd cpio archive that places them in the /.extra/tpm2-pcr-signature.json and /.extra/tpm2-pcr-public-key.pem files. Typically, a tmpfiles.d(5) line then ensures they are copied into /run/systemd/tpm2-pcr-signature.json and /run/systemd/tpm2-pcr-public-key.pem where they remain accessible even after the system transitions out of the initrd environment into the host file system. Tools such systemd-cryptsetup@.service(8), systemd-cryptenroll(1) and systemd-creds(1) will automatically use files present under these paths to unlock protected resources (encrypted storage or credentials) or bind encryption to booted kernels.

For further details about the UKI concept, see the UKI specification[3].

## COMPANION FILES
The systemd-stub UEFI boot stub automatically collects three types of auxiliary companion files optionally placed in drop-in directories on the same partition as the EFI binary, dynamically generates cpio initrd archives from them, and passes them to the kernel. Specifically:

•For a kernel binary called foo.efi, it will look for files with the .cred suffix in a directory named foo.efi.extra.d/ next to it. If the kernel binary uses a counter for the purpose of Automatic Boot Assessment[4], this counter will be ignored. For example, foo+3-0.efi will look in directory foo.efi.extra.d/. A cpio archive is generated from all files found that way, placing them in the /.extra/credentials/ directory of the initrd file hierarchy. The main initrd may then access them in this directory. This is supposed to be used to store auxiliary, encrypted, authenticated credentials for use with LoadCredentialEncrypted in the UEFI System Partition. See systemd.exec(5) and systemd-creds(1) for details on encrypted credentials. The generated cpio archive is measured into TPM PCR 12 (if a TPM is present).

•Similarly, files foo.efi.extra.d/*.sysext.raw are packed up in a cpio archive and placed in the /.extra/sysext/ directory in the initrd file hierarchy. This is supposed to be used to pass additional UKI-specific system extension images to the initrd. See systemd-sysext(8) for details on system extension images. The generated cpio archive containing these system extension images is measured into TPM PCR 13 (if a TPM is present).

•Similarly, files /loader/extensions/*.sysext.raw are packed up in a cpio archive and placed in the /.extra/global_sysext/ directory in the initrd file hierarchy. This is supposed to be used to pass additional global system extension images to the initrd. See systemd-sysext(8) for details on system extension images. The generated cpio archive containing these system extension images is measured into TPM PCR 13 (if a TPM is present).

•Similarly, files foo.efi.extra.d/*.confext.raw are packed up in a cpio archive and placed in the /.extra/confext/ directory in the initrd file hierarchy. This is supposed to be used to pass additional UKI-specific configuration extension images to the initrd. See systemd-confext(8) for details on configuration extension images. The generated cpio archive containing these configuration extension images is measured into TPM PCR 12 (if a TPM is present).

•Similarly, files /loader/extensions/*.confext.raw are packed up in a cpio archive and placed in the /.extra/global_confext/ directory in the initrd file hierarchy. This is supposed to be used to pass additional global configuration extension images to the initrd. See systemd-confext(8) for details on configuration extension images. The generated cpio archive containing these configuration extension images is measured into TPM PCR 12 (if a TPM is present).

•Similarly, files foo.efi.extra.d/*.addon.efi are loaded and verified as PE binaries and specific sections are loaded from them. Addons are used to pass additional kernel command line parameters (".cmdline" section), or DeviceTree blobs (".dtb" section), additional initrds (".initrd" section), and microcode updates (".ucode" section). Addons allow those resources to be passed regardless of the kernel version being booted, for example allowing platform vendors to ship platform-specific configuration. In case Secure Boot is enabled, these files will be validated using keys in UEFI DB, Shim's DB or Shim's MOK, and only loaded if the check passes. Additionally, if both the addon and the UKI contain a ".uname" section, the addon will be rejected if they do not match exactly. It is recommended to always add a ".sbat" section to all signed addons, so that they may be revoked with a SBAT policy update, without requiring blocklisting via DBX/MOKX. The ukify(1) tool will add a SBAT policy by default if none is passed when building addons. For more information on SBAT see Shim documentation[2].

Addon files are sorted, loaded, and measured into TPM PCR 12 (if a TPM is present) and appended to the kernel command line. UKI command line options are listed first, then options from addons in /loader/addons/*.addon.efi, and finally UKI-specific addons. Device tree blobs are loaded and measured following the same algorithm. Microcode addons are passed to the kernel in inverse order (UKI specific addons, global addons, UKI embedded section). This is because the microcode update driver stops on the first matching filename. Addons are always loaded in the same order based on the filename, so that, given the same set of addons, the same set of measurements can be expected in PCR12. However, note that the filename is not protected by the PE signature, and as such an attacker with write access to the ESP could potentially rename these files to change the order in which they are loaded, in a way that could alter the functionality of the kernel, as some options might be order-dependent. If you sign such addons, you should pay attention to the PCR12 values and make use of an attestation service so that improper use of your signed addons can be detected and dealt with using one of the aforementioned revocation mechanisms.

•Files /loader/credentials/*.cred are packed up in a cpio archive and placed in the /.extra/global_credentials/ directory of the initrd file hierarchy. This is supposed to be used to pass additional credentials to the initrd, regardless of the kernel version being booted. The generated cpio archive is measured into TPM PCR 12 (if a TPM is present).

•Additionally, files /loader/addons/*.addon.efi are loaded and verified as PE binaries, and ".cmdline", ".dtb", ".initrd", and ".ucode" sections are parsed from them. This is supposed to be used to pass additional command line parameters, DeviceTree blobs, initrds, and microcode updates to the kernel, regardless of the kernel version being booted.

These mechanisms may be used to parameterize and extend trusted (i.e. signed), immutable initrd images in a reasonably safe way: all data they contain is measured into TPM PCRs. On access they should be further validated: in case of the credentials case by encrypting/authenticating them via TPM, as exposed by systemd-creds encrypt -T (see systemd-creds(1) for details); in case of the system extension images by using signed Verity images.

## MULTI-PROFILE UKIS
In many contexts it is useful to allow invocation of a single UKI in multiple different modes (or "profiles") without compromising the cryptographic integrity, measurements and so on of the boot process. For example, a single UKI might provide three distinct profiles: a regular boot one, one that invokes a "factory reset" operation, and one that boots into a storage target mode (as in systemd-storagetm.service(8)). Each profile would then use the same ".linux" and ".initrd" sections, but would have a separate ".cmdline" section. For example the latter two profiles would extend the regular kernel command line with "systemd.unit=factory-reset.target" or "rd.systemd.unit=storagetm.target".

A single UKI may support multiple profiles by means of the special ".profile" PE section. This section acts as separator between the PE sections of the individual profiles. ".profile" PE sections hence may appear multiple times in a single UKI, and the other PE sections listed above may appear multiple times too, if ".profile" are used, but only once before the first ".profile" section, once between each subsequent pair, and once after the last appearance of ".profile". The sections listed before the first ".profile" are considered the "base" profile of the UKI. Each ".profile" section then introduces a new profile, which are numbered starting from zero. The PE sections following each ".profile" are specific to that profile. When booting into a specific profile, the base section's profiles are used in combination with the specific profile's sections: if the same section is defined in both, the per-profile section overrides the base profile's version, otherwise the base profile sections are used.

A UKI that contains no ".profile" is consider equivalent to one that just contains a single ".profile", as having only a single profile "@0".

Here's a simple example for a multi-profile UKI's sections, inspired by the setup suggested above:

Table 1. Multi-Profile UKI Example

Section

Profile

".linux"

Base profile

".osrel"

".cmdline"

".initrd"

".profile"

Profile @0

".profile"

Profile @1

".cmdline"

".profile"

Profile @2

".cmdline"

The section list above would define three profiles. The first four sections make up the base profile. A

".profile" section then introduces profile @0. It does not override any sections (or add any) from the base section, hence it is immediately followed by another ".profile" section that then introduces section @1. This profile overrides the kernel command line. Finally, the last two sections define section @2, again overriding the command line. (Note that in this example the first ".cmdline" could also moved behind the first ".profile" with equivalent effect. To keep things nicely extensible, it is probably a good idea to keep the generic command line in the base section instead of profile 0, in case later added profiles might want to reuse it.)

The profile to boot may be controlled via the UKI's own command line: if the first argument starts with "@", followed by a positive integer number in decimal, it selects the profile to boot into. If the first argument is not specified like that, the UKI will automatically boot into profile 0.

A ".profile" section may contain meta-information about the profile. It follows a similar format as ".osrel" (i.e. an environment-variable-assignment-block-like list of newline separated strings). Currently two fields are defined: "ID=" is supposed to carry a short identifying string that identifies the profile (e.g. "ID=factory-reset"). "TITLE=" should contain a human-readable string that may appear in the boot menu entry for this profile (e.g. "TITLE='Factory Reset this Device'").

## TPM PCR NOTES
Note that when a unified kernel using systemd-stub is invoked the firmware will measure it as a whole to TPM PCR 4, covering all embedded resources, such as the stub code itself, the core kernel, the embedded initrd and kernel command line (see above for a full list), including all UKI profiles.

Also note that when systemd-stub measures a PE section, it will measure the amount of bytes that the section takes up in memory (VirtualSize) and not the amount of bytes that the section takes up on disk (SizeOfRawData). This means that if the size in memory is larger than the size on disk, systemd-stub will end up measuring extra zeroes. To avoid this from happening, it is recommended to make sure that the size in memory of each section that is measured by systemd-stub is always smaller than or equal to the size on disk. ukify automatically makes sure this is the case when building UKIs or addons.

Also note that the Linux kernel will measure all initrds it receives into TPM PCR 9. This means every type of initrd (of the selected UKI profile) will possibly be measured two or three times: the initrds embedded in the kernel image will be measured to PCR 4, PCR 9 and PCR 11; the initrd synthesized from credentials (and the one synthesized from configuration extensions) will be measured to both PCR 9 and PCR 12; the initrd synthesized from system extensions will be measured to both PCR 4 and PCR 9. Let's summarize the OS resources and the PCRs they are measured to:

Table 2. OS Resource PCR Summary

OS Resource

Measurement PCR

systemd-stub code (the entry point of the unified PE binary)

4

Core kernel code (embedded in unified PE binary)

4 + 11

OS release information (embedded in the unified PE binary)

4 + 11

Main initrd (embedded in unified PE binary)

4 + 9 + 11

Microcode initrd (embedded in unified PE binary)

4 + 9 + 11

Default kernel command line (embedded in unified PE binary)

4 + 11

Overridden kernel command line

12

Boot splash (embedded in the unified PE binary)

4 + 11

TPM2 PCR signature JSON (embedded in unified PE binary, synthesized into initrd)

4 + 9

TPM2 PCR PEM public key (embedded in unified PE binary, synthesized into initrd)

4 + 9 + 11

Credentials (synthesized initrd from companion files)

9 + 12

System Extensions (synthesized initrd from companion files)

9 + 13

Configuration Extensions (synthesized initrd from companion files)

9 + 12

Selected profile unless zero

12

## EFI VARIABLES
The following EFI variables are defined, set and read by

systemd-stub, under the vendor UUID "4a67b082-0a4c-41cf-b6c7-440b29bb8c4f", for communication between the boot stub and the OS:

LoaderDevicePartUUID

Contains the partition UUID of the partition the boot loader has been started from on the current boot (usually a EFI System Partition). If already set by the boot loader, this will remain untouched by systemd-stub. If not set yet, this will be set to the partition UUID of the partition the unified kernel is started from, in order to support systems that directly boot into a unified kernel image, bypassing any boot loader. systemd-gpt-auto-generator(8) uses this information to automatically find the disk booted from, in order to discover various other partitions on the same disk automatically. Added in version 224.

LoaderFirmwareInfo, LoaderFirmwareType

Brief firmware information. Use bootctl(1) to view this data. Added in version 250.

LoaderTpm2ActivePcrBanks

Hexadecimal string representation of a bitmask with values defined by the TCG EFI Protocol Specification for TPM 2.0 as EFI_TCG2_BOOT_HASH_ALG_*. If no TPM2 support or no active banks were detected, will be set to 0. Set by the boot loader. Use systemd-analyze(1) to view this data. Added in version 258.

LoaderImageIdentifier

The file system path to the EFI executable of the boot loader for the current boot, relative to the partition's root directory (i.e. relative to the partition indicated by LoaderDevicePartUUID, see above). If not set yet, this will be set to the file system path of the EFI executable of the booted unified kernel, in order to support systems that directly boot into a unified kernel image, bypassing any boot loader. Use bootctl(1) to view this data. Added in version 237.

StubDevicePartUUID, StubImageIdentifier

Similar to LoaderDevicePartUUID and LoaderImageIdentifier, but indicates the location of the unified kernel image EFI binary rather than the location of the boot loader binary, regardless of whether booted via a boot loader or not. Added in version 257.

StubDeviceURL

If the kernel image has been invoked via network booting this variable contains the originating URL. This may be used to automatically acquire additional resources from the same source. Added in version 258.

StubInfo

Brief stub information. Use bootctl(1) to view this data. Added in version 250.

StubPcrKernelImage

The PCR register index the kernel image, initrd image, boot splash, devicetree database, and the embedded command line are measured into, formatted as decimal ASCII string (e.g. "11"). This variable is set if a measurement was successfully completed, and remains unset otherwise. Added in version 252.

StubPcrKernelParameters

The PCR register index the kernel command line and credentials are measured into, formatted as decimal ASCII string (e.g. "12"). This variable is set if a measurement was successfully completed, and remains unset otherwise. Added in version 252.

StubPcrInitRDSysExts

The PCR register index the system extensions for the initrd, which are picked up from the file system the kernel image is located on. Formatted as decimal ASCII string (e.g. "13"). This variable is set if a measurement was successfully completed, and remains unset otherwise. Added in version 252.

StubPcrInitRDConfExts

The PCR register index the configuration extensions for the initrd, which are picked up from the file system the kernel image is located on. Formatted as decimal ASCII string (e.g. "12"). This variable is set if a measurement was successfully completed, and remains unset otherwise. Added in version 255.

StubProfile

The numeric index of the selected profile, without the "@", formatted as decimal string. Set both on single-profile and multi-profile UKIs. (In the former case this variable will be set to "0" unconditionally.) Added in version 257.

Note that some of the variables above may also be set by the boot loader. The stub will only set them if they are not set already. Some of these variables are defined by the Boot Loader Interface[5].

## INITRD RESOURCES
The following resources are passed as initrd cpio archives to the booted kernel, and thus make up the initial file system hierarchy in the initrd execution environment:

/

The main initrd from the ".initrd" PE section of the unified kernel image. Added in version 252.

/.extra/credentials/*.cred

Credential files (suffix ".cred") that are placed next to the unified kernel image (as described above) are copied into the /.extra/credentials/ directory in the initrd execution environment. Added in version 252.

/.extra/global_credentials/*.cred

Similarly, credential files in the /loader/credentials/ directory in the file system the unified kernel image is placed in are copied into the /.extra/global_credentials/ directory in the initrd execution environment. Added in version 252.

/.extra/sysext/*.sysext.raw

System extension image files (suffix ".sysext.raw") that are placed next to the unified kernel image (as described above) are copied into the /.extra/sysext/ directory in the initrd execution environment. Added in version 252.

/.extra/global_sysext/*.sysext.raw

Similarly, system extension image files (suffix ".sysext.raw") that are placed in the /loader/extensions/ directory in the file system the unified kernel image is placed in are copied into the /.extra/global_sysext/ directory in the initrd execution environment. Added in version 258.

/.extra/confext/*.confext.raw

Configuration extension image files (suffix ".confext.raw") that are placed next to the unified kernel image (as described above) are copied into the /.extra/confext/ directory in the initrd execution environment. Added in version 255.

/.extra/global_confext/*.confext.raw

Similarly, configuration extension image files (suffix ".confext.raw") that are placed in the /loader/extensions/ directory in the file system the unified kernel image is placed in are copied into the /.extra/global_confext/ directory in the initrd execution environment. Added in version 258.

/.extra/tpm2-pcr-signature.json

The TPM2 PCR signature JSON object included in the ".pcrsig" PE section of the unified kernel image is copied into the /.extra/tpm2-pcr-signature.json file in the initrd execution environment. Added in version 252.

/.extra/tpm2-pcr-public-key.pem

The PEM public key included in the ".pcrpkey" PE section of the unified kernel image is copied into the /.extra/tpm2-pcr-public-key.pem file in the initrd execution environment. Added in version 252.

/.extra/profile, /.extra/os-release

The contents of the ".profile" and ".osrel" sections of the selected profile, if any. Added in version 257.

Note that all these files are located in the "tmpfs" file system the kernel sets up for the initrd file hierarchy and are thus lost when the system transitions from the initrd execution environment into the host file system. If these resources shall be kept around over this transition they need to be copied to a place that survives the transition first, for example via a suitable tmpfiles.d(5) line. By default, this is done for the TPM2 PCR signature and public key files.

## SMBIOS TYPE 11 STRINGS
systemd-stub can be configured using SMBIOS Type 11 strings. Applicable strings consist of a name, followed by "=", followed by the value. Unless systemd-stub detects it is running inside a confidential computing environment, systemd-stub will search the table for a string with a specific name, and if found, use its value. The following strings are read:

io.systemd.stub.kernel-cmdline-extra

If set, the value of this string is added to the list of kernel command line arguments that are measured in PCR12 and passed to the kernel. Added in version 254.

## ASSEMBLING KERNEL IMAGES
In order to assemble a bootable Unified Kernel Image from various components as described above, use ukify(1).

## SEE ALSO
systemd-boot(7), systemd.exec(5), systemd-creds(1), systemd-sysext(8), Boot Loader Specification[6], Boot Loader Interface[5], ukify(1), systemd-measure(1), TPM2 PCR Measurements Made by systemd[7]

## NOTES
1.

specification

https://learn.microsoft.com/en-us/windows-hardware/drivers/install/specifying-hardware-ids-for-a-computer

2.

SBAT

https://github.com/rhboot/shim/blob/main/SBAT.md

3.

UKI specification

https://uapi-group.org/specifications/specs/unified_kernel_image/

4.

Automatic Boot Assessment

https://systemd.io/AUTOMATIC_BOOT_ASSESSMENT

5.

Boot Loader Interface

https://systemd.io/BOOT_LOADER_INTERFACE

6.

Boot Loader Specification

https://uapi-group.org/specifications/specs/boot_loader_specification

7.

TPM2 PCR Measurements Made by systemd

https://systemd.io/TPM2_PCR_MEASUREMENTS