Merge branch 'master' into staging
[jackhill/guix/guix.git] / gnu / build / linux-boot.scm
CommitLineData
88840f02 1;;; GNU Guix --- Functional package management for GNU
aeed74f3 2;;; Copyright © 2013, 2014, 2015, 2016, 2017, 2018 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?
c8289690
HG
362is true, mount ROOT read-only and make it a overlay with a writable tmpfs
363using the kernel build-in overlayfs."
4dfbdcbc
LC
364 (if volatile-root?
365 (begin
366 (mkdir-p "/real-root")
367 (mount root "/real-root" type MS_RDONLY)
368 (mkdir-p "/rw-root")
369 (mount "none" "/rw-root" "tmpfs")
370
c8289690
HG
371 ;; Create the upperdir and the workdir of the overlayfs
372 (mkdir-p "/rw-root/upper")
373 (mkdir-p "/rw-root/work")
374
4dfbdcbc 375 ;; We want read-write /dev nodes.
c8289690
HG
376 (mkdir-p "/rw-root/upper/dev")
377 (mount "none" "/rw-root/upper/dev" "devtmpfs")
378
379 ;; Make /root an overlay of the tmpfs and the actual root.
380 (mount "none" "/root" "overlay" 0
381 "lowerdir=/real-root,upperdir=/rw-root/upper,workdir=/rw-root/work"))
4dfbdcbc
LC
382 (begin
383 (check-file-system root type)
384 (mount root "/root" type)))
b1995341 385
9331ba5d 386 ;; Make sure /root/etc/mtab is a symlink to /proc/self/mounts.
01ed3c4f 387 (false-if-exception
9331ba5d 388 (delete-file "/root/etc/mtab"))
748d4a84 389 (mkdir-p "/root/etc")
9331ba5d 390 (symlink "/proc/self/mounts" "/root/etc/mtab"))
83bcd0b8 391
1d462832
LC
392(define (switch-root root)
393 "Switch to ROOT as the root file system, in a way similar to what
394util-linux' switch_root(8) does."
395 (move-essential-file-systems root)
396 (chdir root)
26a728eb
LC
397
398 ;; Since we're about to 'rm -rf /', try to make sure we're on an initrd.
399 ;; TODO: Use 'statfs' to check the fs type, like klibc does.
400 (when (or (not (file-exists? "/init")) (directory-exists? "/home"))
401 (format (current-error-port)
402 "The root file system is probably not an initrd; \
403bailing out.~%root contents: ~s~%" (scandir "/"))
404 (force-output (current-error-port))
405 (exit 1))
406
407 ;; Delete files from the old root, without crossing mount points (assuming
408 ;; there are no mount points in sub-directories.) That means we're leaving
409 ;; the empty ROOT directory behind us, but that's OK.
410 (let ((root-device (stat:dev (stat "/"))))
411 (for-each (lambda (file)
412 (unless (member file '("." ".."))
413 (let* ((file (string-append "/" file))
414 (device (stat:dev (lstat file))))
415 (when (= device root-device)
416 (delete-file-recursively file)))))
417 (scandir "/")))
418
419 ;; Make ROOT the new root.
1d462832 420 (mount root "/" "" MS_MOVE)
26a728eb
LC
421 (chroot ".")
422 (chdir "/")
423
424 (when (file-exists? "/dev/console")
425 ;; Close the standard file descriptors since they refer to the old
474b832d
LC
426 ;; /dev/console, and reopen them.
427 (let ((console (open-file "/dev/console" "r+b0")))
428 (for-each close-fdes '(0 1 2))
429
430 (dup2 (fileno console) 0)
431 (dup2 (fileno console) 1)
432 (dup2 (fileno console) 2)
433
434 (close-port console))))
1d462832 435
85a83edb 436\f
d4254711
LC
437(define* (boot-system #:key
438 (linux-modules '())
0e704a2d 439 linux-module-directory
d4254711 440 qemu-guest-networking?
3c05b4bc 441 volatile-root?
de1c158f 442 pre-mount
aeed74f3
LC
443 (mounts '())
444 (on-error 'debug))
d4254711 445 "This procedure is meant to be called from an initrd. Boot a system by
0e704a2d
LC
446first loading LINUX-MODULES (a list of module names) from
447LINUX-MODULE-DIRECTORY, then setting up QEMU guest networking if
448QEMU-GUEST-NETWORKING? is true, calling PRE-MOUNT, mounting the file systems
449specified in MOUNTS, and finally booting into the new root if any. The initrd
450supports kernel command-line options '--load', '--root', and '--repl'.
d4254711 451
3c05b4bc
LC
452Mount the root file system, specified by the '--root' command-line argument,
453if any.
03ddfaf5 454
1c65cca5 455MOUNTS must be a list of <file-system> objects.
d4254711 456
44ddf33e 457When VOLATILE-ROOT? is true, the root file system is writable but any changes
aeed74f3
LC
458to it are lost.
459
460ON-ERROR is passed to 'call-with-error-handling'; it determines what happens
461upon error."
1c65cca5
LC
462 (define (root-mount-point? fs)
463 (string=? (file-system-mount-point fs) "/"))
3c05b4bc
LC
464
465 (define root-fs-type
1c65cca5
LC
466 (or (any (lambda (fs)
467 (and (root-mount-point? fs)
468 (file-system-type fs)))
3c05b4bc
LC
469 mounts)
470 "ext4"))
471
0e704a2d
LC
472 (define (lookup-module name)
473 (string-append linux-module-directory "/"
474 (ensure-dot-ko name)))
475
d4254711
LC
476 (display "Welcome, this is GNU's early boot Guile.\n")
477 (display "Use '--repl' for an initrd REPL.\n\n")
478
e3ced65a
LC
479 (call-with-error-handling
480 (lambda ()
481 (mount-essential-file-systems)
482 (let* ((args (linux-command-line))
483 (to-load (find-long-option "--load" args))
484 (root (find-long-option "--root" args)))
485
486 (when (member "--repl" args)
487 (start-repl))
488
489 (display "loading kernel modules...\n")
0e704a2d
LC
490 (for-each (cut load-linux-module* <>
491 #:lookup-module lookup-module)
492 (map lookup-module linux-modules))
e3ced65a
LC
493
494 (when qemu-guest-networking?
495 (unless (configure-qemu-networking)
496 (display "network interface is DOWN\n")))
497
e3ced65a
LC
498 ;; Prepare the real root file system under /root.
499 (unless (file-exists? "/root")
500 (mkdir "/root"))
67979e42
LC
501
502 (when (procedure? pre-mount)
503 ;; Do whatever actions are needed before mounting the root file
504 ;; system--e.g., installing device mappings. Error out when the
505 ;; return value is false.
506 (unless (pre-mount)
507 (error "pre-mount actions failed")))
508
e3ced65a 509 (if root
a5acc17a
LC
510 ;; The "--root=SPEC" kernel command-line option always provides a
511 ;; string, but the string can represent a device, a UUID, or a
512 ;; label. So check for all three.
513 (let ((root (cond ((string-prefix? "/" root) root)
514 ((uuid root) => identity)
515 (else (file-system-label root)))))
516 (mount-root-file-system (canonicalize-device-spec root)
517 root-fs-type
518 #:volatile-root? volatile-root?))
e3ced65a
LC
519 (mount "none" "/root" "tmpfs"))
520
e3ced65a
LC
521 ;; Mount the specified file systems.
522 (for-each mount-file-system
523 (remove root-mount-point? mounts))
524
e3ced65a
LC
525 (if to-load
526 (begin
527 (switch-root "/root")
528 (format #t "loading '~a'...\n" to-load)
529
e3ced65a
LC
530 (primitive-load to-load)
531
532 (format (current-error-port)
533 "boot program '~a' terminated, rebooting~%"
534 to-load)
535 (sleep 2)
536 (reboot))
537 (begin
538 (display "no boot file passed via '--load'\n")
539 (display "entering a warm and cozy REPL\n")
aeed74f3
LC
540 (start-repl)))))
541 #:on-error on-error))
d4254711 542
88840f02 543;;; linux-initrd.scm ends here