gnu: emacs-eshell-prompt-extras: Update to 1.0.
[jackhill/guix/guix.git] / gnu / build / linux-boot.scm
CommitLineData
88840f02 1;;; GNU Guix --- Functional package management for GNU
ae7a316b 2;;; Copyright © 2013, 2014, 2015, 2016, 2017, 2018, 2019 Ludovic Courtès <ludo@gnu.org>
a5e13c3b 3;;; Copyright © 2017 Mathieu Othacehe <m.othacehe@gmail.com>
88840f02
LC
4;;;
5;;; This file is part of GNU Guix.
6;;;
7;;; GNU Guix is free software; you can redistribute it and/or modify it
8;;; under the terms of the GNU General Public License as published by
9;;; the Free Software Foundation; either version 3 of the License, or (at
10;;; your option) any later version.
11;;;
12;;; GNU Guix is distributed in the hope that it will be useful, but
13;;; WITHOUT ANY WARRANTY; without even the implied warranty of
14;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15;;; GNU General Public License for more details.
16;;;
17;;; You should have received a copy of the GNU General Public License
18;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
19
8a9e21d1 20(define-module (gnu build linux-boot)
88840f02 21 #:use-module (rnrs io ports)
e3ced65a 22 #:use-module (system repl error-handling)
d4254711 23 #:autoload (system repl repl) (start-repl)
d4254711 24 #:use-module (srfi srfi-1)
97817e7f 25 #:use-module (srfi srfi-9)
d4254711
LC
26 #:use-module (srfi srfi-26)
27 #:use-module (ice-9 match)
97817e7f
DM
28 #:use-module (ice-9 rdelim)
29 #:use-module (ice-9 regex)
44ddf33e 30 #:use-module (ice-9 ftw)
d4254711 31 #:use-module (guix build utils)
1c65cca5
LC
32 #:use-module ((guix build syscalls)
33 #:hide (file-system-type))
0e704a2d 34 #:use-module (gnu build linux-modules)
e2f4b305 35 #:use-module (gnu build file-systems)
1c65cca5 36 #:use-module (gnu system file-systems)
88840f02
LC
37 #:export (mount-essential-file-systems
38 linux-command-line
87a52da7 39 find-long-option
015d0a84 40 find-long-options
d91712ee 41 make-essential-device-nodes
97817e7f 42 make-static-device-nodes
88840f02 43 configure-qemu-networking
85a83edb 44
d4254711
LC
45 device-number
46 boot-system))
88840f02
LC
47
48;;; Commentary:
49;;;
50;;; Utility procedures useful in a Linux initial RAM disk (initrd). Note that
51;;; many of these use procedures not yet available in vanilla Guile (`mount',
52;;; `load-linux-module', etc.); these are provided by a Guile patch used in
53;;; the GNU distribution.
54;;;
55;;; Code:
56
57(define* (mount-essential-file-systems #:key (root "/"))
cc0e575a 58 "Mount /dev, /proc, and /sys under ROOT."
88840f02
LC
59 (define (scope dir)
60 (string-append root
61 (if (string-suffix? "/" root)
62 ""
63 "/")
64 dir))
65
66 (unless (file-exists? (scope "proc"))
67 (mkdir (scope "proc")))
68 (mount "none" (scope "proc") "proc")
69
cc0e575a
LC
70 (unless (file-exists? (scope "dev"))
71 (mkdir (scope "dev")))
72 (mount "none" (scope "dev") "devtmpfs")
73
88840f02
LC
74 (unless (file-exists? (scope "sys"))
75 (mkdir (scope "sys")))
76 (mount "none" (scope "sys") "sysfs"))
77
1d462832
LC
78(define (move-essential-file-systems root)
79 "Move currently mounted essential file systems to ROOT."
80 (for-each (lambda (dir)
81 (let ((target (string-append root dir)))
82 (unless (file-exists? target)
83 (mkdir target))
84 (mount dir target "" MS_MOVE)))
cc0e575a 85 '("/dev" "/proc" "/sys")))
1d462832 86
88840f02
LC
87(define (linux-command-line)
88 "Return the Linux kernel command line as a list of strings."
89 (string-tokenize
90 (call-with-input-file "/proc/cmdline"
91 get-string-all)))
92
87a52da7
LC
93(define (find-long-option option arguments)
94 "Find OPTION among ARGUMENTS, where OPTION is something like \"--load\".
95Return the value associated with OPTION, or #f on failure."
96 (let ((opt (string-append option "=")))
97 (and=> (find (cut string-prefix? opt <>)
98 arguments)
99 (lambda (arg)
100 (substring arg (+ 1 (string-index arg #\=)))))))
101
015d0a84
DM
102(define (find-long-options option arguments)
103 "Find OPTIONs among ARGUMENTS, where OPTION is something like \"console\".
104Return the values associated with OPTIONs as a list, or the empty list if
105OPTION doesn't appear in ARGUMENTS."
106 (let ((opt (string-append option "=")))
107 (filter-map (lambda (arg)
108 (and (string-prefix? opt arg)
109 (substring arg (+ 1 (string-index arg #\=)))))
110 arguments)))
111
ac52e80b
LC
112(define* (make-disk-device-nodes base major #:optional (minor 0))
113 "Make the block device nodes around BASE (something like \"/root/dev/sda\")
114with the given MAJOR number, starting with MINOR."
115 (mknod base 'block-special #o644 (device-number major minor))
116 (let loop ((i 1))
ced0106a 117 (when (< i 16)
ac52e80b
LC
118 (mknod (string-append base (number->string i))
119 'block-special #o644 (device-number major (+ minor i)))
120 (loop (+ i 1)))))
121
97817e7f
DM
122;; Representation of a /dev node.
123(define-record-type <device-node>
124 (device-node name type major minor module)
125 device-node?
126 (name device-node-name)
127 (type device-node-type)
128 (major device-node-major)
129 (minor device-node-minor)
130 (module device-node-module))
131
132(define (read-static-device-nodes port)
133 "Read from PORT a list of <device-node> written in the format used by
134/lib/modules/*/*.devname files."
135 (let loop ((line (read-line port)))
136 (if (eof-object? line)
137 '()
138 (match (string-split line #\space)
139 (((? (cut string-prefix? "#" <>)) _ ...)
140 (loop (read-line port)))
141 ((module-name device-name device-spec)
142 (let* ((device-parts
143 (string-match "([bc])([0-9][0-9]*):([0-9][0-9]*)"
144 device-spec))
145 (type-string (match:substring device-parts 1))
146 (type (match type-string
147 ("c" 'char-special)
148 ("b" 'block-special)))
149 (major-string (match:substring device-parts 2))
150 (major (string->number major-string 10))
151 (minor-string (match:substring device-parts 3))
152 (minor (string->number minor-string 10)))
153 (cons (device-node device-name type major minor module-name)
154 (loop (read-line port)))))
155 (_
156 (begin
157 (format (current-error-port)
158 "read-static-device-nodes: ignored devname line '~a'~%" line)
159 (loop (read-line port))))))))
160
161(define* (mkdir-p* dir #:optional (mode #o755))
162 "This is a variant of 'mkdir-p' that works around
163<http://bugs.gnu.org/24659> by passing MODE explicitly in each 'mkdir' call."
164 (define absolute?
165 (string-prefix? "/" dir))
166
167 (define not-slash
168 (char-set-complement (char-set #\/)))
169
170 (let loop ((components (string-tokenize dir not-slash))
171 (root (if absolute?
172 ""
173 ".")))
174 (match components
175 ((head tail ...)
176 (let ((path (string-append root "/" head)))
177 (catch 'system-error
178 (lambda ()
179 (mkdir path mode)
180 (loop tail path))
181 (lambda args
182 (if (= EEXIST (system-error-errno args))
183 (loop tail path)
184 (apply throw args))))))
185 (() #t))))
186
187(define (report-system-error name . args)
188 "Report a system error for the file NAME."
189 (let ((errno (system-error-errno args)))
190 (format (current-error-port) "could not create '~a': ~a~%" name
191 (strerror errno))))
192
193;; Catch a system-error, log it and don't die from it.
194(define-syntax-rule (catch-system-error name exp)
195 (catch 'system-error
196 (lambda ()
197 exp)
198 (lambda args
199 (apply report-system-error name args))))
200
162a1374 201;; Create a device node like the <device-node> passed here on the file system.
97817e7f
DM
202(define create-device-node
203 (match-lambda
204 (($ <device-node> xname type major minor module)
205 (let ((name (string-append "/dev/" xname)))
206 (mkdir-p* (dirname name))
207 (catch-system-error name
208 (mknod name type #o600 (device-number major minor)))))))
209
210(define* (make-static-device-nodes linux-release-module-directory)
211 "Create static device nodes required by the given Linux release.
212This is required in order to solve a chicken-or-egg problem:
213The Linux kernel has a feature to autoload modules when a device is first
214accessed.
215And udev has a feature to set the permissions of static nodes correctly
216when it is starting up and also to automatically create nodes when hardware
217is hotplugged. That leaves universal device files which are not linked to
218one specific hardware device. These we have to create."
219 (let ((devname-name (string-append linux-release-module-directory "/"
220 "modules.devname")))
221 (for-each create-device-node
222 (call-with-input-file devname-name
223 read-static-device-nodes))))
224
d91712ee
LC
225(define* (make-essential-device-nodes #:key (root "/"))
226 "Make essential device nodes under ROOT/dev."
cc0e575a 227 ;; The hand-made devtmpfs/udev!
d91712ee
LC
228
229 (define (scope dir)
230 (string-append root
231 (if (string-suffix? "/" root)
232 ""
233 "/")
234 dir))
235
236 (unless (file-exists? (scope "dev"))
237 (mkdir (scope "dev")))
238
fc4bc4b6 239 ;; Make the device nodes for SCSI disks.
ac52e80b
LC
240 (make-disk-device-nodes (scope "dev/sda") 8)
241 (make-disk-device-nodes (scope "dev/sdb") 8 16)
242 (make-disk-device-nodes (scope "dev/sdc") 8 32)
243 (make-disk-device-nodes (scope "dev/sdd") 8 48)
244
245 ;; SCSI CD-ROM devices (aka. "/dev/sr0" etc.).
246 (mknod (scope "dev/scd0") 'block-special #o644 (device-number 11 0))
247 (mknod (scope "dev/scd1") 'block-special #o644 (device-number 11 1))
fc4bc4b6
LC
248
249 ;; The virtio (para-virtualized) block devices, as supported by QEMU/KVM.
ac52e80b 250 (make-disk-device-nodes (scope "dev/vda") 252)
d91712ee 251
c04c6ff6
LC
252 ;; Memory (used by Xorg's VESA driver.)
253 (mknod (scope "dev/mem") 'char-special #o640 (device-number 1 1))
254 (mknod (scope "dev/kmem") 'char-special #o640 (device-number 1 2))
255
1c221510
LC
256 ;; Inputs (used by Xorg.)
257 (unless (file-exists? (scope "dev/input"))
258 (mkdir (scope "dev/input")))
259 (mknod (scope "dev/input/mice") 'char-special #o640 (device-number 13 63))
260 (mknod (scope "dev/input/mouse0") 'char-special #o640 (device-number 13 32))
261 (mknod (scope "dev/input/event0") 'char-special #o640 (device-number 13 64))
262
9b4a163a
LC
263 ;; System console. This node is magically created by the kernel on the
264 ;; initrd's root, so don't try to create it in that case.
265 (unless (string=? root "/")
266 (mknod (scope "dev/console") 'char-special #o600
267 (device-number 5 1)))
268
d91712ee 269 ;; TTYs.
29804e6e
LC
270 (mknod (scope "dev/tty") 'char-special #o600
271 (device-number 5 0))
289773c1 272 (chmod (scope "dev/tty") #o666)
d91712ee
LC
273 (let loop ((n 0))
274 (and (< n 50)
275 (let ((name (format #f "dev/tty~a" n)))
29804e6e 276 (mknod (scope name) 'char-special #o600
d91712ee
LC
277 (device-number 4 n))
278 (loop (+ 1 n)))))
279
7f17ff78
LC
280 ;; Serial line.
281 (mknod (scope "dev/ttyS0") 'char-special #o660
282 (device-number 4 64))
283
c9c88118
LC
284 ;; Pseudo ttys.
285 (mknod (scope "dev/ptmx") 'char-special #o666
286 (device-number 5 2))
289773c1 287 (chmod (scope "dev/ptmx") #o666)
c9c88118 288
c865a878 289 ;; Create /dev/pts; it will be mounted later, at boot time.
c9c88118
LC
290 (unless (file-exists? (scope "dev/pts"))
291 (mkdir (scope "dev/pts")))
c9c88118 292
37c825eb
LC
293 ;; Rendez-vous point for syslogd.
294 (mknod (scope "dev/log") 'socket #o666 0)
295 (mknod (scope "dev/kmsg") 'char-special #o600 (device-number 1 11))
296
289773c1
LC
297 ;; Other useful nodes, notably relied on by guix-daemon.
298 (for-each (match-lambda
299 ((file major minor)
300 (mknod (scope file) 'char-special #o666
301 (device-number major minor))
302 (chmod (scope file) #o666)))
303 '(("dev/null" 1 3)
304 ("dev/zero" 1 5)
305 ("dev/full" 1 7)
306 ("dev/random" 1 8)
307 ("dev/urandom" 1 9)))
308
309 (symlink "/proc/self/fd" (scope "dev/fd"))
310 (symlink "/proc/self/fd/0" (scope "dev/stdin"))
311 (symlink "/proc/self/fd/1" (scope "dev/stdout"))
1c96c1bb
LC
312 (symlink "/proc/self/fd/2" (scope "dev/stderr"))
313
3035b50f
LC
314 ;; Loopback devices.
315 (let loop ((i 0))
316 (when (< i 8)
317 (mknod (scope (string-append "dev/loop" (number->string i)))
318 'block-special #o660
319 (device-number 7 i))
320 (loop (+ 1 i))))
321
1c96c1bb
LC
322 ;; File systems in user space (FUSE).
323 (mknod (scope "dev/fuse") 'char-special #o666 (device-number 10 229)))
d91712ee 324
88840f02
LC
325(define %host-qemu-ipv4-address
326 (inet-pton AF_INET "10.0.2.10"))
327
328(define* (configure-qemu-networking #:optional (interface "eth0"))
329 "Setup the INTERFACE network interface and /etc/resolv.conf according to
330QEMU's default networking settings (see net/slirp.c in QEMU for default
331networking values.) Return #t if INTERFACE is up, #f otherwise."
332 (display "configuring QEMU networking...\n")
333 (let* ((sock (socket AF_INET SOCK_STREAM 0))
334 (address (make-socket-address AF_INET %host-qemu-ipv4-address 0))
335 (flags (network-interface-flags sock interface)))
336 (set-network-interface-address sock interface address)
337 (set-network-interface-flags sock interface (logior flags IFF_UP))
338
c0b9213d
LC
339 ;; Hello! We used to create /etc/resolv.conf here, with "nameserver
340 ;; 10.0.2.3\n". However, with Linux-libre 3.16, we're getting ENOSPC.
341 ;; And since it's actually unnecessary, it's gone.
88840f02
LC
342
343 (logand (network-interface-flags sock interface) IFF_UP)))
344
88840f02
LC
345(define (device-number major minor)
346 "Return the device number for the device with MAJOR and MINOR, for use as
347the last argument of `mknod'."
348 (+ (* major 256) minor))
349
7d57cfd3
LC
350(define (pidof program)
351 "Return the PID of the first presumed instance of PROGRAM."
352 (let ((program (basename program)))
353 (find (lambda (pid)
354 (let ((exe (format #f "/proc/~a/exe" pid)))
355 (and=> (false-if-exception (readlink exe))
356 (compose (cut string=? program <>) basename))))
357 (filter-map string->number (scandir "/proc")))))
358
83bcd0b8 359(define* (mount-root-file-system root type
c8289690 360 #:key volatile-root?)
83bcd0b8 361 "Mount the root file system of type TYPE at device ROOT. If VOLATILE-ROOT?
41e03c4b
MC
362is true, mount ROOT read-only and make it an overlay with a writable tmpfs
363using the kernel built-in overlayfs."
364
4dfbdcbc
LC
365 (if volatile-root?
366 (begin
367 (mkdir-p "/real-root")
368 (mount root "/real-root" type MS_RDONLY)
369 (mkdir-p "/rw-root")
370 (mount "none" "/rw-root" "tmpfs")
371
c8289690
HG
372 ;; Create the upperdir and the workdir of the overlayfs
373 (mkdir-p "/rw-root/upper")
374 (mkdir-p "/rw-root/work")
375
4dfbdcbc 376 ;; We want read-write /dev nodes.
c8289690
HG
377 (mkdir-p "/rw-root/upper/dev")
378 (mount "none" "/rw-root/upper/dev" "devtmpfs")
379
380 ;; Make /root an overlay of the tmpfs and the actual root.
381 (mount "none" "/root" "overlay" 0
382 "lowerdir=/real-root,upperdir=/rw-root/upper,workdir=/rw-root/work"))
4dfbdcbc
LC
383 (begin
384 (check-file-system root type)
385 (mount root "/root" type)))
b1995341 386
9331ba5d 387 ;; Make sure /root/etc/mtab is a symlink to /proc/self/mounts.
01ed3c4f 388 (false-if-exception
9331ba5d 389 (delete-file "/root/etc/mtab"))
748d4a84 390 (mkdir-p "/root/etc")
9331ba5d 391 (symlink "/proc/self/mounts" "/root/etc/mtab"))
83bcd0b8 392
1d462832
LC
393(define (switch-root root)
394 "Switch to ROOT as the root file system, in a way similar to what
395util-linux' switch_root(8) does."
396 (move-essential-file-systems root)
397 (chdir root)
26a728eb
LC
398
399 ;; Since we're about to 'rm -rf /', try to make sure we're on an initrd.
400 ;; TODO: Use 'statfs' to check the fs type, like klibc does.
401 (when (or (not (file-exists? "/init")) (directory-exists? "/home"))
402 (format (current-error-port)
403 "The root file system is probably not an initrd; \
404bailing out.~%root contents: ~s~%" (scandir "/"))
405 (force-output (current-error-port))
406 (exit 1))
407
408 ;; Delete files from the old root, without crossing mount points (assuming
409 ;; there are no mount points in sub-directories.) That means we're leaving
410 ;; the empty ROOT directory behind us, but that's OK.
411 (let ((root-device (stat:dev (stat "/"))))
412 (for-each (lambda (file)
413 (unless (member file '("." ".."))
414 (let* ((file (string-append "/" file))
415 (device (stat:dev (lstat file))))
416 (when (= device root-device)
417 (delete-file-recursively file)))))
418 (scandir "/")))
419
420 ;; Make ROOT the new root.
1d462832 421 (mount root "/" "" MS_MOVE)
26a728eb
LC
422 (chroot ".")
423 (chdir "/")
424
425 (when (file-exists? "/dev/console")
426 ;; Close the standard file descriptors since they refer to the old
474b832d
LC
427 ;; /dev/console, and reopen them.
428 (let ((console (open-file "/dev/console" "r+b0")))
429 (for-each close-fdes '(0 1 2))
430
431 (dup2 (fileno console) 0)
432 (dup2 (fileno console) 1)
433 (dup2 (fileno console) 2)
434
435 (close-port console))))
1d462832 436
85a83edb 437\f
d4254711
LC
438(define* (boot-system #:key
439 (linux-modules '())
0e704a2d 440 linux-module-directory
ae7a316b 441 keymap-file
d4254711 442 qemu-guest-networking?
3c05b4bc 443 volatile-root?
de1c158f 444 pre-mount
aeed74f3
LC
445 (mounts '())
446 (on-error 'debug))
d4254711 447 "This procedure is meant to be called from an initrd. Boot a system by
0e704a2d 448first loading LINUX-MODULES (a list of module names) from
ae7a316b
LC
449LINUX-MODULE-DIRECTORY, then installing KEYMAP-FILE with 'loadkeys' (if
450KEYMAP-FILE is true), then setting up QEMU guest networking if
0e704a2d
LC
451QEMU-GUEST-NETWORKING? is true, calling PRE-MOUNT, mounting the file systems
452specified in MOUNTS, and finally booting into the new root if any. The initrd
453supports kernel command-line options '--load', '--root', and '--repl'.
d4254711 454
3c05b4bc
LC
455Mount the root file system, specified by the '--root' command-line argument,
456if any.
03ddfaf5 457
1c65cca5 458MOUNTS must be a list of <file-system> objects.
d4254711 459
44ddf33e 460When VOLATILE-ROOT? is true, the root file system is writable but any changes
aeed74f3
LC
461to it are lost.
462
463ON-ERROR is passed to 'call-with-error-handling'; it determines what happens
464upon error."
1c65cca5
LC
465 (define (root-mount-point? fs)
466 (string=? (file-system-mount-point fs) "/"))
3c05b4bc
LC
467
468 (define root-fs-type
1c65cca5
LC
469 (or (any (lambda (fs)
470 (and (root-mount-point? fs)
471 (file-system-type fs)))
3c05b4bc
LC
472 mounts)
473 "ext4"))
474
d4254711
LC
475 (display "Welcome, this is GNU's early boot Guile.\n")
476 (display "Use '--repl' for an initrd REPL.\n\n")
477
e3ced65a
LC
478 (call-with-error-handling
479 (lambda ()
480 (mount-essential-file-systems)
481 (let* ((args (linux-command-line))
482 (to-load (find-long-option "--load" args))
483 (root (find-long-option "--root" args)))
484
485 (when (member "--repl" args)
486 (start-repl))
487
488 (display "loading kernel modules...\n")
e1a9a7f2
LC
489 (load-linux-modules-from-directory linux-modules
490 linux-module-directory)
e3ced65a 491
ae7a316b
LC
492 (when keymap-file
493 (let ((status (system* "loadkeys" keymap-file)))
494 (unless (zero? status)
495 ;; Emit a warning rather than abort when we cannot load
496 ;; KEYMAP-FILE.
497 (format (current-error-port)
498 "warning: 'loadkeys' exited with status ~a~%"
499 status))))
500
e3ced65a
LC
501 (when qemu-guest-networking?
502 (unless (configure-qemu-networking)
503 (display "network interface is DOWN\n")))
504
e3ced65a
LC
505 ;; Prepare the real root file system under /root.
506 (unless (file-exists? "/root")
507 (mkdir "/root"))
67979e42
LC
508
509 (when (procedure? pre-mount)
510 ;; Do whatever actions are needed before mounting the root file
511 ;; system--e.g., installing device mappings. Error out when the
512 ;; return value is false.
513 (unless (pre-mount)
514 (error "pre-mount actions failed")))
515
aa901521
DM
516 (setenv "EXT2FS_NO_MTAB_OK" "1")
517
e3ced65a 518 (if root
a5acc17a
LC
519 ;; The "--root=SPEC" kernel command-line option always provides a
520 ;; string, but the string can represent a device, a UUID, or a
521 ;; label. So check for all three.
522 (let ((root (cond ((string-prefix? "/" root) root)
523 ((uuid root) => identity)
524 (else (file-system-label root)))))
525 (mount-root-file-system (canonicalize-device-spec root)
526 root-fs-type
527 #:volatile-root? volatile-root?))
e3ced65a
LC
528 (mount "none" "/root" "tmpfs"))
529
e3ced65a
LC
530 ;; Mount the specified file systems.
531 (for-each mount-file-system
532 (remove root-mount-point? mounts))
533
aa901521
DM
534 (setenv "EXT2FS_NO_MTAB_OK" #f)
535
e3ced65a
LC
536 (if to-load
537 (begin
538 (switch-root "/root")
539 (format #t "loading '~a'...\n" to-load)
540
e3ced65a
LC
541 (primitive-load to-load)
542
543 (format (current-error-port)
544 "boot program '~a' terminated, rebooting~%"
545 to-load)
546 (sleep 2)
547 (reboot))
548 (begin
549 (display "no boot file passed via '--load'\n")
550 (display "entering a warm and cozy REPL\n")
aeed74f3
LC
551 (start-repl)))))
552 #:on-error on-error))
d4254711 553
88840f02 554;;; linux-initrd.scm ends here