#!/usr/bin/perl

# Copyright (C) 2007-2008  Jeffrey Brian Arnold <jbarnold@mit.edu>
# Copyright (C) 2008  Anders Kaseorg <andersk@mit.edu>,
#                     Tim Abbott <tabbott@mit.edu>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
# 02110-1301, USA.

use strict;
use warnings;
use lib '/usr/share/ksplice';
use Ksplice;

my $debug = 0;
GetOptions(@common_options,
	"debug" => \$debug) or pod2usage(1);

pod2usage(1) if($help || scalar(@ARGV) != 1);

my $file = abs_path($ARGV[0]);

my $tmpdir = tempdir('ksplice-tmp-XXXXXX', TMPDIR => 1, CLEANUP => 1);
chdir($tmpdir);
my $ksplice = unpack_update($file);
chdir($ksplice);

my $nounload = runstr("lsmod") =~ m/- $/m;

(my $kid = $ksplice) =~s|ksplice[-_]([^-_]+)|$1|;
my $update = "ksplice_$kid";
if(update_loaded($kid)) {
	my $stage = get_stage($kid);
	if ($stage eq "applied") {
		print STDERR "Ksplice update $kid already applied.\n";
		exit(0);
	}
	die "Reversed Ksplice module $update already loaded!" if ($stage eq "reversed");
}

runstr_err(qw(modprobe -q ksplice)) eq "" || die;
if (-e "ksplice-$kid.ko") {
	if (runstr("lsmod") =~ m/^ksplice_$kid\s+/) {
		die "Ksplice core module ksplice_$kid already loaded.";
	}
	if (!load_module("ksplice-$kid.ko", "debug=$debug")) {
		die "Error loading Ksplice core for update $kid";
	}
}

foreach my $helper (glob('ksplice-*-helper.ko')) {
	(my $primary = $helper) =~ s/\-helper\.ko$/.ko/;
	die unless(-e $primary && -e $helper);
	(my $target = $primary) =~ s/^ksplice-[^_]+_(.*)\.ko/$1/;
	if ($target ne 'vmlinux' && runstr("lsmod") !~ m/^${target}\s/m) {
		cleanup_modules();
		die "Module $target to be patched not loaded";
	}
}
foreach my $helper (glob('ksplice-*-helper.ko')) {
	(my $primary = $helper) =~ s/\-helper\.ko$/.ko/;
	if(!load_module($primary)) {
		die "Error loading primary module $primary";
	}
	if(!load_module($helper)) {
		my ($debugfile, $debugout) = get_debug_output("init_$kid");
		print STDERR "Error loading helper module $helper\n";
		(my $module = $primary) =~ s/-/_/g;
		$module =~ s/\.ko//;
		cleanup_modules();
		if(defined $debugfile) {
			print $debugout;
			print("Debugging output saved to $debugfile\n");
		}
		die;
	}
}

set_debug_level($kid, $debug);
set_stage($kid, "applied");
my $stage = get_stage($kid);
if($stage ne 'applied') {
	my ($debugfile, $debugout) = get_debug_output($kid);
	my $abort_cause = get_abort_cause($kid);
	my $conflicts = get_conflicts($kid);
	cleanup_modules();
	print STDERR "Error applying Ksplice update $kid:\n";
	print $debugout;
	print_error($abort_cause);
	if ($abort_cause eq 'code_busy') {
		print $conflicts;
	}
	print("Debugging output saved to $debugfile\n");
	die;
}
mkpath("/var/run/ksplice/updates/$kid");
copy("patch", "/var/run/ksplice/updates/$kid/patch");
foreach my $helper (glob('ksplice-*-helper.ko')) {
	$helper =~ s/-/_/g;
	$helper =~ s/\.ko$//;
	runval('rmmod', $helper) if(!$nounload);
}
print "Done!\n";
exit(0);

my @modules_loaded = qw();

sub load_module {
	my ($module, @params) = @_;
	if (runval_raw("insmod", $module, @params) != 0) {
		child_error();
		return 0;
	}
	$module =~ s/\.ko//;
	$module =~ s/-/_/g;
	push @modules_loaded, $module;
	return 1;
}

sub cleanup_modules {
	foreach my $module (reverse(@modules_loaded)) {
		runval("rmmod", $module) if(!$nounload);
	}
}

sub print_error {
	my ($error) = @_;
	my %errors = (
		"no_match" => <<'END',
Ksplice has aborted the upgrade because Ksplice has been unable to match the
object code produced by your current compiler and assembler against the running
kernel's object code.  If you provided the exact kernel source to the running
kernel, then it appears that your current compiler and/or assembler are
behaving differently from the compiler and assembler used to build the running
kernel.  If possible, please use the exact compiler and assembler that were
used to build the running kernel.  If you are using exactly the same compiler
and assembler, consider reporting a bug to ksplice@mit.edu.
END
		"code_busy" => <<'END',
Ksplice has aborted the upgrade because it appears that the code that you are
trying to patch is continuously in use by the system.  More specifically,
Ksplice has been unable to find a moment when one or more of the to-be-patched
functions is not on a thread's kernel stack.
END
		"bad_system_map" => <<'END',
Ksplice has aborted the upgrade because it appears that the System.map file
provided to ksplice-create does not match the running kernel.
END
		"failed_to_find" => <<'END',
Ksplice has aborted the upgrade because it was unable to resolve some of the
symbols used in the update.
END
		"already_reversed" => <<'END',
The Ksplice update that you are attempting to apply has already been applied
and reversed.  You need to unload the Ksplice modules associated with this
update before you can apply this update again.
END
		"missing_export" => <<'END',
Ksplice has aborted the upgrade because the symbols exported by the kernel
did not match Ksplice's expectations.
END
		"unexpected_running_task" => <<'END',
Ksplice has aborted the upgrade because of an unexpected failure during the
kernel stack check.  Please consider reporting a bug to ksplice@mit.edu.
END
		"out_of_memory" => <<'END',
Ksplice has aborted the upgrade because the kernel ran out of memory.
END
		"unexpected" => <<'END',
Ksplice has aborted because of an unexpected error.
Please consider reporting a bug to ksplice@mit.edu.
END
		"UNKNOWN" => <<'END',
The Ksplice kernel component has returned an error code that this version of
ksplice-apply does not understand.
END
		"ok" => <<'END',
Ksplice has aborted the upgrade for unknown reasons.
Please consider reporting a bug to ksplice@mit.edu.
END
	);
	$error = "UNKNOWN" if (!exists $errors{$error});
	print STDERR "\n$errors{$error}\n";
}

=head1 NAME

ksplice-apply - Apply an on-disk Ksplice update to the running kernel

=head1 SYNOPSIS

B<ksplice-apply> I<UPDATE_TARBALL>

=head1 DESCRIPTION

B<ksplice-apply> takes as input a Ksplice update tarball, as generated by
L<ksplice-create(8)>, and it applies the update to the running binary kernel.

The update tarball used with B<ksplice-apply> must have been generated for the
running kernel's version.

=head1 OPTIONS

=over 8

=item B<--debug>

Applies the update with debugging output enabled.  Recommended only for
debugging.

=back

=head1 SEE ALSO

L<ksplice-create(8)>, L<ksplice-view(8)>, L<ksplice-undo(8)>

=head1 COPYRIGHT

Copyright (C) 2007-2008  Jeffrey Brian Arnold <jbarnold@mit.edu>
Copyright (C) 2008  Anders Kaseorg <andersk@mit.edu>,
                    Tim Abbott <tabbott@mit.edu>

This is free software and documentation.  You can redistribute and/or modify it
under the terms of the GNU General Public License, version 2.

=cut
