linux-boot.scm 21 KB

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