linux-boot.scm 19 KB

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