Subject: [PATCH v11 3/6] linux-modules: Add 'load-needed-linux-modules'.

From: Ludovic Courtès <[email-masked]>
Date: Mon, 12 Mar 2018 23:15:38 +0100

Based on a patch by Danny Milosavljevic <[email-masked]>.

* gnu/build/linux-modules.scm (load-needed-linux-modules): New
procedure.
---
 gnu/build/linux-modules.scm | 34 +++++++++++++++++++++++++++++++++-
 1 file changed, 33 insertions(+), 1 deletion(-)

diff --git a/gnu/build/linux-modules.scm b/gnu/build/linux-modules.scm
index 0084f972b..55161e026 100644
--- a/gnu/build/linux-modules.scm
+++ b/gnu/build/linux-modules.scm
@@ -30,6 +30,7 @@
   #:use-module (ice-9 vlist)
   #:use-module (ice-9 match)
   #:use-module (ice-9 rdelim)
+  #:use-module (ice-9 ftw)
   #:export (dot-ko
             ensure-dot-ko
             module-aliases
@@ -45,7 +46,8 @@
             device-module-aliases
             known-module-aliases
             matching-modules
-            write-module-alias-database))
+            write-module-alias-database
+            load-needed-linux-modules))
 
 ;;; Commentary:
 ;;;
@@ -413,4 +415,34 @@ ALIAS is a string like \"scsi:t-0x00\" as returned by
                              aliases)))
                 aliases))))
 
+(define (load-needed-linux-modules module-directory)
+  "Examine /sys/devices to find out which modules are needed and load those we
+have in MODULE-DIRECTORY.  Return the list of modules loaded, not including
+dependencies.
+
+Note: loading modules leads to the creation of new entries in /sys/devices,
+which is why we need traversal and loading to be interleaved.  If we walked
+/sys/devices and *then* loaded modules, we'd miss the entries added as a
+side-effect and would thus need to traverse /sys/devices again."
+  (define aliases
+    (known-module-aliases
+     (string-append module-directory "/modules.alias")))
+
+  (define (enter? director stat result) result)
+  (define (down directory stat result) result)
+  (define (up directory stat result) result)
+  (define (skip entry stat result) result)
+  (define (error name stat errno result) result)
+  (define (leaf file stat result)
+    (if (string=? (basename file) "modalias")
+        (let* ((alias   (string-trim-right
+                         (call-with-input-file file get-string-all)))
+               (modules (matching-modules alias aliases)))
+          (load-linux-modules-from-directory modules
+                                             module-directory)
+          (append modules result))
+        result))
+
+  (file-system-fold enter? leaf down up skip error #t "/sys/devices"))
+
 ;;; linux-modules.scm ends here
-- 
2.16.2