Back to home page

OSCL-LXR

 
 

    


0001 .. SPDX-License-Identifier: GPL-2.0
0002 
0003 ===========================
0004 Ramfs, rootfs and initramfs
0005 ===========================
0006 
0007 October 17, 2005
0008 
0009 Rob Landley <rob@landley.net>
0010 =============================
0011 
0012 What is ramfs?
0013 --------------
0014 
0015 Ramfs is a very simple filesystem that exports Linux's disk caching
0016 mechanisms (the page cache and dentry cache) as a dynamically resizable
0017 RAM-based filesystem.
0018 
0019 Normally all files are cached in memory by Linux.  Pages of data read from
0020 backing store (usually the block device the filesystem is mounted on) are kept
0021 around in case it's needed again, but marked as clean (freeable) in case the
0022 Virtual Memory system needs the memory for something else.  Similarly, data
0023 written to files is marked clean as soon as it has been written to backing
0024 store, but kept around for caching purposes until the VM reallocates the
0025 memory.  A similar mechanism (the dentry cache) greatly speeds up access to
0026 directories.
0027 
0028 With ramfs, there is no backing store.  Files written into ramfs allocate
0029 dentries and page cache as usual, but there's nowhere to write them to.
0030 This means the pages are never marked clean, so they can't be freed by the
0031 VM when it's looking to recycle memory.
0032 
0033 The amount of code required to implement ramfs is tiny, because all the
0034 work is done by the existing Linux caching infrastructure.  Basically,
0035 you're mounting the disk cache as a filesystem.  Because of this, ramfs is not
0036 an optional component removable via menuconfig, since there would be negligible
0037 space savings.
0038 
0039 ramfs and ramdisk:
0040 ------------------
0041 
0042 The older "ram disk" mechanism created a synthetic block device out of
0043 an area of RAM and used it as backing store for a filesystem.  This block
0044 device was of fixed size, so the filesystem mounted on it was of fixed
0045 size.  Using a ram disk also required unnecessarily copying memory from the
0046 fake block device into the page cache (and copying changes back out), as well
0047 as creating and destroying dentries.  Plus it needed a filesystem driver
0048 (such as ext2) to format and interpret this data.
0049 
0050 Compared to ramfs, this wastes memory (and memory bus bandwidth), creates
0051 unnecessary work for the CPU, and pollutes the CPU caches.  (There are tricks
0052 to avoid this copying by playing with the page tables, but they're unpleasantly
0053 complicated and turn out to be about as expensive as the copying anyway.)
0054 More to the point, all the work ramfs is doing has to happen _anyway_,
0055 since all file access goes through the page and dentry caches.  The RAM
0056 disk is simply unnecessary; ramfs is internally much simpler.
0057 
0058 Another reason ramdisks are semi-obsolete is that the introduction of
0059 loopback devices offered a more flexible and convenient way to create
0060 synthetic block devices, now from files instead of from chunks of memory.
0061 See losetup (8) for details.
0062 
0063 ramfs and tmpfs:
0064 ----------------
0065 
0066 One downside of ramfs is you can keep writing data into it until you fill
0067 up all memory, and the VM can't free it because the VM thinks that files
0068 should get written to backing store (rather than swap space), but ramfs hasn't
0069 got any backing store.  Because of this, only root (or a trusted user) should
0070 be allowed write access to a ramfs mount.
0071 
0072 A ramfs derivative called tmpfs was created to add size limits, and the ability
0073 to write the data to swap space.  Normal users can be allowed write access to
0074 tmpfs mounts.  See Documentation/filesystems/tmpfs.rst for more information.
0075 
0076 What is rootfs?
0077 ---------------
0078 
0079 Rootfs is a special instance of ramfs (or tmpfs, if that's enabled), which is
0080 always present in 2.6 systems.  You can't unmount rootfs for approximately the
0081 same reason you can't kill the init process; rather than having special code
0082 to check for and handle an empty list, it's smaller and simpler for the kernel
0083 to just make sure certain lists can't become empty.
0084 
0085 Most systems just mount another filesystem over rootfs and ignore it.  The
0086 amount of space an empty instance of ramfs takes up is tiny.
0087 
0088 If CONFIG_TMPFS is enabled, rootfs will use tmpfs instead of ramfs by
0089 default.  To force ramfs, add "rootfstype=ramfs" to the kernel command
0090 line.
0091 
0092 What is initramfs?
0093 ------------------
0094 
0095 All 2.6 Linux kernels contain a gzipped "cpio" format archive, which is
0096 extracted into rootfs when the kernel boots up.  After extracting, the kernel
0097 checks to see if rootfs contains a file "init", and if so it executes it as PID
0098 1.  If found, this init process is responsible for bringing the system the
0099 rest of the way up, including locating and mounting the real root device (if
0100 any).  If rootfs does not contain an init program after the embedded cpio
0101 archive is extracted into it, the kernel will fall through to the older code
0102 to locate and mount a root partition, then exec some variant of /sbin/init
0103 out of that.
0104 
0105 All this differs from the old initrd in several ways:
0106 
0107   - The old initrd was always a separate file, while the initramfs archive is
0108     linked into the linux kernel image.  (The directory ``linux-*/usr`` is
0109     devoted to generating this archive during the build.)
0110 
0111   - The old initrd file was a gzipped filesystem image (in some file format,
0112     such as ext2, that needed a driver built into the kernel), while the new
0113     initramfs archive is a gzipped cpio archive (like tar only simpler,
0114     see cpio(1) and Documentation/driver-api/early-userspace/buffer-format.rst).
0115     The kernel's cpio extraction code is not only extremely small, it's also
0116     __init text and data that can be discarded during the boot process.
0117 
0118   - The program run by the old initrd (which was called /initrd, not /init) did
0119     some setup and then returned to the kernel, while the init program from
0120     initramfs is not expected to return to the kernel.  (If /init needs to hand
0121     off control it can overmount / with a new root device and exec another init
0122     program.  See the switch_root utility, below.)
0123 
0124   - When switching another root device, initrd would pivot_root and then
0125     umount the ramdisk.  But initramfs is rootfs: you can neither pivot_root
0126     rootfs, nor unmount it.  Instead delete everything out of rootfs to
0127     free up the space (find -xdev / -exec rm '{}' ';'), overmount rootfs
0128     with the new root (cd /newmount; mount --move . /; chroot .), attach
0129     stdin/stdout/stderr to the new /dev/console, and exec the new init.
0130 
0131     Since this is a remarkably persnickety process (and involves deleting
0132     commands before you can run them), the klibc package introduced a helper
0133     program (utils/run_init.c) to do all this for you.  Most other packages
0134     (such as busybox) have named this command "switch_root".
0135 
0136 Populating initramfs:
0137 ---------------------
0138 
0139 The 2.6 kernel build process always creates a gzipped cpio format initramfs
0140 archive and links it into the resulting kernel binary.  By default, this
0141 archive is empty (consuming 134 bytes on x86).
0142 
0143 The config option CONFIG_INITRAMFS_SOURCE (in General Setup in menuconfig,
0144 and living in usr/Kconfig) can be used to specify a source for the
0145 initramfs archive, which will automatically be incorporated into the
0146 resulting binary.  This option can point to an existing gzipped cpio
0147 archive, a directory containing files to be archived, or a text file
0148 specification such as the following example::
0149 
0150   dir /dev 755 0 0
0151   nod /dev/console 644 0 0 c 5 1
0152   nod /dev/loop0 644 0 0 b 7 0
0153   dir /bin 755 1000 1000
0154   slink /bin/sh busybox 777 0 0
0155   file /bin/busybox initramfs/busybox 755 0 0
0156   dir /proc 755 0 0
0157   dir /sys 755 0 0
0158   dir /mnt 755 0 0
0159   file /init initramfs/init.sh 755 0 0
0160 
0161 Run "usr/gen_init_cpio" (after the kernel build) to get a usage message
0162 documenting the above file format.
0163 
0164 One advantage of the configuration file is that root access is not required to
0165 set permissions or create device nodes in the new archive.  (Note that those
0166 two example "file" entries expect to find files named "init.sh" and "busybox" in
0167 a directory called "initramfs", under the linux-2.6.* directory.  See
0168 Documentation/driver-api/early-userspace/early_userspace_support.rst for more details.)
0169 
0170 The kernel does not depend on external cpio tools.  If you specify a
0171 directory instead of a configuration file, the kernel's build infrastructure
0172 creates a configuration file from that directory (usr/Makefile calls
0173 usr/gen_initramfs.sh), and proceeds to package up that directory
0174 using the config file (by feeding it to usr/gen_init_cpio, which is created
0175 from usr/gen_init_cpio.c).  The kernel's build-time cpio creation code is
0176 entirely self-contained, and the kernel's boot-time extractor is also
0177 (obviously) self-contained.
0178 
0179 The one thing you might need external cpio utilities installed for is creating
0180 or extracting your own preprepared cpio files to feed to the kernel build
0181 (instead of a config file or directory).
0182 
0183 The following command line can extract a cpio image (either by the above script
0184 or by the kernel build) back into its component files::
0185 
0186   cpio -i -d -H newc -F initramfs_data.cpio --no-absolute-filenames
0187 
0188 The following shell script can create a prebuilt cpio archive you can
0189 use in place of the above config file::
0190 
0191   #!/bin/sh
0192 
0193   # Copyright 2006 Rob Landley <rob@landley.net> and TimeSys Corporation.
0194   # Licensed under GPL version 2
0195 
0196   if [ $# -ne 2 ]
0197   then
0198     echo "usage: mkinitramfs directory imagename.cpio.gz"
0199     exit 1
0200   fi
0201 
0202   if [ -d "$1" ]
0203   then
0204     echo "creating $2 from $1"
0205     (cd "$1"; find . | cpio -o -H newc | gzip) > "$2"
0206   else
0207     echo "First argument must be a directory"
0208     exit 1
0209   fi
0210 
0211 .. Note::
0212 
0213    The cpio man page contains some bad advice that will break your initramfs
0214    archive if you follow it.  It says "A typical way to generate the list
0215    of filenames is with the find command; you should give find the -depth
0216    option to minimize problems with permissions on directories that are
0217    unwritable or not searchable."  Don't do this when creating
0218    initramfs.cpio.gz images, it won't work.  The Linux kernel cpio extractor
0219    won't create files in a directory that doesn't exist, so the directory
0220    entries must go before the files that go in those directories.
0221    The above script gets them in the right order.
0222 
0223 External initramfs images:
0224 --------------------------
0225 
0226 If the kernel has initrd support enabled, an external cpio.gz archive can also
0227 be passed into a 2.6 kernel in place of an initrd.  In this case, the kernel
0228 will autodetect the type (initramfs, not initrd) and extract the external cpio
0229 archive into rootfs before trying to run /init.
0230 
0231 This has the memory efficiency advantages of initramfs (no ramdisk block
0232 device) but the separate packaging of initrd (which is nice if you have
0233 non-GPL code you'd like to run from initramfs, without conflating it with
0234 the GPL licensed Linux kernel binary).
0235 
0236 It can also be used to supplement the kernel's built-in initramfs image.  The
0237 files in the external archive will overwrite any conflicting files in
0238 the built-in initramfs archive.  Some distributors also prefer to customize
0239 a single kernel image with task-specific initramfs images, without recompiling.
0240 
0241 Contents of initramfs:
0242 ----------------------
0243 
0244 An initramfs archive is a complete self-contained root filesystem for Linux.
0245 If you don't already understand what shared libraries, devices, and paths
0246 you need to get a minimal root filesystem up and running, here are some
0247 references:
0248 
0249 - https://www.tldp.org/HOWTO/Bootdisk-HOWTO/
0250 - https://www.tldp.org/HOWTO/From-PowerUp-To-Bash-Prompt-HOWTO.html
0251 - http://www.linuxfromscratch.org/lfs/view/stable/
0252 
0253 The "klibc" package (https://www.kernel.org/pub/linux/libs/klibc) is
0254 designed to be a tiny C library to statically link early userspace
0255 code against, along with some related utilities.  It is BSD licensed.
0256 
0257 I use uClibc (https://www.uclibc.org) and busybox (https://www.busybox.net)
0258 myself.  These are LGPL and GPL, respectively.  (A self-contained initramfs
0259 package is planned for the busybox 1.3 release.)
0260 
0261 In theory you could use glibc, but that's not well suited for small embedded
0262 uses like this.  (A "hello world" program statically linked against glibc is
0263 over 400k.  With uClibc it's 7k.  Also note that glibc dlopens libnss to do
0264 name lookups, even when otherwise statically linked.)
0265 
0266 A good first step is to get initramfs to run a statically linked "hello world"
0267 program as init, and test it under an emulator like qemu (www.qemu.org) or
0268 User Mode Linux, like so::
0269 
0270   cat > hello.c << EOF
0271   #include <stdio.h>
0272   #include <unistd.h>
0273 
0274   int main(int argc, char *argv[])
0275   {
0276     printf("Hello world!\n");
0277     sleep(999999999);
0278   }
0279   EOF
0280   gcc -static hello.c -o init
0281   echo init | cpio -o -H newc | gzip > test.cpio.gz
0282   # Testing external initramfs using the initrd loading mechanism.
0283   qemu -kernel /boot/vmlinuz -initrd test.cpio.gz /dev/zero
0284 
0285 When debugging a normal root filesystem, it's nice to be able to boot with
0286 "init=/bin/sh".  The initramfs equivalent is "rdinit=/bin/sh", and it's
0287 just as useful.
0288 
0289 Why cpio rather than tar?
0290 -------------------------
0291 
0292 This decision was made back in December, 2001.  The discussion started here:
0293 
0294   http://www.uwsg.iu.edu/hypermail/linux/kernel/0112.2/1538.html
0295 
0296 And spawned a second thread (specifically on tar vs cpio), starting here:
0297 
0298   http://www.uwsg.iu.edu/hypermail/linux/kernel/0112.2/1587.html
0299 
0300 The quick and dirty summary version (which is no substitute for reading
0301 the above threads) is:
0302 
0303 1) cpio is a standard.  It's decades old (from the AT&T days), and already
0304    widely used on Linux (inside RPM, Red Hat's device driver disks).  Here's
0305    a Linux Journal article about it from 1996:
0306 
0307       http://www.linuxjournal.com/article/1213
0308 
0309    It's not as popular as tar because the traditional cpio command line tools
0310    require _truly_hideous_ command line arguments.  But that says nothing
0311    either way about the archive format, and there are alternative tools,
0312    such as:
0313 
0314      http://freecode.com/projects/afio
0315 
0316 2) The cpio archive format chosen by the kernel is simpler and cleaner (and
0317    thus easier to create and parse) than any of the (literally dozens of)
0318    various tar archive formats.  The complete initramfs archive format is
0319    explained in buffer-format.txt, created in usr/gen_init_cpio.c, and
0320    extracted in init/initramfs.c.  All three together come to less than 26k
0321    total of human-readable text.
0322 
0323 3) The GNU project standardizing on tar is approximately as relevant as
0324    Windows standardizing on zip.  Linux is not part of either, and is free
0325    to make its own technical decisions.
0326 
0327 4) Since this is a kernel internal format, it could easily have been
0328    something brand new.  The kernel provides its own tools to create and
0329    extract this format anyway.  Using an existing standard was preferable,
0330    but not essential.
0331 
0332 5) Al Viro made the decision (quote: "tar is ugly as hell and not going to be
0333    supported on the kernel side"):
0334 
0335       http://www.uwsg.iu.edu/hypermail/linux/kernel/0112.2/1540.html
0336 
0337    explained his reasoning:
0338 
0339      - http://www.uwsg.iu.edu/hypermail/linux/kernel/0112.2/1550.html
0340      - http://www.uwsg.iu.edu/hypermail/linux/kernel/0112.2/1638.html
0341 
0342    and, most importantly, designed and implemented the initramfs code.
0343 
0344 Future directions:
0345 ------------------
0346 
0347 Today (2.6.16), initramfs is always compiled in, but not always used.  The
0348 kernel falls back to legacy boot code that is reached only if initramfs does
0349 not contain an /init program.  The fallback is legacy code, there to ensure a
0350 smooth transition and allowing early boot functionality to gradually move to
0351 "early userspace" (I.E. initramfs).
0352 
0353 The move to early userspace is necessary because finding and mounting the real
0354 root device is complex.  Root partitions can span multiple devices (raid or
0355 separate journal).  They can be out on the network (requiring dhcp, setting a
0356 specific MAC address, logging into a server, etc).  They can live on removable
0357 media, with dynamically allocated major/minor numbers and persistent naming
0358 issues requiring a full udev implementation to sort out.  They can be
0359 compressed, encrypted, copy-on-write, loopback mounted, strangely partitioned,
0360 and so on.
0361 
0362 This kind of complexity (which inevitably includes policy) is rightly handled
0363 in userspace.  Both klibc and busybox/uClibc are working on simple initramfs
0364 packages to drop into a kernel build.
0365 
0366 The klibc package has now been accepted into Andrew Morton's 2.6.17-mm tree.
0367 The kernel's current early boot code (partition detection, etc) will probably
0368 be migrated into a default initramfs, automatically created and used by the
0369 kernel build.