User:Sakaki/Sakaki's EFI Install Guide/Installing the Gentoo Stage 3 Files

Our main goals in this section, which shadows Chapter 5 of the Gentoo handbook, will be to download and unpack the Gentoo 'stage 3' tarball, and to set up Portage's main configuration file.

We'll also present a brief backgrounder covering some key Portage topics, which may be skipped if desired.

Double-Checking the Date and Time
Before downloading anything, double-check that you have the correct time and date on the target machine (you should do, as you set it up earlier, but since having an incorrect date can cause problems later, it is best to make sure now). Check it with:

Per the handbook, you should stick with UTC for now (the real timezone specification will come later in the install). If necessary, set the date and time, in MMDDhhmmYYYY format (Month, Day, hour, minute, year):

Downloading, Verifying and Unpacking the Gentoo Stage 3 Tarball
The 'Stage 3' file is a tarball containing a populated directory structure from a basic Gentoo system. Unlike the minimal installation image however, the stage 3 system contains no kernel, only binaries and libraries essential to bootstrapping. As such, we will have to host it within a chroot from our existing (minimal install image) system, until we have recompiled all system files and libraries, built a fresh kernel, and the new system becomes self-hosting.

The stage 3 tarball is generally released on the same date as the minimal install image, and may be found (together with the usual contents and digest files) in the same autobuilds directory. As the amount of data involved here is small, pace the handbook we'll skip using the slightly awkward browser / mirror selection process at this stage, and just grab the files directly with.

Change to the Gentoo filesystem root mountpoint:

Now download the files. As before, substitute for YYYYMMDDThhmmssZ in the below with the current release file timestamp (open the link http://distfiles.gentoo.org/releases/amd64/autobuilds/latest-stage3-amd64.txt in a browser to determine the current name).

As before (when we downloaded the minimal install image), we have to go through a two-stage verification: first check the signature in the file, and then check the digests in that file themselves. As this is the target machine (not the helper), we don't yet have the necessary Gentoo automated weekly release public key, whose fingerprint may be found on the Gentoo release engineering page. So let's fetch it now. Issue:

You should next verify that the key's full fingerprint matches that listed on the Release Engineering page:

If all looks good, verify the digest file:

And assuming that worked (output reports 'Good signature'), next check the digests themselves; we'll use the SHA512 variants here:

If this outputs:

then continue.

The last step in this stage is to unpack the tarball. Double check you are in the directory, then issue:

As per the handbook, the options to are to extract, provide verbose output, decompress with xz (J), preserve permissions and extract from a file, not standard input. Further, the  option ensures that extended attributes stored in the tarball are also copied (from all namespaces), and the  option uses the numeric owner and group IDs from the tarball, even if they are different in the host system (they will not be here, since we are booted from an official minimal install image, but it doesn't hurt to specify this).

Check that the base system has unpacked OK:

If you see a file structure similar to the above, then you can proceed. As we no longer need the stage files, they can be deleted now to save space:

This structure looks, as it should, a lot like a normal Linux root directory, but it is positioned at. Later, we'll in a few additional special directories from our running (minimal) system, and then  into this new base to continue with the installation.

Lastly, return back to root's home:

Before we continue, we'll take a brief detour to discuss some essential Gentoo / Portage background information and terminology. If you are an old hand with this, feel free to skip this material.

Gentoo, Portage, Ebuilds and (Background Reading)
Gentoo is a source-based distribution, the heart of which is a powerful package manager called Portage. Portage itself has two main components:
 * the ebuild system, which performs the actual work of fetching, configuring, building and installing packages, and
 * the Emerge tool, which provides a command line interface to invoke ebuilds, and also allows you to update the Portage tree (discussed below), resolve package dependencies, and other related tasks.

Package ebuilds are Bash shell scripts, or more accurately shell script fragments, that are sourced into a larger build system 'host' script. This host script provides a package management control flow that invokes a set of default 'hook' functions, which a particular package's ebuild may override if it needs to (these are covered in detail in the Gentoo Development Guide). The ebuild also must define a minimum set of variables to allow the whole process to operate successfully (for example, the URI from where a package's source tarball may be downloaded must be assigned to the variable).

Now, when you invoke an ebuild to install a particular (as yet uninstalled) package on your system (via, for example, as described below), it will typically carry out the following tasks (inter alia):
 * check that the specified package can be installed (that is, that it isn't masked, or has an incompatible license requirement);
 * download the package's tarball (or other format source archive) from an upstream repository (or Gentoo mirror);
 * unpack the tarball in a temporary working area;
 * patch (and otherwise modify) the unpacked source if need be;
 * configure the source to prepare it for compilation on your machine;
 * compile / build the source, as a non-privileged user in the temporary work area;
 * run tests (if provided and required);
 * install the built package to a dummy filesystem root; and
 * copy ('merge') the package installation files from the dummy filesystem root to the real filesystem root (keeping a record of what gets done).

Up until the final file copy-over step (the 'merge' in ), all operations (even where the package's is invoked, for example) take place in a temporary staging area. This enables Portage to keep track of all the files installed by a particular package, limit the damage caused by failed compiles or installs, and facilitate simple removal of installed packages. Furthermore, for most of these tasks, Portage operates in a 'sandbox' mode, where attempts to write directly to the real root filesystem (rather than the temporary work area) are detected, and cause an error to be thrown (NB this is not intended as a security system per se, but it does help prevent accidental filesystem corruption).

Portage stores ebuilds in a hierarchical folder structure - the Portage tree (or repository), which by default is located under. The first tree level is the package category, which is used to organize packages into groups which have broadly similar functionality. So, for example, non-core development utilities are typically placed in the category (in folder). The next tree level is the package name itself. To take a concrete example, the small utility (which, as its name suggests, displays a histogram of changes implied by a patch file, or other  output), is located in the folder. Within that subdirectory we have the actual per-package content, specifically:
 * The  files. Each supported version has a file of format . At the time of writing, there are two supported versions (1.60 and 1.61) of in the Portage tree, so the ebuilds are located at  and . Portage supports a complex version numbering taxonomy which, for the most part, reflects upstream versioning (discussed further below), and most packages, like, will have multiple ebuild versions available at any given time.
 * Package metadata. This is stored in an xml-format text file (one per package), named . Its contents are described here, and can contain detailed package descriptions, email addresses for upstream maintainers, documentation about USE flags etc. 's metadata file is at.
 * A manifest file, which contains digests (BLAKE2B and SHA512) and file sizes for the contents of the package directory and any referenced tarballs (and patches, if present). It is used to detect corruption and possible tampering during package download / installation. This manifest, which may optionally be digitally signed, is stored in the file; 's therefore resides at.
 * An optional files directory. This is used to hold patches and other small files that are supplementary to the main source tarball but referenced by one or more of the package's ebuilds. The directory may be absent if unused. As (at the time of writing) does not require patches, it has no  subdirectory either.

A Simple ()
So what does an file actually look like, then? happens to be a good minimal example; here (at the time of writing) is what contains:

Not a lot to see, is there? That's because uses a standard 'Autotools'-style build, without patches, so the default  control flow (and invoked 'hook' functions) can do almost everything for us. Therefore, all that has to be done is:
 * to specify (via the EAPI variable) that the makes use of the most modern package manager functionality, including built-in default behaviours (version, at the time of writing).
 * to specify a brief DESCRIPTION, HOMEPAGE (both self-explanatory) and most importantly, SRC_URI ; this last variable tells Portage the location from whence to download the package tarball, if it cannot find it in the Portage mirrors (the ${P} expands out to be the package name and version; a handy list of these special variables may be found here);
 * to specify the LICENSE (the relevant text may be found at );
 * to specify that SLOTTING is not used by this ebuild (this is an advanced feature; see below for a brief overview); and
 * finally to list the architectures ( KEYWORDS ) for which this applies. Here, we can see that (at the time of writing) it is in testing (has a tilde) for all the architectures listed (,  etc.).

That's all that is needed in this case, because the default functions will automatically pull down the tarball, unpack it, issue a , issue a  , followed by a   (to a dummy root), after which, the program file (plus manpage etc.) will be copied over ('merged') to the real filesystem (and any prior version's files safely unmerged immediately thereafter).

There are then two main ways to invoke the ebuild. The first (and more common way) is via : typically, you would issue:

The second (lower level) way is invoke the directly; for example, you could issue:

which will clean Portage's temporary build directories, and then perform all the steps of the ebuild workflow, providing detailed output as it does so (you can also use the command to perform only certain steps, if you wish, and it can also create  files; see the manpage for details).

A More Complex ()
The example above is about as simple as a real-world ebuild gets!

However, one common additional requirement is the need to apply patches. To do this, an ebuild will typically override the default ebuild 'hook' function (invoked by the standard  flow after the source tarball has been successfully unpacked), and in the overridden version use the epatch utility function to apply patches held in the  directory.

For example, consider the package, which provides a file signing and signature verification utility. It lives in the category. Looking in its corresponding directory we notice immediately that unlike, there is a  subdirectory, containing two patches ( and ).

Let's examine version 1.0.7 of the :

Most of this should be familiar enough from the example, but there are some new elements too. Specifically:
 * the command is used to pull in two useful 'eclasses': eutils (which supplies the  function discussed shortly) and toolchain-funcs (which supplies, a function to return the name of the toolchain C compiler);
 * the SRC_URI makes use of the ${PN} variable, which expands out to the package name, without version (a full list of these convenience variables may be found here);
 * the IUSE definition is not blank: there is one optional USE flag here, (which switches to that SSL library, as we shall discuss next; see below for a brief introduction to USE flags);
 * the RDEPEND variable specifies a set of runtime dependencies, and the DEPEND a set of build/install time dependencies, for the package. This is used by Portage to ensure that all prerequisites are also installed, when you ask to . Notice that this build pulls in by default, unless the  USE flag is specified, in which case  is pulled in instead;
 * the 'hook' function (which by default is a no-op at EAPI 5) is overridden to perform two custom tasks:
 * to patch the source using the utility, using patch files  and  ( ${PV} expands to the package version, without name or revision tags). As described here,  intelligently attempts to apply patches using different  levels etc.
 * to invoke a small script to modify the Makefile slightly.
 * the 'hook' function (which by default will simply invoke  after some pre-preprocessing) is overridden to ensure that the C compiler is set correctly (the upstream Makefile not supporting environment-set   values in this case);
 * the 'hook' function (which by default will invoke emake DESTDIR="${D}" install and then further install any documentation specified via the DOCS array variable) is overridden to perform a manual install using some helper install functions; this is sometimes necessary if the upstream Makefile does not support the use of DESTDIR, or does not support the  target.

Ebuild Repositories (aka Overlays)
What if you want to modify an yourself, or add a new one? You could of course submit the to Gentoo using Bugzilla, but that only really applies to completed work you want to share. For work in progress, or private ebuilds, a different approach is required. You can't simply insert new entries into the tree, as they'll get overwritten next time you synchronize the Gentoo repository.

Instead, Portage supports the concept of ebuild repositories (historically known as "overlays") to address just this issue. These are simply additional collections of ebuilds and associated metadata, laid out in a similar filestructure to the main Portage tree, which Portage (by default, and as the historical name suggests) 'overlays' on the file structure. To illustrate, suppose you created a directory at, say,, created the subfolders and , then created an ebuild  (and manifest, ), and then created the following (in , to inform Portage's plug-in sync system of its presence):

Then, when referring to (or installing), Portage would use your version, rather than the 'official' (however, if you had created an ebuild with a lower version number, say 1.57, then by default Portage would still use the higher numbered version, from the official  'underlay').

We'll exploit this ability shortly, when we add the  ebuild repository (which will contain a number of useful tools used in this installation walk-through).

Portage's Configuration Files
Portage provides you, the user, with a great deal of flexibility. As such, it has many configuration options, specified via a set of files held in the directory (and subdirectories thereof). As our installation process is going to involve using Portage (via the command-line tool ) to download, then build and install up-to-date versions of all core system software, we first need to set up these configuration files appropriately.

The most important Portage configuration files you'll need to know about now are as follows (this is not complete - see this list for more information, and also the Portage manpage ):

Atoms, Packages, Categories, Versions, Sets and SLOTs
Finally for this background overview, there are a few Portage package management terms that are worth a brief recap: For more information on atom naming, see the (5) manpage.
 * As mentioned, a package refers to a homogeneous block of software which has a single provided ebuild per installable version, whether third-party (e.g., ) or internal to Gentoo itself (e.g., ).
 * Packages are grouped (as leaves of a tree) into categories, which describe broad classes of functionality. For example, is in the  category (along with other similar tools like  and );  is in the  category (along with other Portage applications, like  and ).
 * A package base atom simply refers to the name made up of the full category, followed by the package, without version information or other qualifiers. So for example, etc. You can find all the ebuilds in the currently sync'd tree for a given / base atom in the directory  (so, for example, ), and find more information about that base atom online at  (so, for example, https://packages.gentoo.org/package/app-portage/gentoolkit). While it is often possible to drop the category name and simply use the package itself, it's generally safer to use the base atom, since two different packages of the same name may exist in different categories (e.g.  could refer to either , an object database over SQLite, or , a computer algebra system).
 * It is generally possible to specify that a specific repository should be used to supply a package, by appending to its atom. For example,  would force Portage to install the  package from the  repository (and would fail if either that overlay was unknown, or if the  package was not present in it).
 * Any given package will normally be supported at multiple versions within Portage (one ebuild per version). Not all versions from the upstream tree may be present as ebuilds, only certain selected versions. The online package data referred to above will show what versions are available, on which architectures, and which are marked as 'stable', which are 'testing' (shown with a tilde ('~')), and which are masked (will not be installed by Portage, generally due to known problems or with the ebuild, or incompatibilities with other packages). You can fully qualify an atom by specifying its version as a suffix - generally, you take the base atom, then add a hyphen ('-'), then add a period-separated list of numbers (possibly finishing with a letter, and/or a revision suffix). So, for example, version 2.4.3 of would be written as ; version 1.19.1 (r1) of  as . Revisions are Gentoo  specific, they do not relate to upstream versioning (one implication of which being, that different revisions of a particular version of a package will generally use the same upstream source tarball (although they may of course apply different patch sets etc.)).
 * When specifying atoms to Portage in certain places (such as configuration files, like ), you can either specify base atoms (meaning apply the action to all ebuild versions), or a qualified version atom . You can qualify a versioned atom with:
 * A prefix ('>', '>=', '=', '<=', '<'], to restrict the action to particular versions relative to the stated variant (for example, if you appended "" to, you'd be telling Portage to apply the use flag to any version of  at or above 2.4.3.
 * A extended prefix: there are a number of these but the most important is '~', which is used to specify any revision of the base version specified. So, for example, would refer to, ,  etc. (where they exist, of course!)
 * A wildcard suffix ('*'). This can be used to match any version with the same string prefix. So for example, would match (at the time of writing), ,  etc.
 * A number of atoms may be grouped together into a set, so that operations (e.g. reinstallation) can be easily targeted at the whole group. Sets are special names and are prefixed by '@': some of these are pre-defined in Portage (for example, the System set (Portage) set (containing vital system software packages, the contents of the stage 3 tarball plus other component dictated by your profile), or the dynamically populated Preserve-libs set (which holds a list of packages using libraries whose sonames have changed (during an upgrade or downgrade) but whose rebuild has not been triggered automatically). The World set (Portage) set refers to all packages you explicitly requested be installed, and is contained in a file (note however that operations on the  set will include the  set, by default, not just what is in the  file). You can even define your own sets if you like.
 * Portage <span id="slot_intro">also allows (subject to certain limitations) different versions of the same package to exist on a machine at the same time: we speak of them being installed in different SLOTs. We won't need to refer to the SLOT technology explicitly in this tutorial, but should you see a versioned atom with a colon ':' followed by some numbers and possibly other characters at the end, that's a SLOT reference. For example, with the library, it is possible (at the time of writing) to have version 2.24.31-r1 and 3.22.15 installed in parallel, should you desire it (in SLOTs 2 and 3). You might then see a reference to, which would refer to any version of  in SLOT 3 (which would, for example, cover version 3.22.16 as well).

That's about it for this sidebar on atoms and versioning, apart from one last point: unlike other Linux distributions, you'll see no reference to 'releases' of Gentoo itself - there's nothing similar to Ubuntu's "Xenial Xerus" or "Artful Aardvark", Debian's "Stretch" or "Buster", Fedora's "Heisenbug" or "v26" etc. That's because, once installed, Gentoo itself is essentially versionless - when you update your system (more on which later), all installed software updates to the latest supported versions (subject to restrictions imposed by the Gentoo developers and you yourself, through settings in, etc.).

The upside of this is that you can get access to the latest and (often) greatest versions of software as soon as new ebuilds get released into the tree. The downside is that (particularly on the 'testing' (rather than the 'stable') branch), sometimes updates fail to complete successfully, an occurrence that is very rare indeed when using binary distributed, release-based distributions such as Ubuntu.

Time to get back to the install!

<span id="configure_compile_opts">Configuring
Our first Portage configuration task is to ensure that the download / unpack / prepare / configure / compile / install / merge cycle (aka 'emerging') - which you'll see rather a lot of when running Gentoo - is as <span id="parallel_emerge">efficient as possible. That primarily means taking advantage of whatever parallelism your system can offer.

There are two main dimensions to this - the maximum number of concurrent Portage jobs that will be run at any one time, and the maximum number of parallel threads executed by the process invoked by each ebuild itself.

As has been recommended, we'll set our number of concurrent jobs and parallel make threads to attempt, to be equal to the number of CPUs on the system, plus one. We'll also prevent new jobs or compilations starting when the system load average hits or exceeds the number of CPUs.

The two variables we'll need to set here are EMERGE_DEFAULT_OPTS (for Portage job control) and MAKEOPTS (to pass options on to ). These are often defined in the file, but we want to allow the values to be set programmatically. Since Portage doesn't support fancy bash features like command substitution, we'll set and export these variables in root's instead (these will then override any conflicting values in the  or profile, as explained earlier).

Start up your favourite editor: in this tutorial we'll be assuming :

is a pretty simple editor to use: move around using the arrow keys, type to edit as you would in any text processing program, and exit with when done: you'll be prompted whether to save changes if you have modified the file. At this point, enter and  to exit, saving changes, or  to exit without making changes. For some more information on the editor, see this Wiki entry.

Add the following text to the file:

Save and exit the editor.

Next, we need to make sure that the file is picked up by root's login shell, so copy across the default :

Next, <span id="setup_make_conf">on to the configuration file itself. The stage 3 tarball we extracted already contains a skeleton configuration. We'll open this file with (feel free to substitute your favourite alternative editor), delete the existing lines (in,  can be used to quickly cut the current line), and enter our alternative configuration instead (see after for a line-by-line explanation). Issue:

Edit the file so it reads:

Save the file and exit.

Here is a <span id="make_conf_summary">brief summary of the shipped ('stage 3') values are, and what our version achieves:

<span id="next_steps">Next Steps
Now we have these options configured, we're ready to into our 'stage 3' environment and start building! Click here to go to the next chapter, "Building the Gentoo Base System Minus Kernel".