Merge branch 'master' into core-updates
[jackhill/guix/guix.git] / gnu / build / linux-modules.scm
1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2014, 2016, 2018 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
20 (define-module (gnu build linux-modules)
21 #:use-module (guix elf)
22 #:use-module (guix glob)
23 #:use-module (guix build syscalls)
24 #:use-module (rnrs io ports)
25 #:use-module (rnrs bytevectors)
26 #:use-module (srfi srfi-1)
27 #:use-module (srfi srfi-26)
28 #:use-module (ice-9 vlist)
29 #:use-module (ice-9 match)
30 #:use-module (ice-9 rdelim)
31 #:export (dot-ko
32 ensure-dot-ko
33 module-aliases
34 module-dependencies
35 normalize-module-name
36 recursive-module-dependencies
37 modules-loaded
38 module-loaded?
39 load-linux-module*
40
41 current-module-debugging-port
42
43 device-module-aliases
44 known-module-aliases
45 matching-modules))
46
47 ;;; Commentary:
48 ;;;
49 ;;; Tools to deal with Linux kernel modules.
50 ;;;
51 ;;; Code:
52
53 (define current-module-debugging-port
54 (make-parameter (%make-void-port "w")))
55
56 (define (section-contents elf section)
57 "Return the contents of SECTION in ELF as a bytevector."
58 (let* ((modinfo (elf-section-by-name elf ".modinfo"))
59 (contents (make-bytevector (elf-section-size modinfo))))
60 (bytevector-copy! (elf-bytes elf) (elf-section-offset modinfo)
61 contents 0
62 (elf-section-size modinfo))
63 contents))
64
65 (define %not-nul
66 (char-set-complement (char-set #\nul)))
67
68 (define (nul-separated-string->list str)
69 "Split STR at occurrences of the NUL character and return the resulting
70 string list."
71 (string-tokenize str %not-nul))
72
73 (define (key=value->pair str)
74 "Assuming STR has the form \"KEY=VALUE\", return a pair like (KEY
75 . \"VALUE\")."
76 (let ((= (string-index str #\=)))
77 (cons (string->symbol (string-take str =))
78 (string-drop str (+ 1 =)))))
79
80 (define (modinfo-section-contents file)
81 "Return the contents of the '.modinfo' section of FILE as a list of
82 key/value pairs.."
83 (let* ((bv (call-with-input-file file get-bytevector-all))
84 (elf (parse-elf bv))
85 (modinfo (section-contents elf ".modinfo")))
86 (map key=value->pair
87 (nul-separated-string->list (utf8->string modinfo)))))
88
89 (define %not-comma
90 (char-set-complement (char-set #\,)))
91
92 (define (module-dependencies file)
93 "Return the list of modules that FILE depends on. The returned list
94 contains module names, not actual file names."
95 (let ((info (modinfo-section-contents file)))
96 (match (assq 'depends info)
97 (('depends . what)
98 (string-tokenize what %not-comma)))))
99
100 (define (module-aliases file)
101 "Return the list of aliases of module FILE."
102 (let ((info (modinfo-section-contents file)))
103 (filter-map (match-lambda
104 (('alias . value)
105 value)
106 (_ #f))
107 (modinfo-section-contents file))))
108
109 (define dot-ko
110 (cut string-append <> ".ko"))
111
112 (define (ensure-dot-ko name)
113 "Return NAME with a '.ko' prefix appended, unless it already has it."
114 (if (string-suffix? ".ko" name)
115 name
116 (dot-ko name)))
117
118 (define (normalize-module-name module)
119 "Return the \"canonical\" name for MODULE, replacing hyphens with
120 underscores."
121 ;; See 'modname_normalize' in libkmod.
122 (string-map (lambda (chr)
123 (case chr
124 ((#\-) #\_)
125 (else chr)))
126 module))
127
128 (define (file-name->module-name file)
129 "Return the module name corresponding to FILE, stripping the trailing '.ko'
130 and normalizing it."
131 (normalize-module-name (basename file ".ko")))
132
133 (define* (recursive-module-dependencies files
134 #:key (lookup-module dot-ko))
135 "Return the topologically-sorted list of file names of the modules depended
136 on by FILES, recursively. File names of modules are determined by applying
137 LOOKUP-MODULE to the module name."
138 (let loop ((files files)
139 (result '())
140 (visited vlist-null))
141 (match files
142 (()
143 (delete-duplicates (reverse result)))
144 ((head . tail)
145 (let* ((visited? (vhash-assoc head visited))
146 (deps (if visited?
147 '()
148 (map lookup-module (module-dependencies head))))
149 (visited (if visited?
150 visited
151 (vhash-cons head #t visited))))
152 (loop (append deps tail)
153 (append result deps) visited))))))
154
155 (define %not-newline
156 (char-set-complement (char-set #\newline)))
157
158 (define (modules-loaded)
159 "Return the list of names of currently loaded Linux modules."
160 (let* ((contents (call-with-input-file "/proc/modules"
161 get-string-all))
162 (lines (string-tokenize contents %not-newline)))
163 (match (map string-tokenize lines)
164 (((modules . _) ...)
165 modules))))
166
167 (define (module-black-list)
168 "Return the black list of modules that must not be loaded. This black list
169 is specified using 'modprobe.blacklist=MODULE1,MODULE2,...' on the kernel
170 command line; it is honored by libkmod for users that pass
171 'KMOD_PROBE_APPLY_BLACKLIST', which includes 'modprobe --use-blacklist' and
172 udev."
173 (define parameter
174 "modprobe.blacklist=")
175
176 (let ((command (call-with-input-file "/proc/cmdline"
177 get-string-all)))
178 (append-map (lambda (arg)
179 (if (string-prefix? parameter arg)
180 (string-tokenize (string-drop arg (string-length parameter))
181 %not-comma)
182 '()))
183 (string-tokenize command))))
184
185 (define (module-loaded? module)
186 "Return #t if MODULE is already loaded. MODULE must be a Linux module name,
187 not a file name."
188 (member module (modules-loaded)))
189
190 (define* (load-linux-module* file
191 #:key
192 (recursive? #t)
193 (lookup-module dot-ko)
194 (black-list (module-black-list)))
195 "Load Linux module from FILE, the name of a '.ko' file; return true on
196 success, false otherwise. When RECURSIVE? is true, load its dependencies
197 first (à la 'modprobe'.) The actual files containing modules depended on are
198 obtained by calling LOOKUP-MODULE with the module name. Modules whose name
199 appears in BLACK-LIST are not loaded."
200 (define (black-listed? module)
201 (let ((result (member module black-list)))
202 (when result
203 (format (current-module-debugging-port)
204 "not loading module '~a' because it's black-listed~%"
205 module))
206 result))
207
208 (define (load-dependencies file)
209 (let ((dependencies (module-dependencies file)))
210 (every (cut load-linux-module* <>
211 #:lookup-module lookup-module
212 #:black-list black-list)
213 (map lookup-module dependencies))))
214
215 (and (not (black-listed? (file-name->module-name file)))
216 (or (not recursive?)
217 (load-dependencies file))
218 (let ((fd #f))
219 (format (current-module-debugging-port)
220 "loading Linux module from '~a'...~%" file)
221
222 (catch 'system-error
223 (lambda ()
224 (set! fd (open-fdes file O_RDONLY))
225 (load-linux-module/fd fd)
226 (close-fdes fd)
227 #t)
228 (lambda args
229 ;; If this module was already loaded and we're in modprobe style, ignore
230 ;; the error.
231 (when fd (close-fdes fd))
232 (or (and recursive? (= EEXIST (system-error-errno args)))
233 (apply throw args)))))))
234
235 \f
236 ;;;
237 ;;; Device modules.
238 ;;;
239
240 ;; Copied from (guix utils). FIXME: Factorize.
241 (define (readlink* file)
242 "Call 'readlink' until the result is not a symlink."
243 (define %max-symlink-depth 50)
244
245 (let loop ((file file)
246 (depth 0))
247 (define (absolute target)
248 (if (absolute-file-name? target)
249 target
250 (string-append (dirname file) "/" target)))
251
252 (if (>= depth %max-symlink-depth)
253 file
254 (call-with-values
255 (lambda ()
256 (catch 'system-error
257 (lambda ()
258 (values #t (readlink file)))
259 (lambda args
260 (let ((errno (system-error-errno args)))
261 (if (or (= errno EINVAL))
262 (values #f file)
263 (apply throw args))))))
264 (lambda (success? target)
265 (if success?
266 (loop (absolute target) (+ depth 1))
267 file))))))
268
269 ;; See 'major' and 'minor' in <sys/sysmacros.h>.
270
271 (define (stat->device-major st)
272 (ash (logand #xfff00 (stat:rdev st)) -8))
273
274 (define (stat->device-minor st)
275 (logand #xff (stat:rdev st)))
276
277 (define %not-slash
278 (char-set-complement (char-set #\/)))
279
280 (define (read-uevent port)
281 "Read a /sys 'uevent' file from PORT and return an alist where each car is a
282 key such as 'MAJOR or 'DEVTYPE and each cdr is the corresponding value."
283 (let loop ((result '()))
284 (match (read-line port)
285 ((? eof-object?)
286 (reverse result))
287 (line
288 (loop (cons (key=value->pair line) result))))))
289
290 (define (device-module-aliases device)
291 "Return the list of module aliases required by DEVICE, a /dev file name, as
292 in this example:
293
294 (device-module-aliases \"/dev/sda\")
295 => (\"scsi:t-0x00\" \"pci:v00008086d00009D03sv0000103Csd000080FAbc01sc06i01\")
296
297 The modules corresponding to these aliases can then be found using
298 'matching-modules'."
299 ;; The approach is adapted from
300 ;; <https://unix.stackexchange.com/questions/97676/how-to-find-the-driver-module-associated-with-a-device-on-linux>.
301 (let* ((st (stat device))
302 (type (stat:type st))
303 (major (stat->device-major st))
304 (minor (stat->device-minor st))
305 (sys-name (string-append "/sys/dev/"
306 (case type
307 ((block-special) "block")
308 ((char-special) "char")
309 (else (symbol->string type)))
310 "/" (number->string major) ":"
311 (number->string minor)))
312 (directory (canonicalize-path (readlink* sys-name))))
313 (let loop ((components (string-tokenize directory %not-slash))
314 (aliases '()))
315 (match components
316 (("sys" "devices" _)
317 (reverse aliases))
318 ((head ... _)
319 (let ((uevent (string-append (string-join components "/" 'prefix)
320 "/uevent")))
321 (if (file-exists? uevent)
322 (let ((props (call-with-input-file uevent read-uevent)))
323 (match (assq-ref props 'MODALIAS)
324 (#f (loop head aliases))
325 (alias (loop head (cons alias aliases)))))
326 (loop head aliases))))))))
327
328 (define (read-module-aliases port)
329 "Read from PORT data in the Linux 'modules.alias' file format. Return a
330 list of alias/module pairs where each alias is a glob pattern as like the
331 result of:
332
333 (string->compiled-sglob \"scsi:t-0x01*\")
334
335 and each module is a module name like \"snd_hda_intel\"."
336 (define (comment? str)
337 (string-prefix? "#" str))
338
339 (define (tokenize str)
340 ;; Lines have the form "alias ALIAS MODULE", where ALIAS can contain
341 ;; whitespace. This is why we don't use 'string-tokenize'.
342 (let* ((str (string-trim-both str))
343 (left (string-index str #\space))
344 (right (string-rindex str #\space)))
345 (list (string-take str left)
346 (string-trim-both (substring str left right))
347 (string-trim-both (string-drop str right)))))
348
349 (let loop ((aliases '()))
350 (match (read-line port)
351 ((? eof-object?)
352 (reverse aliases))
353 ((? comment?)
354 (loop aliases))
355 (line
356 (match (tokenize line)
357 (("alias" alias module)
358 (loop (alist-cons (string->compiled-sglob alias) module
359 aliases)))
360 (() ;empty line
361 (loop aliases)))))))
362
363 (define (current-kernel-directory)
364 "Return the directory of the currently running Linux kernel."
365 (string-append (or (getenv "LINUX_MODULE_DIRECTORY")
366 "/run/booted-system/kernel/lib/modules")
367 "/" (utsname:release (uname))))
368
369 (define (current-alias-file)
370 "Return the absolute file name of the default 'modules.alias' file."
371 (string-append (current-kernel-directory) "/modules.alias"))
372
373 (define* (known-module-aliases #:optional (alias-file (current-alias-file)))
374 "Return the list of alias/module pairs read from ALIAS-FILE. Each alias is
375 actually a pattern."
376 (call-with-input-file alias-file read-module-aliases))
377
378 (define* (matching-modules alias
379 #:optional (known-aliases (known-module-aliases)))
380 "Return the list of modules that match ALIAS according to KNOWN-ALIASES.
381 ALIAS is a string like \"scsi:t-0x00\" as returned by
382 'device-module-aliases'."
383 (filter-map (match-lambda
384 ((pattern . module)
385 (and (glob-match? pattern alias)
386 module)))
387 known-aliases))
388
389 ;;; linux-modules.scm ends here