#!/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;
my $partial = 0;
GetOptions(@common_options,
	"partial" => \$partial,
	"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";
	}
}

my @helpers = ();
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) {
		if (!$partial) {
			cleanup_modules();
			print_error("target_not_loaded");
			die "Module $target to be patched not loaded";
		}
	}
	push @helpers, $helper;
}
foreach my $helper (@helpers) {
	(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($debug && defined $debugfile) {
			print $debugout;
			print("Debugging output saved to $debugfile\n");
		}
		die;
	}
}

set_debug_level($kid, $debug);
set_partial($kid, $partial);
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 if (defined $debugfile);
	print_error($abort_cause);
	if ($abort_cause eq 'code_busy') {
		print $conflicts;
	}
	if ($debug && defined $debugfile) {
		print("Debugging output saved to $debugfile\n");
	}
	die;
}
mkpath("/var/run/ksplice/updates/$kid");
copy("patch", "/var/run/ksplice/updates/$kid/patch") if (-e "patch");
copy("description", "/var/run/ksplice/updates/$kid/description") if (-e "description");
if (!$nounload) {
	foreach my $helper (@helpers) {
		$helper =~ s/-/_/g;
		$helper =~ s/\.ko$//;
		(my $primary = $helper) =~ s/_helper$//;
		runval('rmmod', $helper);
		runval('rmmod', $primary) if ($partial && refcount($primary) == 0);
	}
}
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 refcount {
	my ($module) = @_;
	foreach(split(/\n/, runstr("lsmod"))) {
		if (m/^(\S+)\s+[0-9]+\s+([0-9])+\s/) {
			return $2 if ($1 eq $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 devel@ksplice.com.
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 devel@ksplice.com.
END
		"target_not_loaded" => <<'END',
Ksplice has aborted the upgrade because one of the modules to be
patched by the update was not loaded.  If you want to apply this
update only to those modules that are loaded, then you should use the
--partial option.
END
		"out_of_memory" => <<'END',
Ksplice has aborted the upgrade because the kernel ran out of memory.
END
		"call_failed" => <<'END',
Ksplice has aborted the upgrade at the request of a one of the
pre-application hooks that were included as part of this Ksplice
update.  This is likely the result of a bug in the patch used to
generate this update.
END
		"unexpected" => <<'END',
Ksplice has aborted because of an unexpected error.
Please consider reporting a bug to devel@ksplice.com.
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 devel@ksplice.com.
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.

=item B<--partial>

Applies the update only to those modules which are loaded.  Any
modules patched by the update that are not loaded are ignored (without
this option, Ksplice aborts if any modules patched by the update are
not loaded).

=back

=head1 SEE ALSO

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

=head1 BUGS

Please report bugs to <devel@ksplice.com>.

=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
