xref: /linux/Documentation/filesystems/ramfs-rootfs-initramfs.rst (revision 6f7e6393d1ce636bb7ec77a7fe7b77458fddf701)
1.. SPDX-License-Identifier: GPL-2.0
2
3===========================
4Ramfs, rootfs and initramfs
5===========================
6
7October 17, 2005
8
9:Author: Rob Landley <rob@landley.net>
10
11What is ramfs?
12--------------
13
14Ramfs is a very simple filesystem that exports Linux's disk caching
15mechanisms (the page cache and dentry cache) as a dynamically resizable
16RAM-based filesystem.
17
18Normally all files are cached in memory by Linux.  Pages of data read from
19backing store (usually the block device the filesystem is mounted on) are kept
20around in case it's needed again, but marked as clean (freeable) in case the
21Virtual Memory system needs the memory for something else.  Similarly, data
22written to files is marked clean as soon as it has been written to backing
23store, but kept around for caching purposes until the VM reallocates the
24memory.  A similar mechanism (the dentry cache) greatly speeds up access to
25directories.
26
27With ramfs, there is no backing store.  Files written into ramfs allocate
28dentries and page cache as usual, but there's nowhere to write them to.
29This means the pages are never marked clean, so they can't be freed by the
30VM when it's looking to recycle memory.
31
32The amount of code required to implement ramfs is tiny, because all the
33work is done by the existing Linux caching infrastructure.  Basically,
34you're mounting the disk cache as a filesystem.  Because of this, ramfs is not
35an optional component removable via menuconfig, since there would be negligible
36space savings.
37
38ramfs and ramdisk:
39------------------
40
41The older "ram disk" mechanism created a synthetic block device out of
42an area of RAM and used it as backing store for a filesystem.  This block
43device was of fixed size, so the filesystem mounted on it was of fixed
44size.  Using a ram disk also required unnecessarily copying memory from the
45fake block device into the page cache (and copying changes back out), as well
46as creating and destroying dentries.  Plus it needed a filesystem driver
47(such as ext2) to format and interpret this data.
48
49Compared to ramfs, this wastes memory (and memory bus bandwidth), creates
50unnecessary work for the CPU, and pollutes the CPU caches.  (There are tricks
51to avoid this copying by playing with the page tables, but they're unpleasantly
52complicated and turn out to be about as expensive as the copying anyway.)
53More to the point, all the work ramfs is doing has to happen _anyway_,
54since all file access goes through the page and dentry caches.  The RAM
55disk is simply unnecessary; ramfs is internally much simpler.
56
57Another reason ramdisks are semi-obsolete is that the introduction of
58loopback devices offered a more flexible and convenient way to create
59synthetic block devices, now from files instead of from chunks of memory.
60See losetup (8) for details.
61
62ramfs and tmpfs:
63----------------
64
65One downside of ramfs is you can keep writing data into it until you fill
66up all memory, and the VM can't free it because the VM thinks that files
67should get written to backing store (rather than swap space), but ramfs hasn't
68got any backing store.  Because of this, only root (or a trusted user) should
69be allowed write access to a ramfs mount.
70
71A ramfs derivative called tmpfs was created to add size limits, and the ability
72to write the data to swap space.  Normal users can be allowed write access to
73tmpfs mounts.  See Documentation/filesystems/tmpfs.rst for more information.
74
75What is rootfs?
76---------------
77
78Rootfs is a special instance of ramfs (or tmpfs, if that's enabled), which is
79always present in Linux systems.  The kernel uses an immutable empty filesystem
80called nullfs as the true root of the VFS hierarchy, with the mutable rootfs
81(tmpfs/ramfs) mounted on top of it.  This allows pivot_root() and unmounting
82of the initramfs to work normally.
83
84Most systems just mount another filesystem over rootfs and ignore it.  The
85amount of space an empty instance of ramfs takes up is tiny.
86
87If CONFIG_TMPFS is enabled, rootfs will use tmpfs instead of ramfs by
88default.  To force ramfs, add "rootfstype=ramfs" to the kernel command
89line.
90
91What is initramfs?
92------------------
93
94All 2.6 Linux kernels contain a gzipped "cpio" format archive, which is
95extracted into rootfs when the kernel boots up.  After extracting, the kernel
96checks to see if rootfs contains a file "init", and if so it executes it as PID
971.  If found, this init process is responsible for bringing the system the
98rest of the way up, including locating and mounting the real root device (if
99any).  If rootfs does not contain an init program after the embedded cpio
100archive is extracted into it, the kernel will fall through to the older code
101to locate and mount a root partition, then exec some variant of /sbin/init
102out of that.
103
104All this differs from the old initrd in several ways:
105
106  - The old initrd was always a separate file, while the initramfs archive is
107    linked into the linux kernel image.  (The directory ``linux-*/usr`` is
108    devoted to generating this archive during the build.)
109
110  - The old initrd file was a gzipped filesystem image (in some file format,
111    such as ext2, that needed a driver built into the kernel), while the new
112    initramfs archive is a gzipped cpio archive (like tar only simpler,
113    see cpio(1) and Documentation/driver-api/early-userspace/buffer-format.rst).
114    The kernel's cpio extraction code is not only extremely small, it's also
115    __init text and data that can be discarded during the boot process.
116
117  - The program run by the old initrd (which was called /initrd, not /init) did
118    some setup and then returned to the kernel, while the init program from
119    initramfs is not expected to return to the kernel.  (If /init needs to hand
120    off control it can overmount / with a new root device and exec another init
121    program.  See the switch_root utility, below.)
122
123  - When switching another root device, initrd would pivot_root and then
124    umount the ramdisk.  With nullfs as the true root, pivot_root() works
125    normally from the initramfs.  Userspace can simply do::
126
127      chdir(new_root);
128      pivot_root(".", ".");
129      umount2(".", MNT_DETACH);
130
131    This is the preferred method for switching root filesystems.
132
133Populating initramfs:
134---------------------
135
136The 2.6 kernel build process always creates a gzipped cpio format initramfs
137archive and links it into the resulting kernel binary.  By default, this
138archive is empty (consuming 134 bytes on x86).
139
140The config option CONFIG_INITRAMFS_SOURCE (in General Setup in menuconfig,
141and living in usr/Kconfig) can be used to specify a source for the
142initramfs archive, which will automatically be incorporated into the
143resulting binary.  This option can point to an existing gzipped cpio
144archive, a directory containing files to be archived, or a text file
145specification such as the following example::
146
147  dir /dev 755 0 0
148  nod /dev/console 644 0 0 c 5 1
149  nod /dev/loop0 644 0 0 b 7 0
150  dir /bin 755 1000 1000
151  slink /bin/sh busybox 777 0 0
152  file /bin/busybox initramfs/busybox 755 0 0
153  dir /proc 755 0 0
154  dir /sys 755 0 0
155  dir /mnt 755 0 0
156  file /init initramfs/init.sh 755 0 0
157
158Run "usr/gen_init_cpio" (after the kernel build) to get a usage message
159documenting the above file format.
160
161One advantage of the configuration file is that root access is not required to
162set permissions or create device nodes in the new archive.  (Note that those
163two example "file" entries expect to find files named "init.sh" and "busybox" in
164a directory called "initramfs", under the linux-2.6.* directory.  See
165Documentation/driver-api/early-userspace/early_userspace_support.rst for more details.)
166
167The kernel does not depend on external cpio tools.  If you specify a
168directory instead of a configuration file, the kernel's build infrastructure
169creates a configuration file from that directory (usr/Makefile calls
170usr/gen_initramfs.sh), and proceeds to package up that directory
171using the config file (by feeding it to usr/gen_init_cpio, which is created
172from usr/gen_init_cpio.c).  The kernel's build-time cpio creation code is
173entirely self-contained, and the kernel's boot-time extractor is also
174(obviously) self-contained.
175
176The one thing you might need external cpio utilities installed for is creating
177or extracting your own preprepared cpio files to feed to the kernel build
178(instead of a config file or directory).
179
180The following command line can extract a cpio image (either by the above script
181or by the kernel build) back into its component files::
182
183  cpio -i -d -H newc -F initramfs_data.cpio --no-absolute-filenames
184
185The following shell script can create a prebuilt cpio archive you can
186use in place of the above config file::
187
188  #!/bin/sh
189
190  # Copyright 2006 Rob Landley <rob@landley.net> and TimeSys Corporation.
191  # Licensed under GPL version 2
192
193  if [ $# -ne 2 ]
194  then
195    echo "usage: mkinitramfs directory imagename.cpio.gz"
196    exit 1
197  fi
198
199  if [ -d "$1" ]
200  then
201    echo "creating $2 from $1"
202    (cd "$1"; find . | cpio -o -H newc | gzip) > "$2"
203  else
204    echo "First argument must be a directory"
205    exit 1
206  fi
207
208.. Note::
209
210   The cpio man page contains some bad advice that will break your initramfs
211   archive if you follow it.  It says "A typical way to generate the list
212   of filenames is with the find command; you should give find the -depth
213   option to minimize problems with permissions on directories that are
214   unwritable or not searchable."  Don't do this when creating
215   initramfs.cpio.gz images, it won't work.  The Linux kernel cpio extractor
216   won't create files in a directory that doesn't exist, so the directory
217   entries must go before the files that go in those directories.
218   The above script gets them in the right order.
219
220External initramfs images:
221--------------------------
222
223If the kernel has initrd support enabled, an external cpio.gz archive can also
224be passed into a 2.6 kernel in place of an initrd.  In this case, the kernel
225will autodetect the type (initramfs, not initrd) and extract the external cpio
226archive into rootfs before trying to run /init.
227
228This has the memory efficiency advantages of initramfs (no ramdisk block
229device) but the separate packaging of initrd (which is nice if you have
230non-GPL code you'd like to run from initramfs, without conflating it with
231the GPL licensed Linux kernel binary).
232
233It can also be used to supplement the kernel's built-in initramfs image.  The
234files in the external archive will overwrite any conflicting files in
235the built-in initramfs archive.  Some distributors also prefer to customize
236a single kernel image with task-specific initramfs images, without recompiling.
237
238Contents of initramfs:
239----------------------
240
241An initramfs archive is a complete self-contained root filesystem for Linux.
242If you don't already understand what shared libraries, devices, and paths
243you need to get a minimal root filesystem up and running, here are some
244references:
245
246- https://www.tldp.org/HOWTO/Bootdisk-HOWTO/
247- https://www.tldp.org/HOWTO/From-PowerUp-To-Bash-Prompt-HOWTO.html
248- http://www.linuxfromscratch.org/lfs/view/stable/
249
250The "klibc" package (https://www.kernel.org/pub/linux/libs/klibc) is
251designed to be a tiny C library to statically link early userspace
252code against, along with some related utilities.  It is BSD licensed.
253
254I use uClibc (https://www.uclibc.org) and busybox (https://www.busybox.net)
255myself.  These are LGPL and GPL, respectively.  (A self-contained initramfs
256package is planned for the busybox 1.3 release.)
257
258In theory you could use glibc, but that's not well suited for small embedded
259uses like this.  (A "hello world" program statically linked against glibc is
260over 400k.  With uClibc it's 7k.  Also note that glibc dlopens libnss to do
261name lookups, even when otherwise statically linked.)
262
263A good first step is to get initramfs to run a statically linked "hello world"
264program as init, and test it under an emulator like qemu (www.qemu.org) or
265User Mode Linux, like so::
266
267  cat > hello.c << EOF
268  #include <stdio.h>
269  #include <unistd.h>
270
271  int main(int argc, char *argv[])
272  {
273    printf("Hello world!\n");
274    sleep(999999999);
275  }
276  EOF
277  gcc -static hello.c -o init
278  echo init | cpio -o -H newc | gzip > test.cpio.gz
279  # Testing external initramfs using the initrd loading mechanism.
280  qemu -kernel /boot/vmlinuz -initrd test.cpio.gz /dev/zero
281
282When debugging a normal root filesystem, it's nice to be able to boot with
283"init=/bin/sh".  The initramfs equivalent is "rdinit=/bin/sh", and it's
284just as useful.
285
286Why cpio rather than tar?
287-------------------------
288
289This decision was made back in December, 2001.  The discussion started here:
290
291- https://lore.kernel.org/lkml/a03cke$640$1@cesium.transmeta.com/
292
293And spawned a second thread (specifically on tar vs cpio), starting here:
294
295- https://lore.kernel.org/lkml/3C25A06D.7030408@zytor.com/
296
297The quick and dirty summary version (which is no substitute for reading
298the above threads) is:
299
3001) cpio is a standard.  It's decades old (from the AT&T days), and already
301   widely used on Linux (inside RPM, Red Hat's device driver disks).  Here's
302   a Linux Journal article about it from 1996:
303
304      http://www.linuxjournal.com/article/1213
305
306   It's not as popular as tar because the traditional cpio command line tools
307   require _truly_hideous_ command line arguments.  But that says nothing
308   either way about the archive format, and there are alternative tools,
309   such as:
310
311      https://linux.die.net/man/1/afio
312
3132) The cpio archive format chosen by the kernel is simpler and cleaner (and
314   thus easier to create and parse) than any of the (literally dozens of)
315   various tar archive formats.  The complete initramfs archive format is
316   explained in buffer-format.rst, created in usr/gen_init_cpio.c, and
317   extracted in init/initramfs.c.  All three together come to less than 26k
318   total of human-readable text.
319
3203) The GNU project standardizing on tar is approximately as relevant as
321   Windows standardizing on zip.  Linux is not part of either, and is free
322   to make its own technical decisions.
323
3244) Since this is a kernel internal format, it could easily have been
325   something brand new.  The kernel provides its own tools to create and
326   extract this format anyway.  Using an existing standard was preferable,
327   but not essential.
328
3295) Al Viro made the decision (quote: "tar is ugly as hell and not going to be
330   supported on the kernel side"):
331
332    - https://lore.kernel.org/lkml/Pine.GSO.4.21.0112222109050.21702-100000@weyl.math.psu.edu/
333
334   explained his reasoning:
335
336    - https://lore.kernel.org/lkml/Pine.GSO.4.21.0112222240530.21702-100000@weyl.math.psu.edu/
337    - https://lore.kernel.org/lkml/Pine.GSO.4.21.0112230849550.23300-100000@weyl.math.psu.edu/
338
339   and, most importantly, designed and implemented the initramfs code.
340
341Future directions:
342------------------
343
344Today (2.6.16), initramfs is always compiled in, but not always used.  The
345kernel falls back to legacy boot code that is reached only if initramfs does
346not contain an /init program.  The fallback is legacy code, there to ensure a
347smooth transition and allowing early boot functionality to gradually move to
348"early userspace" (I.E. initramfs).
349
350The move to early userspace is necessary because finding and mounting the real
351root device is complex.  Root partitions can span multiple devices (raid or
352separate journal).  They can be out on the network (requiring dhcp, setting a
353specific MAC address, logging into a server, etc).  They can live on removable
354media, with dynamically allocated major/minor numbers and persistent naming
355issues requiring a full udev implementation to sort out.  They can be
356compressed, encrypted, copy-on-write, loopback mounted, strangely partitioned,
357and so on.
358
359This kind of complexity (which inevitably includes policy) is rightly handled
360in userspace.  Both klibc and busybox/uClibc are working on simple initramfs
361packages to drop into a kernel build.
362
363The klibc package has now been accepted into Andrew Morton's 2.6.17-mm tree.
364The kernel's current early boot code (partition detection, etc) will probably
365be migrated into a default initramfs, automatically created and used by the
366kernel build.
367