Fixed kernel module compilation if invoked by mount(8).
[lufs.git] / kernel / Linux / prepmod.in
1 #! /usr/bin/perl -w
2
3 # $Id$
4 # Check and possibly rebuild lufs kernel module for the current kernel.
5 # Copyright (C) 2003 Jan Kratochvil <project-captive@jankratochvil.net>
6
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; exactly version 2 of June 1991 is required
10
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
20
21 use strict;
22 use Carp qw(cluck confess);
23 use Getopt::Long;
24 # Do not use any non-core Perl modules here.
25 # Be perl-5.0 compatible (is it needed if we require Linux kernel >= 2.4 ?)
26
27
28 my $basedir='@datadir@/lufs';
29 my $vardir='@localstatedir@/lib/lufs';
30 $basedir=~s#\$\Q{prefix}\E#'@prefix@';#ge;
31 $vardir=~s#\$\Q{prefix}\E#'@prefix@';#ge;
32 $vardir="" if $vardir=~/^@/;
33 sub srcdir { my($uname_r)=@_; $basedir."/".($uname_r lt "2.5" ? "2.4" : "2.6"); }
34 my $modbindir=$basedir."/modbin";
35 my @sources=qw(proc.c inode.c dir.c file.c symlink.c);
36
37 my $quiet;
38 my $kernel;
39 my $prebuild;
40 use vars qw($kernel_gcc_args);
41 $kernel_gcc_args="";
42
43 sub modext { my($uname_r)=@_; ($uname_r lt "2.5" ? "o" : "ko"); }
44
45 # mount(8) will util-linux/lib/env.c/sanitize_env()
46 # including the clearance our $PATH:
47 $ENV{"PATH"}=join(":",qw(/usr/local/bin /usr/bin /bin),$ENV{"PATH"});
48
49 my $lufsd_bin;
50 if ($0 eq "lufsd" || $0=~m#/lufsd$#) {
51         $quiet=1;
52         $lufsd_bin='@bindir@/lufsd-bin';
53         $lufsd_bin=~s#\$\Q{exec_prefix}\E#'@exec_prefix@';#ge;
54         $lufsd_bin=~s#\$\Q{prefix}\E#'@prefix@';#ge;
55         }
56 else {
57         die if !GetOptions(
58                         "q|quiet",\$quiet,
59                           "kernel",\$kernel,    # it must contain "include" subdir
60                           "modbindir=s",\$modbindir,
61                           "basedir=s",\$basedir,
62                           "prebuild",\&prebuild,
63                           "kernel-gcc-args=s",\$kernel_gcc_args,
64                         );
65         }
66
67
68 sub _readfile
69 {
70 my($filename,$optional)=@_;
71
72         local $/=undef();
73         local *F;
74         open F,$filename or do { cluck "Open \"$filename\": $!" if !$optional; return ""; };
75         my $r=<F>;
76         close F or cluck "Close \"$filename\": $!";
77         return $r;
78 }
79
80 sub _writefile
81 {
82 my($filename,@content)=@_;
83
84         local *F;
85         open F,($filename=~/^[|]/ ? "" : ">").$filename or confess "rewrite \"$filename\": $!";
86         print F @content;
87         close F or confess "close \"$filename\": $!";   # Do not &cluck as it may be pipe result
88 }
89
90 sub _system
91 {
92 my(@args)=@_;
93
94         print STDERR "+ ".join(" ",@args)."\n" if !$quiet;
95         return system @args;
96 }
97
98 sub _pass
99 {
100 my($load)=@_;
101
102         my $modproberc;
103         if ($load) {
104                 do { ($modproberc=_system $_) and cluck "$_ failed - ignoring"; }
105                                 for ("/sbin/depmod -aq","/sbin/modprobe lufs");
106                 }
107         exit ($modproberc ? 1 : 0) if !$lufsd_bin;
108         do { exec $lufsd_bin,@ARGV; };
109         confess "Failed to exec '$lufsd_bin': $!";
110 }
111
112
113 my $filesystems=_readfile "/proc/filesystems";  # 'lufs' may be built-in
114 _pass if $filesystems=~/\blufs$/m;
115 my $modules=_readfile "/proc/modules";  # 'lufs' may be already loaded
116 _pass if $modules=~/^lufs\b/m;
117 _pass if !_system "/sbin/modprobe lufs 2>/dev/null";
118
119 my $proc_version=_readfile "/proc/version";
120 my $uname_r=($proc_version=~/^Linux version (\S+)/)[0] || _readfile "uname -r|";
121 chomp $uname_r;
122 confess "Failed to detect kernel version" if !$uname_r;
123 my $uname_smp=($uname_r=~s/smp$// && "smp");
124 my $uname_r_base=($uname_r=~/^([^-]+)/)[0];
125 print STDERR "Running kernel version: $uname_r (base version $uname_r_base)\n" if !$quiet;
126
127 my $lufs_o="lufs.".modext($uname_r);
128
129 my $moduledir="/lib/modules/$uname_r$uname_smp/kernel/fs/lufs";
130 print STDERR "Destination module directory: $moduledir\n" if !$quiet;
131
132 my @kernel_paths=(
133                                 "/lib/modules/$uname_r/build",
134                                 "/usr/src/kernel-headers-$uname_r",
135                                 "/usr/src/linux-$uname_r",
136                                 "/usr/src/linux-$uname_r_base",
137                                 "/usr/src/linux",
138                                 "/usr/src/kernel-source-$uname_r",      # no .config?
139                                 );
140 do { $kernel||=$_ if -d $_; } for (@kernel_paths);
141 if (!$kernel) {
142         print STDERR "Failed to find kernel headers for $uname_r\n" if !$kernel && !$quiet;
143         }
144 else {
145         # We need /usr/include/lufs/* for standard package compilation.
146         # There is no sense to make separate 'devel' package.
147         for ("$vardir/$lufs_o") {
148                 next if !$vardir;
149                 # Create the 'lufs.o' in our /var/lib directory and only link it
150                 # to prevent using obsolete modules after upgrading 'lufs' package.
151                 # depmod(1) will take the larget symlink name - we must create directory for  it.
152                 if (build($kernel,$uname_r,$_)) {
153                         do { cluck "Failed to symlink $_"; next; }
154                                         if _system "/bin/rm -rf $moduledir; /bin/mkdir -p $moduledir; /bin/ln -s $_ $moduledir/$lufs_o";
155                         _pass 1;
156                         }
157                 }
158         }
159
160 local $_;
161 for (<$modbindir/*-$uname_r*/$lufs_o>,<$modbindir/*-${uname_r_base}*/$lufs_o>,<$modbindir/*/$lufs_o>) {
162         # Do not: /sbin/insmod -o lufs -p $_ 2>/dev/null
163         # as 2.6 insmod has no options at all.
164         next if _system "/sbin/rmmod lufs 2>/dev/null; /sbin/insmod $_ 2>/dev/null";
165         do { cluck "Failed to symlink $_"; next; }
166                         if _system "/bin/rm -rf $moduledir; /bin/mkdir -p $moduledir; /bin/ln -s $_ $moduledir/$lufs_o";
167         # 0 as already insmod(8)ed.
168         _pass 0;
169         }
170 confess "lufs module not loaded: Try running $basedir/prepmod to see more." if $quiet;
171 confess "Failed to prepare $lufs_o module for your Linux kernel $uname_r.\n"
172                 .($kernel ? "Detected Linux kernel sources \"$kernel\" do not appear to be valid.\n"
173                                 : "No Linux kernel sources for your running kernel were found.\n")
174                 ."Please install kernel-source-x.y.z.i386.rpm or kernel-headers_x.y.z_i386.deb.\n"
175                 ."The following directory paths were search (first existing directory used):\n"
176                 .join("",map("\t\t$_\n",@kernel_paths));
177
178
179 sub build_gcc
180 {
181 my($kernel,$uname_r,$destmodule)=@_;
182
183         print STDERR "Using kernel sources: $kernel\n" if !$quiet;
184         confess "Kernel sources $kernel do not contain 'include' subdirectory" if ! -d $kernel."/include";
185
186         my $kdebug="";
187         do { $kdebug=$_ if !/^@/; } for ('@KDEBUG_FLAGS@');
188         my $cmdline="/usr/bin/gcc"
189                         .($quiet ? " 2>/dev/null" : "")
190                         ." -Wall -Wstrict-prototypes -Wno-trigraphs"
191                         ." -O2 -fno-strict-aliasing -fno-common -fomit-frame-pointer -pipe -mpreferred-stack-boundary=2"
192                         #." -march=i586"
193                         ." -D__KERNEL__ -DMODULE -DLINUX -DKBUILD_MODNAME=lufs"
194                         ." ".$kdebug
195                         ." ".$kernel_gcc_args
196                         ." -I$kernel/include"
197                         ." -I$kernel/include/asm-i386/mach-default";    # gcc should not care if this 2.6 dir does not exist
198
199         my $config=_readfile "$kernel/.config","optional";
200         my $autoconf=_readfile "$kernel/include/linux/autoconf.h","optional";
201         if (0
202                         || $config=~/^CONFIG_MODVERSIONS=y\b/m
203                         || $autoconf=~/^#define CONFIG_MODVERSIONS\b/m
204                         || (!$config && !$autoconf)) {  # assume modversions if not known
205                 $cmdline.=" -DMODVERSIONS";
206                 $cmdline.=" -include $kernel/include/linux/version.h"
207                                 if -f "$kernel/include/linux/version.h";
208                 $cmdline.=" -include $kernel/include/linux/modversions.h";
209                 }
210
211         my @objects=map({ my $o=$_; $o=~s/[.]c$/.o/; $o; } @sources);
212         return !_system "set -e; /bin/mkdir -p `dirname $destmodule`; /bin/rm -f $destmodule;"
213                         .(!$vardir ? "" : " cd $vardir;")
214                         ." $cmdline -c ".join(" ",map({ srcdir($uname_r)."/".$_; } @sources)).";"
215                         ." /usr/bin/ld -r -o $destmodule ".join(" ",@objects).";"
216                         ." /bin/rm -f ".join(" ",@objects);
217 }
218
219
220 sub build_make
221 {
222 my($kernel,$uname_r,$destmodule,%args)=@_;
223
224         print STDERR "Using kernel sources: $kernel\n" if !$quiet;
225         # 'Rules.make' not present in 2.6+ kernels
226         do { confess "Kernel sources $kernel do not contain '$_' file" if ! -f $_; } for ($kernel."/arch/i386/Makefile");
227
228         my $kdebug="";
229         do { $kdebug=$_ if !/^@/; } for ('@KDEBUG_FLAGS@');
230         my $predir=srcdir $uname_r;
231         $predir=$ENV{"PWD"}."/$predir" if $predir!~m#^/#;
232         # Workaround a bug in at least Red Hat 2.4.18-18.8.0
233         if (-f "$kernel/include/linux/version.h") {
234                 for ("$kernel/include/linux/modversions.h") {
235                         _system "cp -p $_ $_-orig" if ! -f "$_-orig";
236                         _writefile $_,"#include <linux/version.h>\t/* lufs */\n"._readfile $_;
237                         }
238                 }
239         my $cmdline="make -C $kernel"
240                         ." SUBDIRS=\"$predir\" modules"
241                         ." EXTRA_CFLAGS=\"$kernel_gcc_args\""
242                         .($quiet ? ' &>/dev/null' : '');
243         my @objects=map({ my $o=$_; $o=~s/[.]c$/.o/; $o; } @sources,"lufs.mod.c","lufs.c");
244         $cmdline="set -e; /bin/mkdir -p `dirname $destmodule`; /bin/rm -f $destmodule;"
245                         ." $cmdline;"
246                         ." /bin/mv -f $predir/lufs.".modext($uname_r)." $destmodule;"
247                         ." /bin/rm -f ".join(" ",map(("$predir/$_","$predir/.$_.flags","$predir/.$_.cmd"),@objects),"$predir/lufs.mod.c","$predir/.lufs.ko.cmd").";";
248         my $r=!_system $cmdline;
249         return $r if $r;
250         # Rebuild existing '$kernel/tmp_include_depends' or '$kernel/.depend'
251         # as it may contain non-existing pathnames:
252         _system "make -C $kernel dep"
253                                 .($quiet ? ' &>/dev/null' : '');
254         return !_system $cmdline;
255 }
256
257
258 sub build
259 {
260 my($kernel,$uname_r,$destmodule,%args)=@_;
261
262         # Debian uname(1) does not support '-p'.
263         my $arch=_readfile "uname -p 2>/dev/null || true|"
264                         || _readfile "uname -m|";
265         chomp $arch;
266         my $single_config=-f "$kernel/.config";
267         if (!$single_config) {
268                 my $spec_config="$kernel/configs/kernel-$uname_r_base-$arch".($uname_smp ? "-smp" : "").".config";
269                 _system "ln -s $spec_config $kernel/.config"
270                                 if -f $spec_config;
271                 }
272         my $r;
273         # 'Rules.make' not present in 2.6+ kernels
274         if (-f $kernel."/arch/i386/Makefile" && -f "$kernel/.config")
275                 { $r=build_make $kernel,$uname_r,$destmodule,%args; }
276         else
277                 { $r=build_gcc $kernel,$uname_r,$destmodule,%args; }
278         _system "rm -f $kernel/.config"
279                         if !$single_config;
280         return $r;
281 }
282
283
284 sub prebuild_kernel
285 {
286 my($dir,$vendor,$uname_r,%args)=@_;
287
288         confess "Unrecognized vendor for dir: $dir" if !$vendor;
289         confess "Unrecognized uname_r for dir: $dir" if !$uname_r;
290         confess "Failed to build $dir" if !build $dir,$uname_r,$modbindir."/lufs-$vendor-$uname_r.".modext($uname_r),%args;
291 }
292
293
294 sub prebuild_rpm
295 {
296 my($rpm)=@_;
297
298         my $vendor=_readfile "rpm 2>/dev/null --qf '%{VENDOR}' -qp '$rpm' |";
299         $vendor=~s/,.*//;
300         $vendor=~tr/ //d;
301         my $uname_r;
302         $uname_r||=($rpm=~m#/kernel-source-([^-]+-[^-]+)[.][^.]+[.]rpm$#)[0];
303         my $uname_r_base=($uname_r=~/^([^-]+)/)[0];
304         my $dir;
305         do { $dir||=$_ if -d $_; } for ("/usr/src/linux-$uname_r");
306         do { $dir||=$_ if -d $_; } for ("/usr/src/linux-$uname_r_base");        # older RedHat kernels
307         confess "Kernel sources already found in $dir" if $dir;
308         # '--nodeps' to prevent: error: Failed dependencies: perl-base is needed by *mdk
309         _system "rpm -i --nodeps '$rpm'" and confess "RPM installation of $rpm";
310         do { $dir||=$_ if -d $_; } for ("/usr/src/linux-$uname_r");
311         do { $dir||=$_ if -d $_; } for ("/usr/src/linux-$uname_r_base");        # older RedHat kernels
312         $dir or confess "Kernel source tree not found in: $rpm";
313         _system "cp -p $dir/include/linux/rhconfig.h $dir/include/linux/rhconfig.h-orig"
314                                 if -f "$dir/include/linux/rhconfig.h";
315         for my $smp ("","smp") {
316                 my @archs=qw(i386 i586 i686 athlon);
317                 for my $arch (@archs) {
318                         my %boot=(
319                                         "__BOOT_KERNEL_SMP"=>$smp,
320                                         map({ ("__MODULE_KERNEL_$_"=>($arch eq $_)); } @archs),
321                                         "__BOOT_KERNEL_BOOT"=>0,
322                                         "__BOOT_KERNEL_BOOTSMP"=>0,
323                                         "__BOOT_KERNEL_ENTERPRISE"=>0,
324                                         "__BOOT_KERNEL_BIGMEM"=>0,
325                                         "__BOOT_KERNEL_DEBUG"=>0,
326                                         );
327                         if (-f "$dir/include/linux/rhconfig.h") {
328                                 my $defines="";
329                                 for (keys(%boot)) {
330                                         $defines.="+#define $_ ".($boot{$_} ? 1 : 0)."\n";
331                                         }
332                                 _system "cp -p -f $dir/include/linux/rhconfig.h-orig $dir/include/linux/rhconfig.h";
333                                 _writefile "| patch $dir/include/linux/rhconfig.h",<<"RHCONFIG_H_NOBOOT_EOF";
334 --- ./include/linux/rhconfig.h-orig     Thu Aug 21 14:50:16 2003
335 +++ ./include/linux/rhconfig.h  Thu Aug 21 14:59:22 2003
336 \@\@ -10,7 +10,@{[ 7+keys(%boot) ]} \@\@
337   * /boot/kernel.h - initscripts should create it for us
338   */
339  
340 -#include "/boot/kernel.h"
341 +/* lufs: #include "/boot/kernel.h" */
342 $defines
343  #if defined(__BOOT_KERNEL_SMP) && (__BOOT_KERNEL_SMP == 1)
344  #define __module__smp
345 RHCONFIG_H_NOBOOT_EOF
346                                 }
347                         # Mandrake packages have no configs/ and they have just that '.config' file.
348                         my $single_config=-f "$dir/.config";
349                         if (!$single_config) {
350                                 my $spec_config="$dir/configs/kernel-$uname_r_base-$arch".($smp ? "-smp" : "").".config";
351                                 next if ! -f $spec_config;
352                                 _system "ln -s $spec_config $dir/.config";
353                                 }
354                         prebuild_kernel $dir,$vendor,$uname_r.$smp.".".$arch;
355                         _system "rm -f $dir/.config"
356                                         if !$single_config;
357                         }
358                 }
359         _system "rpm -e kernel-source-$uname_r" and confess "Remove of kernel-source-$uname_r";
360         _system "rm -rf $dir";
361 }
362
363 sub prebuild_dir
364 {
365 my($dir)=@_;
366
367         my $vendor;
368         chomp (my $debian=_readfile "/etc/debian_version","optional");
369         $debian=~tr#/#_#;
370         $vendor="Debian".$debian if $debian && $dir=~m#^/usr/src/#;
371         my $uname_r;
372         $uname_r||=($dir=~m#/kernel-headers-([^/]+)/*$#)[0];
373         $uname_r||=($dir=~m#/linux-([^/]+)/*$#)[0];
374         $uname_r||=($dir=~m#^/lib/modules/([^/]+)/build/*$#)[0];
375         prebuild_kernel $dir,$vendor,$uname_r;
376 }
377
378 sub prebuild
379 {
380         $vardir=undef();        # we may not yet have /var/lib/lufs
381         for (@ARGV) {
382                 do { prebuild_rpm $_; next; } if /[.]rpm$/;
383                 do { prebuild_dir $_; next; } if -d $_;
384                 confess "Unrecognized kernel: $_";
385                 }
386         exit 0;
387 }