ktest: Add native support for syslinux boot loader
[profile/ivi/kernel-adaptation-intel-automotive.git] / tools / testing / ktest / ktest.pl
1 #!/usr/bin/perl -w
2 #
3 # Copyright 2010 - Steven Rostedt <srostedt@redhat.com>, Red Hat Inc.
4 # Licensed under the terms of the GNU GPL License version 2
5 #
6
7 use strict;
8 use IPC::Open2;
9 use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);
10 use File::Path qw(mkpath);
11 use File::Copy qw(cp);
12 use FileHandle;
13
14 my $VERSION = "0.2";
15
16 $| = 1;
17
18 my %opt;
19 my %repeat_tests;
20 my %repeats;
21
22 #default opts
23 my %default = (
24     "NUM_TESTS"                 => 1,
25     "TEST_TYPE"                 => "build",
26     "BUILD_TYPE"                => "randconfig",
27     "MAKE_CMD"                  => "make",
28     "TIMEOUT"                   => 120,
29     "TMP_DIR"                   => "/tmp/ktest/\${MACHINE}",
30     "SLEEP_TIME"                => 60,  # sleep time between tests
31     "BUILD_NOCLEAN"             => 0,
32     "REBOOT_ON_ERROR"           => 0,
33     "POWEROFF_ON_ERROR"         => 0,
34     "REBOOT_ON_SUCCESS"         => 1,
35     "POWEROFF_ON_SUCCESS"       => 0,
36     "BUILD_OPTIONS"             => "",
37     "BISECT_SLEEP_TIME"         => 60,   # sleep time between bisects
38     "PATCHCHECK_SLEEP_TIME"     => 60, # sleep time between patch checks
39     "CLEAR_LOG"                 => 0,
40     "BISECT_MANUAL"             => 0,
41     "BISECT_SKIP"               => 1,
42     "MIN_CONFIG_TYPE"           => "boot",
43     "SUCCESS_LINE"              => "login:",
44     "DETECT_TRIPLE_FAULT"       => 1,
45     "NO_INSTALL"                => 0,
46     "BOOTED_TIMEOUT"            => 1,
47     "DIE_ON_FAILURE"            => 1,
48     "SSH_EXEC"                  => "ssh \$SSH_USER\@\$MACHINE \$SSH_COMMAND",
49     "SCP_TO_TARGET"             => "scp \$SRC_FILE \$SSH_USER\@\$MACHINE:\$DST_FILE",
50     "SCP_TO_TARGET_INSTALL"     => "\${SCP_TO_TARGET}",
51     "REBOOT"                    => "ssh \$SSH_USER\@\$MACHINE reboot",
52     "STOP_AFTER_SUCCESS"        => 10,
53     "STOP_AFTER_FAILURE"        => 60,
54     "STOP_TEST_AFTER"           => 600,
55     "MAX_MONITOR_WAIT"          => 1800,
56     "GRUB_REBOOT"               => "grub2-reboot",
57     "SYSLINUX"                  => "extlinux",
58     "SYSLINUX_PATH"             => "/boot/extlinux",
59
60 # required, and we will ask users if they don't have them but we keep the default
61 # value something that is common.
62     "REBOOT_TYPE"               => "grub",
63     "LOCALVERSION"              => "-test",
64     "SSH_USER"                  => "root",
65     "BUILD_TARGET"              => "arch/x86/boot/bzImage",
66     "TARGET_IMAGE"              => "/boot/vmlinuz-test",
67
68     "LOG_FILE"                  => undef,
69     "IGNORE_UNUSED"             => 0,
70 );
71
72 my $ktest_config;
73 my $version;
74 my $have_version = 0;
75 my $machine;
76 my $ssh_user;
77 my $tmpdir;
78 my $builddir;
79 my $outputdir;
80 my $output_config;
81 my $test_type;
82 my $build_type;
83 my $build_options;
84 my $final_post_ktest;
85 my $pre_ktest;
86 my $post_ktest;
87 my $pre_test;
88 my $post_test;
89 my $pre_build;
90 my $post_build;
91 my $pre_build_die;
92 my $post_build_die;
93 my $reboot_type;
94 my $reboot_script;
95 my $power_cycle;
96 my $reboot;
97 my $reboot_on_error;
98 my $switch_to_good;
99 my $switch_to_test;
100 my $poweroff_on_error;
101 my $reboot_on_success;
102 my $die_on_failure;
103 my $powercycle_after_reboot;
104 my $poweroff_after_halt;
105 my $max_monitor_wait;
106 my $ssh_exec;
107 my $scp_to_target;
108 my $scp_to_target_install;
109 my $power_off;
110 my $grub_menu;
111 my $grub_file;
112 my $grub_number;
113 my $grub_reboot;
114 my $syslinux;
115 my $syslinux_path;
116 my $syslinux_label;
117 my $target;
118 my $make;
119 my $pre_install;
120 my $post_install;
121 my $no_install;
122 my $noclean;
123 my $minconfig;
124 my $start_minconfig;
125 my $start_minconfig_defined;
126 my $output_minconfig;
127 my $minconfig_type;
128 my $use_output_minconfig;
129 my $ignore_config;
130 my $ignore_errors;
131 my $addconfig;
132 my $in_bisect = 0;
133 my $bisect_bad_commit = "";
134 my $reverse_bisect;
135 my $bisect_manual;
136 my $bisect_skip;
137 my $config_bisect_good;
138 my $bisect_ret_good;
139 my $bisect_ret_bad;
140 my $bisect_ret_skip;
141 my $bisect_ret_abort;
142 my $bisect_ret_default;
143 my $in_patchcheck = 0;
144 my $run_test;
145 my $redirect;
146 my $buildlog;
147 my $testlog;
148 my $dmesg;
149 my $monitor_fp;
150 my $monitor_pid;
151 my $monitor_cnt = 0;
152 my $sleep_time;
153 my $bisect_sleep_time;
154 my $patchcheck_sleep_time;
155 my $ignore_warnings;
156 my $store_failures;
157 my $store_successes;
158 my $test_name;
159 my $timeout;
160 my $booted_timeout;
161 my $detect_triplefault;
162 my $console;
163 my $reboot_success_line;
164 my $success_line;
165 my $stop_after_success;
166 my $stop_after_failure;
167 my $stop_test_after;
168 my $build_target;
169 my $target_image;
170 my $checkout;
171 my $localversion;
172 my $iteration = 0;
173 my $successes = 0;
174
175 my $bisect_good;
176 my $bisect_bad;
177 my $bisect_type;
178 my $bisect_start;
179 my $bisect_replay;
180 my $bisect_files;
181 my $bisect_reverse;
182 my $bisect_check;
183
184 my $config_bisect;
185 my $config_bisect_type;
186 my $config_bisect_check;
187
188 my $patchcheck_type;
189 my $patchcheck_start;
190 my $patchcheck_end;
191
192 # set when a test is something other that just building or install
193 # which would require more options.
194 my $buildonly = 1;
195
196 # set when creating a new config
197 my $newconfig = 0;
198
199 my %entered_configs;
200 my %config_help;
201 my %variable;
202
203 # force_config is the list of configs that we force enabled (or disabled)
204 # in a .config file. The MIN_CONFIG and ADD_CONFIG configs.
205 my %force_config;
206
207 # do not force reboots on config problems
208 my $no_reboot = 1;
209
210 # reboot on success
211 my $reboot_success = 0;
212
213 my %option_map = (
214     "MACHINE"                   => \$machine,
215     "SSH_USER"                  => \$ssh_user,
216     "TMP_DIR"                   => \$tmpdir,
217     "OUTPUT_DIR"                => \$outputdir,
218     "BUILD_DIR"                 => \$builddir,
219     "TEST_TYPE"                 => \$test_type,
220     "PRE_KTEST"                 => \$pre_ktest,
221     "POST_KTEST"                => \$post_ktest,
222     "PRE_TEST"                  => \$pre_test,
223     "POST_TEST"                 => \$post_test,
224     "BUILD_TYPE"                => \$build_type,
225     "BUILD_OPTIONS"             => \$build_options,
226     "PRE_BUILD"                 => \$pre_build,
227     "POST_BUILD"                => \$post_build,
228     "PRE_BUILD_DIE"             => \$pre_build_die,
229     "POST_BUILD_DIE"            => \$post_build_die,
230     "POWER_CYCLE"               => \$power_cycle,
231     "REBOOT"                    => \$reboot,
232     "BUILD_NOCLEAN"             => \$noclean,
233     "MIN_CONFIG"                => \$minconfig,
234     "OUTPUT_MIN_CONFIG"         => \$output_minconfig,
235     "START_MIN_CONFIG"          => \$start_minconfig,
236     "MIN_CONFIG_TYPE"           => \$minconfig_type,
237     "USE_OUTPUT_MIN_CONFIG"     => \$use_output_minconfig,
238     "IGNORE_CONFIG"             => \$ignore_config,
239     "TEST"                      => \$run_test,
240     "ADD_CONFIG"                => \$addconfig,
241     "REBOOT_TYPE"               => \$reboot_type,
242     "GRUB_MENU"                 => \$grub_menu,
243     "GRUB_FILE"                 => \$grub_file,
244     "GRUB_REBOOT"               => \$grub_reboot,
245     "SYSLINUX"                  => \$syslinux,
246     "SYSLINUX_PATH"             => \$syslinux_path,
247     "SYSLINUX_LABEL"            => \$syslinux_label,
248     "PRE_INSTALL"               => \$pre_install,
249     "POST_INSTALL"              => \$post_install,
250     "NO_INSTALL"                => \$no_install,
251     "REBOOT_SCRIPT"             => \$reboot_script,
252     "REBOOT_ON_ERROR"           => \$reboot_on_error,
253     "SWITCH_TO_GOOD"            => \$switch_to_good,
254     "SWITCH_TO_TEST"            => \$switch_to_test,
255     "POWEROFF_ON_ERROR"         => \$poweroff_on_error,
256     "REBOOT_ON_SUCCESS"         => \$reboot_on_success,
257     "DIE_ON_FAILURE"            => \$die_on_failure,
258     "POWER_OFF"                 => \$power_off,
259     "POWERCYCLE_AFTER_REBOOT"   => \$powercycle_after_reboot,
260     "POWEROFF_AFTER_HALT"       => \$poweroff_after_halt,
261     "MAX_MONITOR_WAIT"          => \$max_monitor_wait,
262     "SLEEP_TIME"                => \$sleep_time,
263     "BISECT_SLEEP_TIME"         => \$bisect_sleep_time,
264     "PATCHCHECK_SLEEP_TIME"     => \$patchcheck_sleep_time,
265     "IGNORE_WARNINGS"           => \$ignore_warnings,
266     "IGNORE_ERRORS"             => \$ignore_errors,
267     "BISECT_MANUAL"             => \$bisect_manual,
268     "BISECT_SKIP"               => \$bisect_skip,
269     "CONFIG_BISECT_GOOD"        => \$config_bisect_good,
270     "BISECT_RET_GOOD"           => \$bisect_ret_good,
271     "BISECT_RET_BAD"            => \$bisect_ret_bad,
272     "BISECT_RET_SKIP"           => \$bisect_ret_skip,
273     "BISECT_RET_ABORT"          => \$bisect_ret_abort,
274     "BISECT_RET_DEFAULT"        => \$bisect_ret_default,
275     "STORE_FAILURES"            => \$store_failures,
276     "STORE_SUCCESSES"           => \$store_successes,
277     "TEST_NAME"                 => \$test_name,
278     "TIMEOUT"                   => \$timeout,
279     "BOOTED_TIMEOUT"            => \$booted_timeout,
280     "CONSOLE"                   => \$console,
281     "DETECT_TRIPLE_FAULT"       => \$detect_triplefault,
282     "SUCCESS_LINE"              => \$success_line,
283     "REBOOT_SUCCESS_LINE"       => \$reboot_success_line,
284     "STOP_AFTER_SUCCESS"        => \$stop_after_success,
285     "STOP_AFTER_FAILURE"        => \$stop_after_failure,
286     "STOP_TEST_AFTER"           => \$stop_test_after,
287     "BUILD_TARGET"              => \$build_target,
288     "SSH_EXEC"                  => \$ssh_exec,
289     "SCP_TO_TARGET"             => \$scp_to_target,
290     "SCP_TO_TARGET_INSTALL"     => \$scp_to_target_install,
291     "CHECKOUT"                  => \$checkout,
292     "TARGET_IMAGE"              => \$target_image,
293     "LOCALVERSION"              => \$localversion,
294
295     "BISECT_GOOD"               => \$bisect_good,
296     "BISECT_BAD"                => \$bisect_bad,
297     "BISECT_TYPE"               => \$bisect_type,
298     "BISECT_START"              => \$bisect_start,
299     "BISECT_REPLAY"             => \$bisect_replay,
300     "BISECT_FILES"              => \$bisect_files,
301     "BISECT_REVERSE"            => \$bisect_reverse,
302     "BISECT_CHECK"              => \$bisect_check,
303
304     "CONFIG_BISECT"             => \$config_bisect,
305     "CONFIG_BISECT_TYPE"        => \$config_bisect_type,
306     "CONFIG_BISECT_CHECK"       => \$config_bisect_check,
307
308     "PATCHCHECK_TYPE"           => \$patchcheck_type,
309     "PATCHCHECK_START"          => \$patchcheck_start,
310     "PATCHCHECK_END"            => \$patchcheck_end,
311 );
312
313 # Options may be used by other options, record them.
314 my %used_options;
315
316 # default variables that can be used
317 chomp ($variable{"PWD"} = `pwd`);
318
319 $config_help{"MACHINE"} = << "EOF"
320  The machine hostname that you will test.
321  For build only tests, it is still needed to differentiate log files.
322 EOF
323     ;
324 $config_help{"SSH_USER"} = << "EOF"
325  The box is expected to have ssh on normal bootup, provide the user
326   (most likely root, since you need privileged operations)
327 EOF
328     ;
329 $config_help{"BUILD_DIR"} = << "EOF"
330  The directory that contains the Linux source code (full path).
331  You can use \${PWD} that will be the path where ktest.pl is run, or use
332  \${THIS_DIR} which is assigned \${PWD} but may be changed later.
333 EOF
334     ;
335 $config_help{"OUTPUT_DIR"} = << "EOF"
336  The directory that the objects will be built (full path).
337  (can not be same as BUILD_DIR)
338  You can use \${PWD} that will be the path where ktest.pl is run, or use
339  \${THIS_DIR} which is assigned \${PWD} but may be changed later.
340 EOF
341     ;
342 $config_help{"BUILD_TARGET"} = << "EOF"
343  The location of the compiled file to copy to the target.
344  (relative to OUTPUT_DIR)
345 EOF
346     ;
347 $config_help{"BUILD_OPTIONS"} = << "EOF"
348  Options to add to \"make\" when building.
349  i.e.  -j20
350 EOF
351     ;
352 $config_help{"TARGET_IMAGE"} = << "EOF"
353  The place to put your image on the test machine.
354 EOF
355     ;
356 $config_help{"POWER_CYCLE"} = << "EOF"
357  A script or command to reboot the box.
358
359  Here is a digital loggers power switch example
360  POWER_CYCLE = wget --no-proxy -O /dev/null -q  --auth-no-challenge 'http://admin:admin\@power/outlet?5=CCL'
361
362  Here is an example to reboot a virtual box on the current host
363  with the name "Guest".
364  POWER_CYCLE = virsh destroy Guest; sleep 5; virsh start Guest
365 EOF
366     ;
367 $config_help{"CONSOLE"} = << "EOF"
368  The script or command that reads the console
369
370   If you use ttywatch server, something like the following would work.
371 CONSOLE = nc -d localhost 3001
372
373  For a virtual machine with guest name "Guest".
374 CONSOLE =  virsh console Guest
375 EOF
376     ;
377 $config_help{"LOCALVERSION"} = << "EOF"
378  Required version ending to differentiate the test
379  from other linux builds on the system.
380 EOF
381     ;
382 $config_help{"REBOOT_TYPE"} = << "EOF"
383  Way to reboot the box to the test kernel.
384  Only valid options so far are "grub", "grub2", "syslinux", and "script".
385
386  If you specify grub, it will assume grub version 1
387  and will search in /boot/grub/menu.lst for the title \$GRUB_MENU
388  and select that target to reboot to the kernel. If this is not
389  your setup, then specify "script" and have a command or script
390  specified in REBOOT_SCRIPT to boot to the target.
391
392  The entry in /boot/grub/menu.lst must be entered in manually.
393  The test will not modify that file.
394
395  If you specify grub2, then you also need to specify both \$GRUB_MENU
396  and \$GRUB_FILE.
397
398  If you specify syslinux, then you may use SYSLINUX to define the syslinux
399  command (defaults to extlinux), and SYSLINUX_PATH to specify the path to
400  the syslinux install (defaults to /boot/extlinux). But you have to specify
401  SYSLINUX_LABEL to define the label to boot to for the test kernel.
402 EOF
403     ;
404 $config_help{"GRUB_MENU"} = << "EOF"
405  The grub title name for the test kernel to boot
406  (Only mandatory if REBOOT_TYPE = grub or grub2)
407
408  Note, ktest.pl will not update the grub menu.lst, you need to
409  manually add an option for the test. ktest.pl will search
410  the grub menu.lst for this option to find what kernel to
411  reboot into.
412
413  For example, if in the /boot/grub/menu.lst the test kernel title has:
414  title Test Kernel
415  kernel vmlinuz-test
416  GRUB_MENU = Test Kernel
417
418  For grub2, a search of \$GRUB_FILE is performed for the lines
419  that begin with "menuentry". It will not detect submenus. The
420  menu must be a non-nested menu. Add the quotes used in the menu
421  to guarantee your selection, as the first menuentry with the content
422  of \$GRUB_MENU that is found will be used.
423 EOF
424     ;
425 $config_help{"GRUB_FILE"} = << "EOF"
426  If grub2 is used, the full path for the grub.cfg file is placed
427  here. Use something like /boot/grub2/grub.cfg to search.
428 EOF
429     ;
430 $config_help{"SYSLINUX_LABEL"} = << "EOF"
431  If syslinux is used, the label that boots the target kernel must
432  be specified with SYSLINUX_LABEL.
433 EOF
434     ;
435 $config_help{"REBOOT_SCRIPT"} = << "EOF"
436  A script to reboot the target into the test kernel
437  (Only mandatory if REBOOT_TYPE = script)
438 EOF
439     ;
440
441 sub read_prompt {
442     my ($cancel, $prompt) = @_;
443
444     my $ans;
445
446     for (;;) {
447         if ($cancel) {
448             print "$prompt [y/n/C] ";
449         } else {
450             print "$prompt [Y/n] ";
451         }
452         $ans = <STDIN>;
453         chomp $ans;
454         if ($ans =~ /^\s*$/) {
455             if ($cancel) {
456                 $ans = "c";
457             } else {
458                 $ans = "y";
459             }
460         }
461         last if ($ans =~ /^y$/i || $ans =~ /^n$/i);
462         if ($cancel) {
463             last if ($ans =~ /^c$/i);
464             print "Please answer either 'y', 'n' or 'c'.\n";
465         } else {
466             print "Please answer either 'y' or 'n'.\n";
467         }
468     }
469     if ($ans =~ /^c/i) {
470         exit;
471     }
472     if ($ans !~ /^y$/i) {
473         return 0;
474     }
475     return 1;
476 }
477
478 sub read_yn {
479     my ($prompt) = @_;
480
481     return read_prompt 0, $prompt;
482 }
483
484 sub read_ync {
485     my ($prompt) = @_;
486
487     return read_prompt 1, $prompt;
488 }
489
490 sub get_ktest_config {
491     my ($config) = @_;
492     my $ans;
493
494     return if (defined($opt{$config}));
495
496     if (defined($config_help{$config})) {
497         print "\n";
498         print $config_help{$config};
499     }
500
501     for (;;) {
502         print "$config = ";
503         if (defined($default{$config}) && length($default{$config})) {
504             print "\[$default{$config}\] ";
505         }
506         $ans = <STDIN>;
507         $ans =~ s/^\s*(.*\S)\s*$/$1/;
508         if ($ans =~ /^\s*$/) {
509             if ($default{$config}) {
510                 $ans = $default{$config};
511             } else {
512                 print "Your answer can not be blank\n";
513                 next;
514             }
515         }
516         $entered_configs{$config} = ${ans};
517         last;
518     }
519 }
520
521 sub get_ktest_configs {
522     get_ktest_config("MACHINE");
523     get_ktest_config("BUILD_DIR");
524     get_ktest_config("OUTPUT_DIR");
525
526     if ($newconfig) {
527         get_ktest_config("BUILD_OPTIONS");
528     }
529
530     # options required for other than just building a kernel
531     if (!$buildonly) {
532         get_ktest_config("POWER_CYCLE");
533         get_ktest_config("CONSOLE");
534     }
535
536     # options required for install and more
537     if ($buildonly != 1) {
538         get_ktest_config("SSH_USER");
539         get_ktest_config("BUILD_TARGET");
540         get_ktest_config("TARGET_IMAGE");
541     }
542
543     get_ktest_config("LOCALVERSION");
544
545     return if ($buildonly);
546
547     my $rtype = $opt{"REBOOT_TYPE"};
548
549     if (!defined($rtype)) {
550         if (!defined($opt{"GRUB_MENU"})) {
551             get_ktest_config("REBOOT_TYPE");
552             $rtype = $entered_configs{"REBOOT_TYPE"};
553         } else {
554             $rtype = "grub";
555         }
556     }
557
558     if ($rtype eq "grub") {
559         get_ktest_config("GRUB_MENU");
560     }
561
562     if ($rtype eq "grub2") {
563         get_ktest_config("GRUB_MENU");
564         get_ktest_config("GRUB_FILE");
565     }
566
567     if ($rtype eq "syslinux") {
568         get_ktest_config("SYSLINUX_LABEL");
569     }
570 }
571
572 sub process_variables {
573     my ($value, $remove_undef) = @_;
574     my $retval = "";
575
576     # We want to check for '\', and it is just easier
577     # to check the previous characet of '$' and not need
578     # to worry if '$' is the first character. By adding
579     # a space to $value, we can just check [^\\]\$ and
580     # it will still work.
581     $value = " $value";
582
583     while ($value =~ /(.*?[^\\])\$\{(.*?)\}(.*)/) {
584         my $begin = $1;
585         my $var = $2;
586         my $end = $3;
587         # append beginning of value to retval
588         $retval = "$retval$begin";
589         if (defined($variable{$var})) {
590             $retval = "$retval$variable{$var}";
591         } elsif (defined($remove_undef) && $remove_undef) {
592             # for if statements, any variable that is not defined,
593             # we simple convert to 0
594             $retval = "${retval}0";
595         } else {
596             # put back the origin piece.
597             $retval = "$retval\$\{$var\}";
598             # This could be an option that is used later, save
599             # it so we don't warn if this option is not one of
600             # ktests options.
601             $used_options{$var} = 1;
602         }
603         $value = $end;
604     }
605     $retval = "$retval$value";
606
607     # remove the space added in the beginning
608     $retval =~ s/ //;
609
610     return "$retval"
611 }
612
613 sub set_value {
614     my ($lvalue, $rvalue, $override, $overrides, $name) = @_;
615
616     my $prvalue = process_variables($rvalue);
617
618     if ($buildonly && $lvalue =~ /^TEST_TYPE(\[.*\])?$/ && $prvalue ne "build") {
619         # Note if a test is something other than build, then we
620         # will need other manditory options.
621         if ($prvalue ne "install") {
622             $buildonly = 0;
623         } else {
624             # install still limits some manditory options.
625             $buildonly = 2;
626         }
627     }
628
629     if (defined($opt{$lvalue})) {
630         if (!$override || defined(${$overrides}{$lvalue})) {
631             my $extra = "";
632             if ($override) {
633                 $extra = "In the same override section!\n";
634             }
635             die "$name: $.: Option $lvalue defined more than once!\n$extra";
636         }
637         ${$overrides}{$lvalue} = $prvalue;
638     }
639     if ($rvalue =~ /^\s*$/) {
640         delete $opt{$lvalue};
641     } else {
642         $opt{$lvalue} = $prvalue;
643     }
644 }
645
646 sub set_variable {
647     my ($lvalue, $rvalue) = @_;
648
649     if ($rvalue =~ /^\s*$/) {
650         delete $variable{$lvalue};
651     } else {
652         $rvalue = process_variables($rvalue);
653         $variable{$lvalue} = $rvalue;
654     }
655 }
656
657 sub process_compare {
658     my ($lval, $cmp, $rval) = @_;
659
660     # remove whitespace
661
662     $lval =~ s/^\s*//;
663     $lval =~ s/\s*$//;
664
665     $rval =~ s/^\s*//;
666     $rval =~ s/\s*$//;
667
668     if ($cmp eq "==") {
669         return $lval eq $rval;
670     } elsif ($cmp eq "!=") {
671         return $lval ne $rval;
672     } elsif ($cmp eq "=~") {
673         return $lval =~ m/$rval/;
674     } elsif ($cmp eq "!~") {
675         return $lval !~ m/$rval/;
676     }
677
678     my $statement = "$lval $cmp $rval";
679     my $ret = eval $statement;
680
681     # $@ stores error of eval
682     if ($@) {
683         return -1;
684     }
685
686     return $ret;
687 }
688
689 sub value_defined {
690     my ($val) = @_;
691
692     return defined($variable{$2}) ||
693         defined($opt{$2});
694 }
695
696 my $d = 0;
697 sub process_expression {
698     my ($name, $val) = @_;
699
700     my $c = $d++;
701
702     while ($val =~ s/\(([^\(]*?)\)/\&\&\&\&VAL\&\&\&\&/) {
703         my $express = $1;
704
705         if (process_expression($name, $express)) {
706             $val =~ s/\&\&\&\&VAL\&\&\&\&/ 1 /;
707         } else {
708             $val =~ s/\&\&\&\&VAL\&\&\&\&/ 0 /;
709         }
710     }
711
712     $d--;
713     my $OR = "\\|\\|";
714     my $AND = "\\&\\&";
715
716     while ($val =~ s/^(.*?)($OR|$AND)//) {
717         my $express = $1;
718         my $op = $2;
719
720         if (process_expression($name, $express)) {
721             if ($op eq "||") {
722                 return 1;
723             }
724         } else {
725             if ($op eq "&&") {
726                 return 0;
727             }
728         }
729     }
730
731     if ($val =~ /(.*)(==|\!=|>=|<=|>|<|=~|\!~)(.*)/) {
732         my $ret = process_compare($1, $2, $3);
733         if ($ret < 0) {
734             die "$name: $.: Unable to process comparison\n";
735         }
736         return $ret;
737     }
738
739     if ($val =~ /^\s*(NOT\s*)?DEFINED\s+(\S+)\s*$/) {
740         if (defined $1) {
741             return !value_defined($2);
742         } else {
743             return value_defined($2);
744         }
745     }
746
747     if ($val =~ /^\s*0\s*$/) {
748         return 0;
749     } elsif ($val =~ /^\s*\d+\s*$/) {
750         return 1;
751     }
752
753     die ("$name: $.: Undefined content $val in if statement\n");
754 }
755
756 sub process_if {
757     my ($name, $value) = @_;
758
759     # Convert variables and replace undefined ones with 0
760     my $val = process_variables($value, 1);
761     my $ret = process_expression $name, $val;
762
763     return $ret;
764 }
765
766 sub __read_config {
767     my ($config, $current_test_num) = @_;
768
769     my $in;
770     open($in, $config) || die "can't read file $config";
771
772     my $name = $config;
773     $name =~ s,.*/(.*),$1,;
774
775     my $test_num = $$current_test_num;
776     my $default = 1;
777     my $repeat = 1;
778     my $num_tests_set = 0;
779     my $skip = 0;
780     my $rest;
781     my $line;
782     my $test_case = 0;
783     my $if = 0;
784     my $if_set = 0;
785     my $override = 0;
786
787     my %overrides;
788
789     while (<$in>) {
790
791         # ignore blank lines and comments
792         next if (/^\s*$/ || /\s*\#/);
793
794         if (/^\s*(TEST_START|DEFAULTS)\b(.*)/) {
795
796             my $type = $1;
797             $rest = $2;
798             $line = $2;
799
800             my $old_test_num;
801             my $old_repeat;
802             $override = 0;
803
804             if ($type eq "TEST_START") {
805
806                 if ($num_tests_set) {
807                     die "$name: $.: Can not specify both NUM_TESTS and TEST_START\n";
808                 }
809
810                 $old_test_num = $test_num;
811                 $old_repeat = $repeat;
812
813                 $test_num += $repeat;
814                 $default = 0;
815                 $repeat = 1;
816             } else {
817                 $default = 1;
818             }
819
820             # If SKIP is anywhere in the line, the command will be skipped
821             if ($rest =~ s/\s+SKIP\b//) {
822                 $skip = 1;
823             } else {
824                 $test_case = 1;
825                 $skip = 0;
826             }
827
828             if ($rest =~ s/\sELSE\b//) {
829                 if (!$if) {
830                     die "$name: $.: ELSE found with out matching IF section\n$_";
831                 }
832                 $if = 0;
833
834                 if ($if_set) {
835                     $skip = 1;
836                 } else {
837                     $skip = 0;
838                 }
839             }
840
841             if ($rest =~ s/\sIF\s+(.*)//) {
842                 if (process_if($name, $1)) {
843                     $if_set = 1;
844                 } else {
845                     $skip = 1;
846                 }
847                 $if = 1;
848             } else {
849                 $if = 0;
850                 $if_set = 0;
851             }
852
853             if (!$skip) {
854                 if ($type eq "TEST_START") {
855                     if ($rest =~ s/\s+ITERATE\s+(\d+)//) {
856                         $repeat = $1;
857                         $repeat_tests{"$test_num"} = $repeat;
858                     }
859                 } elsif ($rest =~ s/\sOVERRIDE\b//) {
860                     # DEFAULT only
861                     $override = 1;
862                     # Clear previous overrides
863                     %overrides = ();
864                 }
865             }
866
867             if (!$skip && $rest !~ /^\s*$/) {
868                 die "$name: $.: Gargbage found after $type\n$_";
869             }
870
871             if ($skip && $type eq "TEST_START") {
872                 $test_num = $old_test_num;
873                 $repeat = $old_repeat;
874             }
875
876         } elsif (/^\s*ELSE\b(.*)$/) {
877             if (!$if) {
878                 die "$name: $.: ELSE found with out matching IF section\n$_";
879             }
880             $rest = $1;
881             if ($if_set) {
882                 $skip = 1;
883                 $rest = "";
884             } else {
885                 $skip = 0;
886
887                 if ($rest =~ /\sIF\s+(.*)/) {
888                     # May be a ELSE IF section.
889                     if (process_if($name, $1)) {
890                         $if_set = 1;
891                     } else {
892                         $skip = 1;
893                     }
894                     $rest = "";
895                 } else {
896                     $if = 0;
897                 }
898             }
899
900             if ($rest !~ /^\s*$/) {
901                 die "$name: $.: Gargbage found after DEFAULTS\n$_";
902             }
903
904         } elsif (/^\s*INCLUDE\s+(\S+)/) {
905
906             next if ($skip);
907
908             if (!$default) {
909                 die "$name: $.: INCLUDE can only be done in default sections\n$_";
910             }
911
912             my $file = process_variables($1);
913
914             if ($file !~ m,^/,) {
915                 # check the path of the config file first
916                 if ($config =~ m,(.*)/,) {
917                     if (-f "$1/$file") {
918                         $file = "$1/$file";
919                     }
920                 }
921             }
922                 
923             if ( ! -r $file ) {
924                 die "$name: $.: Can't read file $file\n$_";
925             }
926
927             if (__read_config($file, \$test_num)) {
928                 $test_case = 1;
929             }
930
931         } elsif (/^\s*([A-Z_\[\]\d]+)\s*=\s*(.*?)\s*$/) {
932
933             next if ($skip);
934
935             my $lvalue = $1;
936             my $rvalue = $2;
937
938             if (!$default &&
939                 ($lvalue eq "NUM_TESTS" ||
940                  $lvalue eq "LOG_FILE" ||
941                  $lvalue eq "CLEAR_LOG")) {
942                 die "$name: $.: $lvalue must be set in DEFAULTS section\n";
943             }
944
945             if ($lvalue eq "NUM_TESTS") {
946                 if ($test_num) {
947                     die "$name: $.: Can not specify both NUM_TESTS and TEST_START\n";
948                 }
949                 if (!$default) {
950                     die "$name: $.: NUM_TESTS must be set in default section\n";
951                 }
952                 $num_tests_set = 1;
953             }
954
955             if ($default || $lvalue =~ /\[\d+\]$/) {
956                 set_value($lvalue, $rvalue, $override, \%overrides, $name);
957             } else {
958                 my $val = "$lvalue\[$test_num\]";
959                 set_value($val, $rvalue, $override, \%overrides, $name);
960
961                 if ($repeat > 1) {
962                     $repeats{$val} = $repeat;
963                 }
964             }
965         } elsif (/^\s*([A-Z_\[\]\d]+)\s*:=\s*(.*?)\s*$/) {
966             next if ($skip);
967
968             my $lvalue = $1;
969             my $rvalue = $2;
970
971             # process config variables.
972             # Config variables are only active while reading the
973             # config and can be defined anywhere. They also ignore
974             # TEST_START and DEFAULTS, but are skipped if they are in
975             # on of these sections that have SKIP defined.
976             # The save variable can be
977             # defined multiple times and the new one simply overrides
978             # the prevous one.
979             set_variable($lvalue, $rvalue);
980
981         } else {
982             die "$name: $.: Garbage found in config\n$_";
983         }
984     }
985
986     if ($test_num) {
987         $test_num += $repeat - 1;
988         $opt{"NUM_TESTS"} = $test_num;
989     }
990
991     close($in);
992
993     $$current_test_num = $test_num;
994
995     return $test_case;
996 }
997
998 sub get_test_case {
999         print "What test case would you like to run?\n";
1000         print " (build, install or boot)\n";
1001         print " Other tests are available but require editing the config file\n";
1002         my $ans = <STDIN>;
1003         chomp $ans;
1004         $default{"TEST_TYPE"} = $ans;
1005 }
1006
1007 sub read_config {
1008     my ($config) = @_;
1009
1010     my $test_case;
1011     my $test_num = 0;
1012
1013     $test_case = __read_config $config, \$test_num;
1014
1015     # make sure we have all mandatory configs
1016     get_ktest_configs;
1017
1018     # was a test specified?
1019     if (!$test_case) {
1020         print "No test case specified.\n";
1021         get_test_case;
1022     }
1023
1024     # set any defaults
1025
1026     foreach my $default (keys %default) {
1027         if (!defined($opt{$default})) {
1028             $opt{$default} = $default{$default};
1029         }
1030     }
1031
1032     if ($opt{"IGNORE_UNUSED"} == 1) {
1033         return;
1034     }
1035
1036     my %not_used;
1037
1038     # check if there are any stragglers (typos?)
1039     foreach my $option (keys %opt) {
1040         my $op = $option;
1041         # remove per test labels.
1042         $op =~ s/\[.*\]//;
1043         if (!exists($option_map{$op}) &&
1044             !exists($default{$op}) &&
1045             !exists($used_options{$op})) {
1046             $not_used{$op} = 1;
1047         }
1048     }
1049
1050     if (%not_used) {
1051         my $s = "s are";
1052         $s = " is" if (keys %not_used == 1);
1053         print "The following option$s not used; could be a typo:\n";
1054         foreach my $option (keys %not_used) {
1055             print "$option\n";
1056         }
1057         print "Set IGRNORE_UNUSED = 1 to have ktest ignore unused variables\n";
1058         if (!read_yn "Do you want to continue?") {
1059             exit -1;
1060         }
1061     }
1062 }
1063
1064 sub __eval_option {
1065     my ($option, $i) = @_;
1066
1067     # Add space to evaluate the character before $
1068     $option = " $option";
1069     my $retval = "";
1070     my $repeated = 0;
1071     my $parent = 0;
1072
1073     foreach my $test (keys %repeat_tests) {
1074         if ($i >= $test &&
1075             $i < $test + $repeat_tests{$test}) {
1076
1077             $repeated = 1;
1078             $parent = $test;
1079             last;
1080         }
1081     }
1082
1083     while ($option =~ /(.*?[^\\])\$\{(.*?)\}(.*)/) {
1084         my $start = $1;
1085         my $var = $2;
1086         my $end = $3;
1087
1088         # Append beginning of line
1089         $retval = "$retval$start";
1090
1091         # If the iteration option OPT[$i] exists, then use that.
1092         # otherwise see if the default OPT (without [$i]) exists.
1093
1094         my $o = "$var\[$i\]";
1095         my $parento = "$var\[$parent\]";
1096
1097         if (defined($opt{$o})) {
1098             $o = $opt{$o};
1099             $retval = "$retval$o";
1100         } elsif ($repeated && defined($opt{$parento})) {
1101             $o = $opt{$parento};
1102             $retval = "$retval$o";
1103         } elsif (defined($opt{$var})) {
1104             $o = $opt{$var};
1105             $retval = "$retval$o";
1106         } else {
1107             $retval = "$retval\$\{$var\}";
1108         }
1109
1110         $option = $end;
1111     }
1112
1113     $retval = "$retval$option";
1114
1115     $retval =~ s/^ //;
1116
1117     return $retval;
1118 }
1119
1120 sub eval_option {
1121     my ($option, $i) = @_;
1122
1123     my $prev = "";
1124
1125     # Since an option can evaluate to another option,
1126     # keep iterating until we do not evaluate any more
1127     # options.
1128     my $r = 0;
1129     while ($prev ne $option) {
1130         # Check for recursive evaluations.
1131         # 100 deep should be more than enough.
1132         if ($r++ > 100) {
1133             die "Over 100 evaluations accurred with $option\n" .
1134                 "Check for recursive variables\n";
1135         }
1136         $prev = $option;
1137         $option = __eval_option($option, $i);
1138     }
1139
1140     return $option;
1141 }
1142
1143 sub _logit {
1144     if (defined($opt{"LOG_FILE"})) {
1145         open(OUT, ">> $opt{LOG_FILE}") or die "Can't write to $opt{LOG_FILE}";
1146         print OUT @_;
1147         close(OUT);
1148     }
1149 }
1150
1151 sub logit {
1152     if (defined($opt{"LOG_FILE"})) {
1153         _logit @_;
1154     } else {
1155         print @_;
1156     }
1157 }
1158
1159 sub doprint {
1160     print @_;
1161     _logit @_;
1162 }
1163
1164 sub run_command;
1165 sub start_monitor;
1166 sub end_monitor;
1167 sub wait_for_monitor;
1168
1169 sub reboot {
1170     my ($time) = @_;
1171
1172     # Make sure everything has been written to disk
1173     run_ssh("sync");
1174
1175     if (defined($time)) {
1176         start_monitor;
1177         # flush out current monitor
1178         # May contain the reboot success line
1179         wait_for_monitor 1;
1180     }
1181
1182     # try to reboot normally
1183     if (run_command $reboot) {
1184         if (defined($powercycle_after_reboot)) {
1185             sleep $powercycle_after_reboot;
1186             run_command "$power_cycle";
1187         }
1188     } else {
1189         # nope? power cycle it.
1190         run_command "$power_cycle";
1191     }
1192
1193     if (defined($time)) {
1194         if (wait_for_monitor($time, $reboot_success_line)) {
1195             # reboot got stuck?
1196             doprint "Reboot did not finish. Forcing power cycle\n";
1197             run_command "$power_cycle";
1198         }
1199         end_monitor;
1200     }
1201 }
1202
1203 sub reboot_to_good {
1204     my ($time) = @_;
1205
1206     if (defined($switch_to_good)) {
1207         run_command $switch_to_good;
1208     }
1209
1210     reboot $time;
1211 }
1212
1213 sub do_not_reboot {
1214     my $i = $iteration;
1215
1216     return $test_type eq "build" || $no_reboot ||
1217         ($test_type eq "patchcheck" && $opt{"PATCHCHECK_TYPE[$i]"} eq "build") ||
1218         ($test_type eq "bisect" && $opt{"BISECT_TYPE[$i]"} eq "build");
1219 }
1220
1221 sub dodie {
1222     doprint "CRITICAL FAILURE... ", @_, "\n";
1223
1224     my $i = $iteration;
1225
1226     if ($reboot_on_error && !do_not_reboot) {
1227
1228         doprint "REBOOTING\n";
1229         reboot_to_good;
1230
1231     } elsif ($poweroff_on_error && defined($power_off)) {
1232         doprint "POWERING OFF\n";
1233         `$power_off`;
1234     }
1235
1236     if (defined($opt{"LOG_FILE"})) {
1237         print " See $opt{LOG_FILE} for more info.\n";
1238     }
1239
1240     die @_, "\n";
1241 }
1242
1243 sub open_console {
1244     my ($fp) = @_;
1245
1246     my $flags;
1247
1248     my $pid = open($fp, "$console|") or
1249         dodie "Can't open console $console";
1250
1251     $flags = fcntl($fp, F_GETFL, 0) or
1252         dodie "Can't get flags for the socket: $!";
1253     $flags = fcntl($fp, F_SETFL, $flags | O_NONBLOCK) or
1254         dodie "Can't set flags for the socket: $!";
1255
1256     return $pid;
1257 }
1258
1259 sub close_console {
1260     my ($fp, $pid) = @_;
1261
1262     doprint "kill child process $pid\n";
1263     kill 2, $pid;
1264
1265     print "closing!\n";
1266     close($fp);
1267 }
1268
1269 sub start_monitor {
1270     if ($monitor_cnt++) {
1271         return;
1272     }
1273     $monitor_fp = \*MONFD;
1274     $monitor_pid = open_console $monitor_fp;
1275
1276     return;
1277
1278     open(MONFD, "Stop perl from warning about single use of MONFD");
1279 }
1280
1281 sub end_monitor {
1282     if (--$monitor_cnt) {
1283         return;
1284     }
1285     close_console($monitor_fp, $monitor_pid);
1286 }
1287
1288 sub wait_for_monitor {
1289     my ($time, $stop) = @_;
1290     my $full_line = "";
1291     my $line;
1292     my $booted = 0;
1293     my $start_time = time;
1294     my $skip_call_trace = 0;
1295     my $bug = 0;
1296     my $bug_ignored = 0;
1297     my $now;
1298
1299     doprint "** Wait for monitor to settle down **\n";
1300
1301     # read the monitor and wait for the system to calm down
1302     while (!$booted) {
1303         $line = wait_for_input($monitor_fp, $time);
1304         last if (!defined($line));
1305         print "$line";
1306         $full_line .= $line;
1307
1308         if (defined($stop) && $full_line =~ /$stop/) {
1309             doprint "wait for monitor detected $stop\n";
1310             $booted = 1;
1311         }
1312
1313         if ($full_line =~ /\[ backtrace testing \]/) {
1314             $skip_call_trace = 1;
1315         }
1316
1317         if ($full_line =~ /call trace:/i) {
1318             if (!$bug && !$skip_call_trace) {
1319                 if ($ignore_errors) {
1320                     $bug_ignored = 1;
1321                 } else {
1322                     $bug = 1;
1323                 }
1324             }
1325         }
1326
1327         if ($full_line =~ /\[ end of backtrace testing \]/) {
1328             $skip_call_trace = 0;
1329         }
1330
1331         if ($full_line =~ /Kernel panic -/) {
1332             $bug = 1;
1333         }
1334
1335         if ($line =~ /\n/) {
1336             $full_line = "";
1337         }
1338         $now = time;
1339         if ($now - $start_time >= $max_monitor_wait) {
1340             doprint "Exiting monitor flush due to hitting MAX_MONITOR_WAIT\n";
1341             return 1;
1342         }
1343     }
1344     print "** Monitor flushed **\n";
1345     return $bug;
1346 }
1347
1348 sub save_logs {
1349         my ($result, $basedir) = @_;
1350         my @t = localtime;
1351         my $date = sprintf "%04d%02d%02d%02d%02d%02d",
1352                 1900+$t[5],$t[4],$t[3],$t[2],$t[1],$t[0];
1353
1354         my $type = $build_type;
1355         if ($type =~ /useconfig/) {
1356             $type = "useconfig";
1357         }
1358
1359         my $dir = "$machine-$test_type-$type-$result-$date";
1360
1361         $dir = "$basedir/$dir";
1362
1363         if (!-d $dir) {
1364             mkpath($dir) or
1365                 die "can't create $dir";
1366         }
1367
1368         my %files = (
1369                 "config" => $output_config,
1370                 "buildlog" => $buildlog,
1371                 "dmesg" => $dmesg,
1372                 "testlog" => $testlog,
1373         );
1374
1375         while (my ($name, $source) = each(%files)) {
1376                 if (-f "$source") {
1377                         cp "$source", "$dir/$name" or
1378                                 die "failed to copy $source";
1379                 }
1380         }
1381
1382         doprint "*** Saved info to $dir ***\n";
1383 }
1384
1385 sub fail {
1386
1387         if (defined($post_test)) {
1388                 run_command $post_test;
1389         }
1390
1391         if ($die_on_failure) {
1392                 dodie @_;
1393         }
1394
1395         doprint "FAILED\n";
1396
1397         my $i = $iteration;
1398
1399         # no need to reboot for just building.
1400         if (!do_not_reboot) {
1401             doprint "REBOOTING\n";
1402             reboot_to_good $sleep_time;
1403         }
1404
1405         my $name = "";
1406
1407         if (defined($test_name)) {
1408             $name = " ($test_name)";
1409         }
1410
1411         doprint "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n";
1412         doprint "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n";
1413         doprint "KTEST RESULT: TEST $i$name Failed: ", @_, "\n";
1414         doprint "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n";
1415         doprint "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n";
1416
1417         if (defined($store_failures)) {
1418             save_logs "fail", $store_failures;
1419         }
1420
1421         return 1;
1422 }
1423
1424 sub run_command {
1425     my ($command) = @_;
1426     my $dolog = 0;
1427     my $dord = 0;
1428     my $pid;
1429
1430     $command =~ s/\$SSH_USER/$ssh_user/g;
1431     $command =~ s/\$MACHINE/$machine/g;
1432
1433     doprint("$command ... ");
1434
1435     $pid = open(CMD, "$command 2>&1 |") or
1436         (fail "unable to exec $command" and return 0);
1437
1438     if (defined($opt{"LOG_FILE"})) {
1439         open(LOG, ">>$opt{LOG_FILE}") or
1440             dodie "failed to write to log";
1441         $dolog = 1;
1442     }
1443
1444     if (defined($redirect)) {
1445         open (RD, ">$redirect") or
1446             dodie "failed to write to redirect $redirect";
1447         $dord = 1;
1448     }
1449
1450     while (<CMD>) {
1451         print LOG if ($dolog);
1452         print RD  if ($dord);
1453     }
1454
1455     waitpid($pid, 0);
1456     my $failed = $?;
1457
1458     close(CMD);
1459     close(LOG) if ($dolog);
1460     close(RD)  if ($dord);
1461
1462     if ($failed) {
1463         doprint "FAILED!\n";
1464     } else {
1465         doprint "SUCCESS\n";
1466     }
1467
1468     return !$failed;
1469 }
1470
1471 sub run_ssh {
1472     my ($cmd) = @_;
1473     my $cp_exec = $ssh_exec;
1474
1475     $cp_exec =~ s/\$SSH_COMMAND/$cmd/g;
1476     return run_command "$cp_exec";
1477 }
1478
1479 sub run_scp {
1480     my ($src, $dst, $cp_scp) = @_;
1481
1482     $cp_scp =~ s/\$SRC_FILE/$src/g;
1483     $cp_scp =~ s/\$DST_FILE/$dst/g;
1484
1485     return run_command "$cp_scp";
1486 }
1487
1488 sub run_scp_install {
1489     my ($src, $dst) = @_;
1490
1491     my $cp_scp = $scp_to_target_install;
1492
1493     return run_scp($src, $dst, $cp_scp);
1494 }
1495
1496 sub run_scp_mod {
1497     my ($src, $dst) = @_;
1498
1499     my $cp_scp = $scp_to_target;
1500
1501     return run_scp($src, $dst, $cp_scp);
1502 }
1503
1504 sub get_grub2_index {
1505
1506     return if (defined($grub_number));
1507
1508     doprint "Find grub2 menu ... ";
1509     $grub_number = -1;
1510
1511     my $ssh_grub = $ssh_exec;
1512     $ssh_grub =~ s,\$SSH_COMMAND,cat $grub_file,g;
1513
1514     open(IN, "$ssh_grub |")
1515         or die "unable to get $grub_file";
1516
1517     my $found = 0;
1518
1519     while (<IN>) {
1520         if (/^menuentry.*$grub_menu/) {
1521             $grub_number++;
1522             $found = 1;
1523             last;
1524         } elsif (/^menuentry\s/) {
1525             $grub_number++;
1526         }
1527     }
1528     close(IN);
1529
1530     die "Could not find '$grub_menu' in $grub_file on $machine"
1531         if (!$found);
1532     doprint "$grub_number\n";
1533 }
1534
1535 sub get_grub_index {
1536
1537     if ($reboot_type eq "grub2") {
1538         get_grub2_index;
1539         return;
1540     }
1541
1542     if ($reboot_type ne "grub") {
1543         return;
1544     }
1545     return if (defined($grub_number));
1546
1547     doprint "Find grub menu ... ";
1548     $grub_number = -1;
1549
1550     my $ssh_grub = $ssh_exec;
1551     $ssh_grub =~ s,\$SSH_COMMAND,cat /boot/grub/menu.lst,g;
1552
1553     open(IN, "$ssh_grub |")
1554         or die "unable to get menu.lst";
1555
1556     my $found = 0;
1557
1558     while (<IN>) {
1559         if (/^\s*title\s+$grub_menu\s*$/) {
1560             $grub_number++;
1561             $found = 1;
1562             last;
1563         } elsif (/^\s*title\s/) {
1564             $grub_number++;
1565         }
1566     }
1567     close(IN);
1568
1569     die "Could not find '$grub_menu' in /boot/grub/menu on $machine"
1570         if (!$found);
1571     doprint "$grub_number\n";
1572 }
1573
1574 sub wait_for_input
1575 {
1576     my ($fp, $time) = @_;
1577     my $rin;
1578     my $ready;
1579     my $line;
1580     my $ch;
1581
1582     if (!defined($time)) {
1583         $time = $timeout;
1584     }
1585
1586     $rin = '';
1587     vec($rin, fileno($fp), 1) = 1;
1588     $ready = select($rin, undef, undef, $time);
1589
1590     $line = "";
1591
1592     # try to read one char at a time
1593     while (sysread $fp, $ch, 1) {
1594         $line .= $ch;
1595         last if ($ch eq "\n");
1596     }
1597
1598     if (!length($line)) {
1599         return undef;
1600     }
1601
1602     return $line;
1603 }
1604
1605 sub reboot_to {
1606     if (defined($switch_to_test)) {
1607         run_command $switch_to_test;
1608     }
1609
1610     if ($reboot_type eq "grub") {
1611         run_ssh "'(echo \"savedefault --default=$grub_number --once\" | grub --batch)'";
1612     } elsif ($reboot_type eq "grub2") {
1613         run_ssh "$grub_reboot $grub_number";
1614     } elsif ($reboot_type eq "syslinux") {
1615         run_ssh "$syslinux --once \\\"$syslinux_label\\\" $syslinux_path";
1616     } elsif (defined $reboot_script) {
1617         run_command "$reboot_script";
1618     }
1619     reboot;
1620 }
1621
1622 sub get_sha1 {
1623     my ($commit) = @_;
1624
1625     doprint "git rev-list --max-count=1 $commit ... ";
1626     my $sha1 = `git rev-list --max-count=1 $commit`;
1627     my $ret = $?;
1628
1629     logit $sha1;
1630
1631     if ($ret) {
1632         doprint "FAILED\n";
1633         dodie "Failed to get git $commit";
1634     }
1635
1636     print "SUCCESS\n";
1637
1638     chomp $sha1;
1639
1640     return $sha1;
1641 }
1642
1643 sub monitor {
1644     my $booted = 0;
1645     my $bug = 0;
1646     my $bug_ignored = 0;
1647     my $skip_call_trace = 0;
1648     my $loops;
1649
1650     wait_for_monitor 5;
1651
1652     my $line;
1653     my $full_line = "";
1654
1655     open(DMESG, "> $dmesg") or
1656         die "unable to write to $dmesg";
1657
1658     reboot_to;
1659
1660     my $success_start;
1661     my $failure_start;
1662     my $monitor_start = time;
1663     my $done = 0;
1664     my $version_found = 0;
1665
1666     while (!$done) {
1667
1668         if ($bug && defined($stop_after_failure) &&
1669             $stop_after_failure >= 0) {
1670             my $time = $stop_after_failure - (time - $failure_start);
1671             $line = wait_for_input($monitor_fp, $time);
1672             if (!defined($line)) {
1673                 doprint "bug timed out after $booted_timeout seconds\n";
1674                 doprint "Test forced to stop after $stop_after_failure seconds after failure\n";
1675                 last;
1676             }
1677         } elsif ($booted) {
1678             $line = wait_for_input($monitor_fp, $booted_timeout);
1679             if (!defined($line)) {
1680                 my $s = $booted_timeout == 1 ? "" : "s";
1681                 doprint "Successful boot found: break after $booted_timeout second$s\n";
1682                 last;
1683             }
1684         } else {
1685             $line = wait_for_input($monitor_fp);
1686             if (!defined($line)) {
1687                 my $s = $timeout == 1 ? "" : "s";
1688                 doprint "Timed out after $timeout second$s\n";
1689                 last;
1690             }
1691         }
1692
1693         doprint $line;
1694         print DMESG $line;
1695
1696         # we are not guaranteed to get a full line
1697         $full_line .= $line;
1698
1699         if ($full_line =~ /$success_line/) {
1700             $booted = 1;
1701             $success_start = time;
1702         }
1703
1704         if ($booted && defined($stop_after_success) &&
1705             $stop_after_success >= 0) {
1706             my $now = time;
1707             if ($now - $success_start >= $stop_after_success) {
1708                 doprint "Test forced to stop after $stop_after_success seconds after success\n";
1709                 last;
1710             }
1711         }
1712
1713         if ($full_line =~ /\[ backtrace testing \]/) {
1714             $skip_call_trace = 1;
1715         }
1716
1717         if ($full_line =~ /call trace:/i) {
1718             if (!$bug && !$skip_call_trace) {
1719                 if ($ignore_errors) {
1720                     $bug_ignored = 1;
1721                 } else {
1722                     $bug = 1;
1723                     $failure_start = time;
1724                 }
1725             }
1726         }
1727
1728         if ($bug && defined($stop_after_failure) &&
1729             $stop_after_failure >= 0) {
1730             my $now = time;
1731             if ($now - $failure_start >= $stop_after_failure) {
1732                 doprint "Test forced to stop after $stop_after_failure seconds after failure\n";
1733                 last;
1734             }
1735         }
1736
1737         if ($full_line =~ /\[ end of backtrace testing \]/) {
1738             $skip_call_trace = 0;
1739         }
1740
1741         if ($full_line =~ /Kernel panic -/) {
1742             $failure_start = time;
1743             $bug = 1;
1744         }
1745
1746         # Detect triple faults by testing the banner
1747         if ($full_line =~ /\bLinux version (\S+).*\n/) {
1748             if ($1 eq $version) {
1749                 $version_found = 1;
1750             } elsif ($version_found && $detect_triplefault) {
1751                 # We already booted into the kernel we are testing,
1752                 # but now we booted into another kernel?
1753                 # Consider this a triple fault.
1754                 doprint "Aleady booted in Linux kernel $version, but now\n";
1755                 doprint "we booted into Linux kernel $1.\n";
1756                 doprint "Assuming that this is a triple fault.\n";
1757                 doprint "To disable this: set DETECT_TRIPLE_FAULT to 0\n";
1758                 last;
1759             }
1760         }
1761
1762         if ($line =~ /\n/) {
1763             $full_line = "";
1764         }
1765
1766         if ($stop_test_after > 0 && !$booted && !$bug) {
1767             if (time - $monitor_start > $stop_test_after) {
1768                 doprint "STOP_TEST_AFTER ($stop_test_after seconds) timed out\n";
1769                 $done = 1;
1770             }
1771         }
1772     }
1773
1774     close(DMESG);
1775
1776     if ($bug) {
1777         return 0 if ($in_bisect);
1778         fail "failed - got a bug report" and return 0;
1779     }
1780
1781     if (!$booted) {
1782         return 0 if ($in_bisect);
1783         fail "failed - never got a boot prompt." and return 0;
1784     }
1785
1786     if ($bug_ignored) {
1787         doprint "WARNING: Call Trace detected but ignored due to IGNORE_ERRORS=1\n";
1788     }
1789
1790     return 1;
1791 }
1792
1793 sub eval_kernel_version {
1794     my ($option) = @_;
1795
1796     $option =~ s/\$KERNEL_VERSION/$version/g;
1797
1798     return $option;
1799 }
1800
1801 sub do_post_install {
1802
1803     return if (!defined($post_install));
1804
1805     my $cp_post_install = eval_kernel_version $post_install;
1806     run_command "$cp_post_install" or
1807         dodie "Failed to run post install";
1808 }
1809
1810 sub install {
1811
1812     return if ($no_install);
1813
1814     if (defined($pre_install)) {
1815         my $cp_pre_install = eval_kernel_version $pre_install;
1816         run_command "$cp_pre_install" or
1817             dodie "Failed to run pre install";
1818     }
1819
1820     my $cp_target = eval_kernel_version $target_image;
1821
1822     run_scp_install "$outputdir/$build_target", "$cp_target" or
1823         dodie "failed to copy image";
1824
1825     my $install_mods = 0;
1826
1827     # should we process modules?
1828     $install_mods = 0;
1829     open(IN, "$output_config") or dodie("Can't read config file");
1830     while (<IN>) {
1831         if (/CONFIG_MODULES(=y)?/) {
1832             if (defined($1)) {
1833                 $install_mods = 1;
1834                 last;
1835             }
1836         }
1837     }
1838     close(IN);
1839
1840     if (!$install_mods) {
1841         do_post_install;
1842         doprint "No modules needed\n";
1843         return;
1844     }
1845
1846     run_command "$make INSTALL_MOD_STRIP=1 INSTALL_MOD_PATH=$tmpdir modules_install" or
1847         dodie "Failed to install modules";
1848
1849     my $modlib = "/lib/modules/$version";
1850     my $modtar = "ktest-mods.tar.bz2";
1851
1852     run_ssh "rm -rf $modlib" or
1853         dodie "failed to remove old mods: $modlib";
1854
1855     # would be nice if scp -r did not follow symbolic links
1856     run_command "cd $tmpdir && tar -cjf $modtar lib/modules/$version" or
1857         dodie "making tarball";
1858
1859     run_scp_mod "$tmpdir/$modtar", "/tmp" or
1860         dodie "failed to copy modules";
1861
1862     unlink "$tmpdir/$modtar";
1863
1864     run_ssh "'(cd / && tar xjf /tmp/$modtar)'" or
1865         dodie "failed to tar modules";
1866
1867     run_ssh "rm -f /tmp/$modtar";
1868
1869     do_post_install;
1870 }
1871
1872 sub get_version {
1873     # get the release name
1874     return if ($have_version);
1875     doprint "$make kernelrelease ... ";
1876     $version = `$make kernelrelease | tail -1`;
1877     chomp($version);
1878     doprint "$version\n";
1879     $have_version = 1;
1880 }
1881
1882 sub start_monitor_and_boot {
1883     # Make sure the stable kernel has finished booting
1884     start_monitor;
1885     wait_for_monitor 5;
1886     end_monitor;
1887
1888     get_grub_index;
1889     get_version;
1890     install;
1891
1892     start_monitor;
1893     return monitor;
1894 }
1895
1896 sub check_buildlog {
1897     my ($patch) = @_;
1898
1899     my @files = `git show $patch | diffstat -l`;
1900
1901     open(IN, "git show $patch |") or
1902         dodie "failed to show $patch";
1903     while (<IN>) {
1904         if (m,^--- a/(.*),) {
1905             chomp $1;
1906             $files[$#files] = $1;
1907         }
1908     }
1909     close(IN);
1910
1911     open(IN, $buildlog) or dodie "Can't open $buildlog";
1912     while (<IN>) {
1913         if (/^\s*(.*?):.*(warning|error)/) {
1914             my $err = $1;
1915             foreach my $file (@files) {
1916                 my $fullpath = "$builddir/$file";
1917                 if ($file eq $err || $fullpath eq $err) {
1918                     fail "$file built with warnings" and return 0;
1919                 }
1920             }
1921         }
1922     }
1923     close(IN);
1924
1925     return 1;
1926 }
1927
1928 sub apply_min_config {
1929     my $outconfig = "$output_config.new";
1930
1931     # Read the config file and remove anything that
1932     # is in the force_config hash (from minconfig and others)
1933     # then add the force config back.
1934
1935     doprint "Applying minimum configurations into $output_config.new\n";
1936
1937     open (OUT, ">$outconfig") or
1938         dodie "Can't create $outconfig";
1939
1940     if (-f $output_config) {
1941         open (IN, $output_config) or
1942             dodie "Failed to open $output_config";
1943         while (<IN>) {
1944             if (/^(# )?(CONFIG_[^\s=]*)/) {
1945                 next if (defined($force_config{$2}));
1946             }
1947             print OUT;
1948         }
1949         close IN;
1950     }
1951     foreach my $config (keys %force_config) {
1952         print OUT "$force_config{$config}\n";
1953     }
1954     close OUT;
1955
1956     run_command "mv $outconfig $output_config";
1957 }
1958
1959 sub make_oldconfig {
1960
1961     my @force_list = keys %force_config;
1962
1963     if ($#force_list >= 0) {
1964         apply_min_config;
1965     }
1966
1967     if (!run_command "$make olddefconfig") {
1968         # Perhaps olddefconfig doesn't exist in this version of the kernel
1969         # try a yes '' | oldconfig
1970         doprint "olddefconfig failed, trying yes '' | make oldconfig\n";
1971         run_command "yes '' | $make oldconfig" or
1972             dodie "failed make config oldconfig";
1973     }
1974 }
1975
1976 # read a config file and use this to force new configs.
1977 sub load_force_config {
1978     my ($config) = @_;
1979
1980     doprint "Loading force configs from $config\n";
1981     open(IN, $config) or
1982         dodie "failed to read $config";
1983     while (<IN>) {
1984         chomp;
1985         if (/^(CONFIG[^\s=]*)(\s*=.*)/) {
1986             $force_config{$1} = $_;
1987         } elsif (/^# (CONFIG_\S*) is not set/) {
1988             $force_config{$1} = $_;
1989         }
1990     }
1991     close IN;
1992 }
1993
1994 sub build {
1995     my ($type) = @_;
1996
1997     unlink $buildlog;
1998
1999     # Failed builds should not reboot the target
2000     my $save_no_reboot = $no_reboot;
2001     $no_reboot = 1;
2002
2003     # Calculate a new version from here.
2004     $have_version = 0;
2005
2006     if (defined($pre_build)) {
2007         my $ret = run_command $pre_build;
2008         if (!$ret && defined($pre_build_die) &&
2009             $pre_build_die) {
2010             dodie "failed to pre_build\n";
2011         }
2012     }
2013
2014     if ($type =~ /^useconfig:(.*)/) {
2015         run_command "cp $1 $output_config" or
2016             dodie "could not copy $1 to .config";
2017
2018         $type = "oldconfig";
2019     }
2020
2021     # old config can ask questions
2022     if ($type eq "oldconfig") {
2023         $type = "olddefconfig";
2024
2025         # allow for empty configs
2026         run_command "touch $output_config";
2027
2028         if (!$noclean) {
2029             run_command "mv $output_config $outputdir/config_temp" or
2030                 dodie "moving .config";
2031
2032             run_command "$make mrproper" or dodie "make mrproper";
2033
2034             run_command "mv $outputdir/config_temp $output_config" or
2035                 dodie "moving config_temp";
2036         }
2037
2038     } elsif (!$noclean) {
2039         unlink "$output_config";
2040         run_command "$make mrproper" or
2041             dodie "make mrproper";
2042     }
2043
2044     # add something to distinguish this build
2045     open(OUT, "> $outputdir/localversion") or dodie("Can't make localversion file");
2046     print OUT "$localversion\n";
2047     close(OUT);
2048
2049     if (defined($minconfig)) {
2050         load_force_config($minconfig);
2051     }
2052
2053     if ($type ne "olddefconfig") {
2054         run_command "$make $type" or
2055             dodie "failed make config";
2056     }
2057     # Run old config regardless, to enforce min configurations
2058     make_oldconfig;
2059
2060     $redirect = "$buildlog";
2061     my $build_ret = run_command "$make $build_options";
2062     undef $redirect;
2063
2064     if (defined($post_build)) {
2065         # Because a post build may change the kernel version
2066         # do it now.
2067         get_version;
2068         my $ret = run_command $post_build;
2069         if (!$ret && defined($post_build_die) &&
2070             $post_build_die) {
2071             dodie "failed to post_build\n";
2072         }
2073     }
2074
2075     if (!$build_ret) {
2076         # bisect may need this to pass
2077         if ($in_bisect) {
2078             $no_reboot = $save_no_reboot;
2079             return 0;
2080         }
2081         fail "failed build" and return 0;
2082     }
2083
2084     $no_reboot = $save_no_reboot;
2085
2086     return 1;
2087 }
2088
2089 sub halt {
2090     if (!run_ssh "halt" or defined($power_off)) {
2091         if (defined($poweroff_after_halt)) {
2092             sleep $poweroff_after_halt;
2093             run_command "$power_off";
2094         }
2095     } else {
2096         # nope? the zap it!
2097         run_command "$power_off";
2098     }
2099 }
2100
2101 sub success {
2102     my ($i) = @_;
2103
2104     if (defined($post_test)) {
2105         run_command $post_test;
2106     }
2107
2108     $successes++;
2109
2110     my $name = "";
2111
2112     if (defined($test_name)) {
2113         $name = " ($test_name)";
2114     }
2115
2116     doprint "\n\n*******************************************\n";
2117     doprint     "*******************************************\n";
2118     doprint     "KTEST RESULT: TEST $i$name SUCCESS!!!!         **\n";
2119     doprint     "*******************************************\n";
2120     doprint     "*******************************************\n";
2121
2122     if (defined($store_successes)) {
2123         save_logs "success", $store_successes;
2124     }
2125
2126     if ($i != $opt{"NUM_TESTS"} && !do_not_reboot) {
2127         doprint "Reboot and wait $sleep_time seconds\n";
2128         reboot_to_good $sleep_time;
2129     }
2130 }
2131
2132 sub answer_bisect {
2133     for (;;) {
2134         doprint "Pass or fail? [p/f]";
2135         my $ans = <STDIN>;
2136         chomp $ans;
2137         if ($ans eq "p" || $ans eq "P") {
2138             return 1;
2139         } elsif ($ans eq "f" || $ans eq "F") {
2140             return 0;
2141         } else {
2142             print "Please answer 'P' or 'F'\n";
2143         }
2144     }
2145 }
2146
2147 sub child_run_test {
2148     my $failed = 0;
2149
2150     # child should have no power
2151     $reboot_on_error = 0;
2152     $poweroff_on_error = 0;
2153     $die_on_failure = 1;
2154
2155     $redirect = "$testlog";
2156     run_command $run_test or $failed = 1;
2157     undef $redirect;
2158
2159     exit $failed;
2160 }
2161
2162 my $child_done;
2163
2164 sub child_finished {
2165     $child_done = 1;
2166 }
2167
2168 sub do_run_test {
2169     my $child_pid;
2170     my $child_exit;
2171     my $line;
2172     my $full_line;
2173     my $bug = 0;
2174     my $bug_ignored = 0;
2175
2176     wait_for_monitor 1;
2177
2178     doprint "run test $run_test\n";
2179
2180     $child_done = 0;
2181
2182     $SIG{CHLD} = qw(child_finished);
2183
2184     $child_pid = fork;
2185
2186     child_run_test if (!$child_pid);
2187
2188     $full_line = "";
2189
2190     do {
2191         $line = wait_for_input($monitor_fp, 1);
2192         if (defined($line)) {
2193
2194             # we are not guaranteed to get a full line
2195             $full_line .= $line;
2196             doprint $line;
2197
2198             if ($full_line =~ /call trace:/i) {
2199                 if ($ignore_errors) {
2200                     $bug_ignored = 1;
2201                 } else {
2202                     $bug = 1;
2203                 }
2204             }
2205
2206             if ($full_line =~ /Kernel panic -/) {
2207                 $bug = 1;
2208             }
2209
2210             if ($line =~ /\n/) {
2211                 $full_line = "";
2212             }
2213         }
2214     } while (!$child_done && !$bug);
2215
2216     if (!$bug && $bug_ignored) {
2217         doprint "WARNING: Call Trace detected but ignored due to IGNORE_ERRORS=1\n";
2218     }
2219
2220     if ($bug) {
2221         my $failure_start = time;
2222         my $now;
2223         do {
2224             $line = wait_for_input($monitor_fp, 1);
2225             if (defined($line)) {
2226                 doprint $line;
2227             }
2228             $now = time;
2229             if ($now - $failure_start >= $stop_after_failure) {
2230                 last;
2231             }
2232         } while (defined($line));
2233
2234         doprint "Detected kernel crash!\n";
2235         # kill the child with extreme prejudice
2236         kill 9, $child_pid;
2237     }
2238
2239     waitpid $child_pid, 0;
2240     $child_exit = $?;
2241
2242     if (!$bug && $in_bisect) {
2243         if (defined($bisect_ret_good)) {
2244             if ($child_exit == $bisect_ret_good) {
2245                 return 1;
2246             }
2247         }
2248         if (defined($bisect_ret_skip)) {
2249             if ($child_exit == $bisect_ret_skip) {
2250                 return -1;
2251             }
2252         }
2253         if (defined($bisect_ret_abort)) {
2254             if ($child_exit == $bisect_ret_abort) {
2255                 fail "test abort" and return -2;
2256             }
2257         }
2258         if (defined($bisect_ret_bad)) {
2259             if ($child_exit == $bisect_ret_skip) {
2260                 return 0;
2261             }
2262         }
2263         if (defined($bisect_ret_default)) {
2264             if ($bisect_ret_default eq "good") {
2265                 return 1;
2266             } elsif ($bisect_ret_default eq "bad") {
2267                 return 0;
2268             } elsif ($bisect_ret_default eq "skip") {
2269                 return -1;
2270             } elsif ($bisect_ret_default eq "abort") {
2271                 return -2;
2272             } else {
2273                 fail "unknown default action: $bisect_ret_default"
2274                     and return -2;
2275             }
2276         }
2277     }
2278
2279     if ($bug || $child_exit) {
2280         return 0 if $in_bisect;
2281         fail "test failed" and return 0;
2282     }
2283     return 1;
2284 }
2285
2286 sub run_git_bisect {
2287     my ($command) = @_;
2288
2289     doprint "$command ... ";
2290
2291     my $output = `$command 2>&1`;
2292     my $ret = $?;
2293
2294     logit $output;
2295
2296     if ($ret) {
2297         doprint "FAILED\n";
2298         dodie "Failed to git bisect";
2299     }
2300
2301     doprint "SUCCESS\n";
2302     if ($output =~ m/^(Bisecting: .*\(roughly \d+ steps?\))\s+\[([[:xdigit:]]+)\]/) {
2303         doprint "$1 [$2]\n";
2304     } elsif ($output =~ m/^([[:xdigit:]]+) is the first bad commit/) {
2305         $bisect_bad_commit = $1;
2306         doprint "Found bad commit... $1\n";
2307         return 0;
2308     } else {
2309         # we already logged it, just print it now.
2310         print $output;
2311     }
2312
2313     return 1;
2314 }
2315
2316 sub bisect_reboot {
2317     doprint "Reboot and sleep $bisect_sleep_time seconds\n";
2318     reboot_to_good $bisect_sleep_time;
2319 }
2320
2321 # returns 1 on success, 0 on failure, -1 on skip
2322 sub run_bisect_test {
2323     my ($type, $buildtype) = @_;
2324
2325     my $failed = 0;
2326     my $result;
2327     my $output;
2328     my $ret;
2329
2330     $in_bisect = 1;
2331
2332     build $buildtype or $failed = 1;
2333
2334     if ($type ne "build") {
2335         if ($failed && $bisect_skip) {
2336             $in_bisect = 0;
2337             return -1;
2338         }
2339         dodie "Failed on build" if $failed;
2340
2341         # Now boot the box
2342         start_monitor_and_boot or $failed = 1;
2343
2344         if ($type ne "boot") {
2345             if ($failed && $bisect_skip) {
2346                 end_monitor;
2347                 bisect_reboot;
2348                 $in_bisect = 0;
2349                 return -1;
2350             }
2351             dodie "Failed on boot" if $failed;
2352
2353             do_run_test or $failed = 1;
2354         }
2355         end_monitor;
2356     }
2357
2358     if ($failed) {
2359         $result = 0;
2360     } else {
2361         $result = 1;
2362     }
2363
2364     # reboot the box to a kernel we can ssh to
2365     if ($type ne "build") {
2366         bisect_reboot;
2367     }
2368     $in_bisect = 0;
2369
2370     return $result;
2371 }
2372
2373 sub run_bisect {
2374     my ($type) = @_;
2375     my $buildtype = "oldconfig";
2376
2377     # We should have a minconfig to use?
2378     if (defined($minconfig)) {
2379         $buildtype = "useconfig:$minconfig";
2380     }
2381
2382     my $ret = run_bisect_test $type, $buildtype;
2383
2384     if ($bisect_manual) {
2385         $ret = answer_bisect;
2386     }
2387
2388     # Are we looking for where it worked, not failed?
2389     if ($reverse_bisect && $ret >= 0) {
2390         $ret = !$ret;
2391     }
2392
2393     if ($ret > 0) {
2394         return "good";
2395     } elsif ($ret == 0) {
2396         return  "bad";
2397     } elsif ($bisect_skip) {
2398         doprint "HIT A BAD COMMIT ... SKIPPING\n";
2399         return "skip";
2400     }
2401 }
2402
2403 sub update_bisect_replay {
2404     my $tmp_log = "$tmpdir/ktest_bisect_log";
2405     run_command "git bisect log > $tmp_log" or
2406         die "can't create bisect log";
2407     return $tmp_log;
2408 }
2409
2410 sub bisect {
2411     my ($i) = @_;
2412
2413     my $result;
2414
2415     die "BISECT_GOOD[$i] not defined\n" if (!defined($bisect_good));
2416     die "BISECT_BAD[$i] not defined\n"  if (!defined($bisect_bad));
2417     die "BISECT_TYPE[$i] not defined\n" if (!defined($bisect_type));
2418
2419     my $good = $bisect_good;
2420     my $bad = $bisect_bad;
2421     my $type = $bisect_type;
2422     my $start = $bisect_start;
2423     my $replay = $bisect_replay;
2424     my $start_files = $bisect_files;
2425
2426     if (defined($start_files)) {
2427         $start_files = " -- " . $start_files;
2428     } else {
2429         $start_files = "";
2430     }
2431
2432     # convert to true sha1's
2433     $good = get_sha1($good);
2434     $bad = get_sha1($bad);
2435
2436     if (defined($bisect_reverse) && $bisect_reverse == 1) {
2437         doprint "Performing a reverse bisect (bad is good, good is bad!)\n";
2438         $reverse_bisect = 1;
2439     } else {
2440         $reverse_bisect = 0;
2441     }
2442
2443     # Can't have a test without having a test to run
2444     if ($type eq "test" && !defined($run_test)) {
2445         $type = "boot";
2446     }
2447
2448     # Check if a bisect was running
2449     my $bisect_start_file = "$builddir/.git/BISECT_START";
2450
2451     my $check = $bisect_check;
2452     my $do_check = defined($check) && $check ne "0";
2453
2454     if ( -f $bisect_start_file ) {
2455         print "Bisect in progress found\n";
2456         if ($do_check) {
2457             print " If you say yes, then no checks of good or bad will be done\n";
2458         }
2459         if (defined($replay)) {
2460             print "** BISECT_REPLAY is defined in config file **";
2461             print " Ignore config option and perform new git bisect log?\n";
2462             if (read_ync " (yes, no, or cancel) ") {
2463                 $replay = update_bisect_replay;
2464                 $do_check = 0;
2465             }
2466         } elsif (read_yn "read git log and continue?") {
2467             $replay = update_bisect_replay;
2468             $do_check = 0;
2469         }
2470     }
2471
2472     if ($do_check) {
2473
2474         # get current HEAD
2475         my $head = get_sha1("HEAD");
2476
2477         if ($check ne "good") {
2478             doprint "TESTING BISECT BAD [$bad]\n";
2479             run_command "git checkout $bad" or
2480                 die "Failed to checkout $bad";
2481
2482             $result = run_bisect $type;
2483
2484             if ($result ne "bad") {
2485                 fail "Tested BISECT_BAD [$bad] and it succeeded" and return 0;
2486             }
2487         }
2488
2489         if ($check ne "bad") {
2490             doprint "TESTING BISECT GOOD [$good]\n";
2491             run_command "git checkout $good" or
2492                 die "Failed to checkout $good";
2493
2494             $result = run_bisect $type;
2495
2496             if ($result ne "good") {
2497                 fail "Tested BISECT_GOOD [$good] and it failed" and return 0;
2498             }
2499         }
2500
2501         # checkout where we started
2502         run_command "git checkout $head" or
2503             die "Failed to checkout $head";
2504     }
2505
2506     run_command "git bisect start$start_files" or
2507         dodie "could not start bisect";
2508
2509     run_command "git bisect good $good" or
2510         dodie "could not set bisect good to $good";
2511
2512     run_git_bisect "git bisect bad $bad" or
2513         dodie "could not set bisect bad to $bad";
2514
2515     if (defined($replay)) {
2516         run_command "git bisect replay $replay" or
2517             dodie "failed to run replay";
2518     }
2519
2520     if (defined($start)) {
2521         run_command "git checkout $start" or
2522             dodie "failed to checkout $start";
2523     }
2524
2525     my $test;
2526     do {
2527         $result = run_bisect $type;
2528         $test = run_git_bisect "git bisect $result";
2529     } while ($test);
2530
2531     run_command "git bisect log" or
2532         dodie "could not capture git bisect log";
2533
2534     run_command "git bisect reset" or
2535         dodie "could not reset git bisect";
2536
2537     doprint "Bad commit was [$bisect_bad_commit]\n";
2538
2539     success $i;
2540 }
2541
2542 # config_ignore holds the configs that were set (or unset) for
2543 # a good config and we will ignore these configs for the rest
2544 # of a config bisect. These configs stay as they were.
2545 my %config_ignore;
2546
2547 # config_set holds what all configs were set as.
2548 my %config_set;
2549
2550 # config_off holds the set of configs that the bad config had disabled.
2551 # We need to record them and set them in the .config when running
2552 # olddefconfig, because olddefconfig keeps the defaults.
2553 my %config_off;
2554
2555 # config_off_tmp holds a set of configs to turn off for now
2556 my @config_off_tmp;
2557
2558 # config_list is the set of configs that are being tested
2559 my %config_list;
2560 my %null_config;
2561
2562 my %dependency;
2563
2564 sub assign_configs {
2565     my ($hash, $config) = @_;
2566
2567     open (IN, $config)
2568         or dodie "Failed to read $config";
2569
2570     while (<IN>) {
2571         if (/^((CONFIG\S*)=.*)/) {
2572             ${$hash}{$2} = $1;
2573         }
2574     }
2575
2576     close(IN);
2577 }
2578
2579 sub process_config_ignore {
2580     my ($config) = @_;
2581
2582     assign_configs \%config_ignore, $config;
2583 }
2584
2585 sub read_current_config {
2586     my ($config_ref) = @_;
2587
2588     %{$config_ref} = ();
2589     undef %{$config_ref};
2590
2591     my @key = keys %{$config_ref};
2592     if ($#key >= 0) {
2593         print "did not delete!\n";
2594         exit;
2595     }
2596     open (IN, "$output_config");
2597
2598     while (<IN>) {
2599         if (/^(CONFIG\S+)=(.*)/) {
2600             ${$config_ref}{$1} = $2;
2601         }
2602     }
2603     close(IN);
2604 }
2605
2606 sub get_dependencies {
2607     my ($config) = @_;
2608
2609     my $arr = $dependency{$config};
2610     if (!defined($arr)) {
2611         return ();
2612     }
2613
2614     my @deps = @{$arr};
2615
2616     foreach my $dep (@{$arr}) {
2617         print "ADD DEP $dep\n";
2618         @deps = (@deps, get_dependencies $dep);
2619     }
2620
2621     return @deps;
2622 }
2623
2624 sub create_config {
2625     my @configs = @_;
2626
2627     open(OUT, ">$output_config") or dodie "Can not write to $output_config";
2628
2629     foreach my $config (@configs) {
2630         print OUT "$config_set{$config}\n";
2631         my @deps = get_dependencies $config;
2632         foreach my $dep (@deps) {
2633             print OUT "$config_set{$dep}\n";
2634         }
2635     }
2636
2637     # turn off configs to keep off
2638     foreach my $config (keys %config_off) {
2639         print OUT "# $config is not set\n";
2640     }
2641
2642     # turn off configs that should be off for now
2643     foreach my $config (@config_off_tmp) {
2644         print OUT "# $config is not set\n";
2645     }
2646
2647     foreach my $config (keys %config_ignore) {
2648         print OUT "$config_ignore{$config}\n";
2649     }
2650     close(OUT);
2651
2652     make_oldconfig;
2653 }
2654
2655 sub compare_configs {
2656     my (%a, %b) = @_;
2657
2658     foreach my $item (keys %a) {
2659         if (!defined($b{$item})) {
2660             print "diff $item\n";
2661             return 1;
2662         }
2663         delete $b{$item};
2664     }
2665
2666     my @keys = keys %b;
2667     if ($#keys) {
2668         print "diff2 $keys[0]\n";
2669     }
2670     return -1 if ($#keys >= 0);
2671
2672     return 0;
2673 }
2674
2675 sub run_config_bisect_test {
2676     my ($type) = @_;
2677
2678     return run_bisect_test $type, "oldconfig";
2679 }
2680
2681 sub process_passed {
2682     my (%configs) = @_;
2683
2684     doprint "These configs had no failure: (Enabling them for further compiles)\n";
2685     # Passed! All these configs are part of a good compile.
2686     # Add them to the min options.
2687     foreach my $config (keys %configs) {
2688         if (defined($config_list{$config})) {
2689             doprint " removing $config\n";
2690             $config_ignore{$config} = $config_list{$config};
2691             delete $config_list{$config};
2692         }
2693     }
2694     doprint "config copied to $outputdir/config_good\n";
2695     run_command "cp -f $output_config $outputdir/config_good";
2696 }
2697
2698 sub process_failed {
2699     my ($config) = @_;
2700
2701     doprint "\n\n***************************************\n";
2702     doprint "Found bad config: $config\n";
2703     doprint "***************************************\n\n";
2704 }
2705
2706 sub run_config_bisect {
2707
2708     my @start_list = keys %config_list;
2709
2710     if ($#start_list < 0) {
2711         doprint "No more configs to test!!!\n";
2712         return -1;
2713     }
2714
2715     doprint "***** RUN TEST ***\n";
2716     my $type = $config_bisect_type;
2717     my $ret;
2718     my %current_config;
2719
2720     my $count = $#start_list + 1;
2721     doprint "  $count configs to test\n";
2722
2723     my $half = int($#start_list / 2);
2724
2725     do {
2726         my @tophalf = @start_list[0 .. $half];
2727
2728         # keep the bottom half off
2729         if ($half < $#start_list) {
2730             @config_off_tmp = @start_list[$half + 1 .. $#start_list];
2731         } else {
2732             @config_off_tmp = ();
2733         }
2734
2735         create_config @tophalf;
2736         read_current_config \%current_config;
2737
2738         $count = $#tophalf + 1;
2739         doprint "Testing $count configs\n";
2740         my $found = 0;
2741         # make sure we test something
2742         foreach my $config (@tophalf) {
2743             if (defined($current_config{$config})) {
2744                 logit " $config\n";
2745                 $found = 1;
2746             }
2747         }
2748         if (!$found) {
2749             # try the other half
2750             doprint "Top half produced no set configs, trying bottom half\n";
2751
2752             # keep the top half off
2753             @config_off_tmp = @tophalf;
2754             @tophalf = @start_list[$half + 1 .. $#start_list];
2755
2756             create_config @tophalf;
2757             read_current_config \%current_config;
2758             foreach my $config (@tophalf) {
2759                 if (defined($current_config{$config})) {
2760                     logit " $config\n";
2761                     $found = 1;
2762                 }
2763             }
2764             if (!$found) {
2765                 doprint "Failed: Can't make new config with current configs\n";
2766                 foreach my $config (@start_list) {
2767                     doprint "  CONFIG: $config\n";
2768                 }
2769                 return -1;
2770             }
2771             $count = $#tophalf + 1;
2772             doprint "Testing $count configs\n";
2773         }
2774
2775         $ret = run_config_bisect_test $type;
2776         if ($bisect_manual) {
2777             $ret = answer_bisect;
2778         }
2779         if ($ret) {
2780             process_passed %current_config;
2781             return 0;
2782         }
2783
2784         doprint "This config had a failure.\n";
2785         doprint "Removing these configs that were not set in this config:\n";
2786         doprint "config copied to $outputdir/config_bad\n";
2787         run_command "cp -f $output_config $outputdir/config_bad";
2788
2789         # A config exists in this group that was bad.
2790         foreach my $config (keys %config_list) {
2791             if (!defined($current_config{$config})) {
2792                 doprint " removing $config\n";
2793                 delete $config_list{$config};
2794             }
2795         }
2796
2797         @start_list = @tophalf;
2798
2799         if ($#start_list == 0) {
2800             process_failed $start_list[0];
2801             return 1;
2802         }
2803
2804         # remove half the configs we are looking at and see if
2805         # they are good.
2806         $half = int($#start_list / 2);
2807     } while ($#start_list > 0);
2808
2809     # we found a single config, try it again unless we are running manually
2810
2811     if ($bisect_manual) {
2812         process_failed $start_list[0];
2813         return 1;
2814     }
2815
2816     my @tophalf = @start_list[0 .. 0];
2817
2818     $ret = run_config_bisect_test $type;
2819     if ($ret) {
2820         process_passed %current_config;
2821         return 0;
2822     }
2823
2824     process_failed $start_list[0];
2825     return 1;
2826 }
2827
2828 sub config_bisect {
2829     my ($i) = @_;
2830
2831     my $start_config = $config_bisect;
2832
2833     my $tmpconfig = "$tmpdir/use_config";
2834
2835     if (defined($config_bisect_good)) {
2836         process_config_ignore $config_bisect_good;
2837     }
2838
2839     # Make the file with the bad config and the min config
2840     if (defined($minconfig)) {
2841         # read the min config for things to ignore
2842         run_command "cp $minconfig $tmpconfig" or
2843             dodie "failed to copy $minconfig to $tmpconfig";
2844     } else {
2845         unlink $tmpconfig;
2846     }
2847
2848     if (-f $tmpconfig) {
2849         load_force_config($tmpconfig);
2850         process_config_ignore $tmpconfig;
2851     }
2852
2853     # now process the start config
2854     run_command "cp $start_config $output_config" or
2855         dodie "failed to copy $start_config to $output_config";
2856
2857     # read directly what we want to check
2858     my %config_check;
2859     open (IN, $output_config)
2860         or dodie "failed to open $output_config";
2861
2862     while (<IN>) {
2863         if (/^((CONFIG\S*)=.*)/) {
2864             $config_check{$2} = $1;
2865         }
2866     }
2867     close(IN);
2868
2869     # Now run oldconfig with the minconfig
2870     make_oldconfig;
2871
2872     # check to see what we lost (or gained)
2873     open (IN, $output_config)
2874         or dodie "Failed to read $start_config";
2875
2876     my %removed_configs;
2877     my %added_configs;
2878
2879     while (<IN>) {
2880         if (/^((CONFIG\S*)=.*)/) {
2881             # save off all options
2882             $config_set{$2} = $1;
2883             if (defined($config_check{$2})) {
2884                 if (defined($config_ignore{$2})) {
2885                     $removed_configs{$2} = $1;
2886                 } else {
2887                     $config_list{$2} = $1;
2888                 }
2889             } elsif (!defined($config_ignore{$2})) {
2890                 $added_configs{$2} = $1;
2891                 $config_list{$2} = $1;
2892             }
2893         } elsif (/^# ((CONFIG\S*).*)/) {
2894             # Keep these configs disabled
2895             $config_set{$2} = $1;
2896             $config_off{$2} = $1;
2897         }
2898     }
2899     close(IN);
2900
2901     my @confs = keys %removed_configs;
2902     if ($#confs >= 0) {
2903         doprint "Configs overridden by default configs and removed from check:\n";
2904         foreach my $config (@confs) {
2905             doprint " $config\n";
2906         }
2907     }
2908     @confs = keys %added_configs;
2909     if ($#confs >= 0) {
2910         doprint "Configs appearing in make oldconfig and added:\n";
2911         foreach my $config (@confs) {
2912             doprint " $config\n";
2913         }
2914     }
2915
2916     my %config_test;
2917     my $once = 0;
2918
2919     @config_off_tmp = ();
2920
2921     # Sometimes kconfig does weird things. We must make sure
2922     # that the config we autocreate has everything we need
2923     # to test, otherwise we may miss testing configs, or
2924     # may not be able to create a new config.
2925     # Here we create a config with everything set.
2926     create_config (keys %config_list);
2927     read_current_config \%config_test;
2928     foreach my $config (keys %config_list) {
2929         if (!defined($config_test{$config})) {
2930             if (!$once) {
2931                 $once = 1;
2932                 doprint "Configs not produced by kconfig (will not be checked):\n";
2933             }
2934             doprint "  $config\n";
2935             delete $config_list{$config};
2936         }
2937     }
2938     my $ret;
2939
2940     if (defined($config_bisect_check) && $config_bisect_check) {
2941         doprint " Checking to make sure bad config with min config fails\n";
2942         create_config keys %config_list;
2943         $ret = run_config_bisect_test $config_bisect_type;
2944         if ($ret) {
2945             doprint " FAILED! Bad config with min config boots fine\n";
2946             return -1;
2947         }
2948         doprint " Bad config with min config fails as expected\n";
2949     }
2950
2951     do {
2952         $ret = run_config_bisect;
2953     } while (!$ret);
2954
2955     return $ret if ($ret < 0);
2956
2957     success $i;
2958 }
2959
2960 sub patchcheck_reboot {
2961     doprint "Reboot and sleep $patchcheck_sleep_time seconds\n";
2962     reboot_to_good $patchcheck_sleep_time;
2963 }
2964
2965 sub patchcheck {
2966     my ($i) = @_;
2967
2968     die "PATCHCHECK_START[$i] not defined\n"
2969         if (!defined($patchcheck_start));
2970     die "PATCHCHECK_TYPE[$i] not defined\n"
2971         if (!defined($patchcheck_type));
2972
2973     my $start = $patchcheck_start;
2974
2975     my $end = "HEAD";
2976     if (defined($patchcheck_end)) {
2977         $end = $patchcheck_end;
2978     }
2979
2980     # Get the true sha1's since we can use things like HEAD~3
2981     $start = get_sha1($start);
2982     $end = get_sha1($end);
2983
2984     my $type = $patchcheck_type;
2985
2986     # Can't have a test without having a test to run
2987     if ($type eq "test" && !defined($run_test)) {
2988         $type = "boot";
2989     }
2990
2991     open (IN, "git log --pretty=oneline $end|") or
2992         dodie "could not get git list";
2993
2994     my @list;
2995
2996     while (<IN>) {
2997         chomp;
2998         $list[$#list+1] = $_;
2999         last if (/^$start/);
3000     }
3001     close(IN);
3002
3003     if ($list[$#list] !~ /^$start/) {
3004         fail "SHA1 $start not found";
3005     }
3006
3007     # go backwards in the list
3008     @list = reverse @list;
3009
3010     my $save_clean = $noclean;
3011     my %ignored_warnings;
3012
3013     if (defined($ignore_warnings)) {
3014         foreach my $sha1 (split /\s+/, $ignore_warnings) {
3015             $ignored_warnings{$sha1} = 1;
3016         }
3017     }
3018
3019     $in_patchcheck = 1;
3020     foreach my $item (@list) {
3021         my $sha1 = $item;
3022         $sha1 =~ s/^([[:xdigit:]]+).*/$1/;
3023
3024         doprint "\nProcessing commit $item\n\n";
3025
3026         run_command "git checkout $sha1" or
3027             die "Failed to checkout $sha1";
3028
3029         # only clean on the first and last patch
3030         if ($item eq $list[0] ||
3031             $item eq $list[$#list]) {
3032             $noclean = $save_clean;
3033         } else {
3034             $noclean = 1;
3035         }
3036
3037         if (defined($minconfig)) {
3038             build "useconfig:$minconfig" or return 0;
3039         } else {
3040             # ?? no config to use?
3041             build "oldconfig" or return 0;
3042         }
3043
3044
3045         if (!defined($ignored_warnings{$sha1})) {
3046             check_buildlog $sha1 or return 0;
3047         }
3048
3049         next if ($type eq "build");
3050
3051         my $failed = 0;
3052
3053         start_monitor_and_boot or $failed = 1;
3054
3055         if (!$failed && $type ne "boot"){
3056             do_run_test or $failed = 1;
3057         }
3058         end_monitor;
3059         return 0 if ($failed);
3060
3061         patchcheck_reboot;
3062
3063     }
3064     $in_patchcheck = 0;
3065     success $i;
3066
3067     return 1;
3068 }
3069
3070 my %depends;
3071 my %depcount;
3072 my $iflevel = 0;
3073 my @ifdeps;
3074
3075 # prevent recursion
3076 my %read_kconfigs;
3077
3078 sub add_dep {
3079     # $config depends on $dep
3080     my ($config, $dep) = @_;
3081
3082     if (defined($depends{$config})) {
3083         $depends{$config} .= " " . $dep;
3084     } else {
3085         $depends{$config} = $dep;
3086     }
3087
3088     # record the number of configs depending on $dep
3089     if (defined $depcount{$dep}) {
3090         $depcount{$dep}++;
3091     } else {
3092         $depcount{$dep} = 1;
3093     } 
3094 }
3095
3096 # taken from streamline_config.pl
3097 sub read_kconfig {
3098     my ($kconfig) = @_;
3099
3100     my $state = "NONE";
3101     my $config;
3102     my @kconfigs;
3103
3104     my $cont = 0;
3105     my $line;
3106
3107
3108     if (! -f $kconfig) {
3109         doprint "file $kconfig does not exist, skipping\n";
3110         return;
3111     }
3112
3113     open(KIN, "$kconfig")
3114         or die "Can't open $kconfig";
3115     while (<KIN>) {
3116         chomp;
3117
3118         # Make sure that lines ending with \ continue
3119         if ($cont) {
3120             $_ = $line . " " . $_;
3121         }
3122
3123         if (s/\\$//) {
3124             $cont = 1;
3125             $line = $_;
3126             next;
3127         }
3128
3129         $cont = 0;
3130
3131         # collect any Kconfig sources
3132         if (/^source\s*"(.*)"/) {
3133             $kconfigs[$#kconfigs+1] = $1;
3134         }
3135
3136         # configs found
3137         if (/^\s*(menu)?config\s+(\S+)\s*$/) {
3138             $state = "NEW";
3139             $config = $2;
3140
3141             for (my $i = 0; $i < $iflevel; $i++) {
3142                 add_dep $config, $ifdeps[$i];
3143             }
3144
3145         # collect the depends for the config
3146         } elsif ($state eq "NEW" && /^\s*depends\s+on\s+(.*)$/) {
3147
3148             add_dep $config, $1;
3149
3150         # Get the configs that select this config
3151         } elsif ($state eq "NEW" && /^\s*select\s+(\S+)/) {
3152
3153             # selected by depends on config
3154             add_dep $1, $config;
3155
3156         # Check for if statements
3157         } elsif (/^if\s+(.*\S)\s*$/) {
3158             my $deps = $1;
3159             # remove beginning and ending non text
3160             $deps =~ s/^[^a-zA-Z0-9_]*//;
3161             $deps =~ s/[^a-zA-Z0-9_]*$//;
3162
3163             my @deps = split /[^a-zA-Z0-9_]+/, $deps;
3164
3165             $ifdeps[$iflevel++] = join ':', @deps;
3166
3167         } elsif (/^endif/) {
3168
3169             $iflevel-- if ($iflevel);
3170
3171         # stop on "help"
3172         } elsif (/^\s*help\s*$/) {
3173             $state = "NONE";
3174         }
3175     }
3176     close(KIN);
3177
3178     # read in any configs that were found.
3179     foreach $kconfig (@kconfigs) {
3180         if (!defined($read_kconfigs{$kconfig})) {
3181             $read_kconfigs{$kconfig} = 1;
3182             read_kconfig("$builddir/$kconfig");
3183         }
3184     }
3185 }
3186
3187 sub read_depends {
3188     # find out which arch this is by the kconfig file
3189     open (IN, $output_config)
3190         or dodie "Failed to read $output_config";
3191     my $arch;
3192     while (<IN>) {
3193         if (m,Linux/(\S+)\s+\S+\s+Kernel Configuration,) {
3194             $arch = $1;
3195             last;
3196         }
3197     }
3198     close IN;
3199
3200     if (!defined($arch)) {
3201         doprint "Could not find arch from config file\n";
3202         doprint "no dependencies used\n";
3203         return;
3204     }
3205
3206     # arch is really the subarch, we need to know
3207     # what directory to look at.
3208     if ($arch eq "i386" || $arch eq "x86_64") {
3209         $arch = "x86";
3210     } elsif ($arch =~ /^tile/) {
3211         $arch = "tile";
3212     }
3213
3214     my $kconfig = "$builddir/arch/$arch/Kconfig";
3215
3216     if (! -f $kconfig && $arch =~ /\d$/) {
3217         my $orig = $arch;
3218         # some subarchs have numbers, truncate them
3219         $arch =~ s/\d*$//;
3220         $kconfig = "$builddir/arch/$arch/Kconfig";
3221         if (! -f $kconfig) {
3222             doprint "No idea what arch dir $orig is for\n";
3223             doprint "no dependencies used\n";
3224             return;
3225         }
3226     }
3227
3228     read_kconfig($kconfig);
3229 }
3230
3231 sub read_config_list {
3232     my ($config) = @_;
3233
3234     open (IN, $config)
3235         or dodie "Failed to read $config";
3236
3237     while (<IN>) {
3238         if (/^((CONFIG\S*)=.*)/) {
3239             if (!defined($config_ignore{$2})) {
3240                 $config_list{$2} = $1;
3241             }
3242         }
3243     }
3244
3245     close(IN);
3246 }
3247
3248 sub read_output_config {
3249     my ($config) = @_;
3250
3251     assign_configs \%config_ignore, $config;
3252 }
3253
3254 sub make_new_config {
3255     my @configs = @_;
3256
3257     open (OUT, ">$output_config")
3258         or dodie "Failed to write $output_config";
3259
3260     foreach my $config (@configs) {
3261         print OUT "$config\n";
3262     }
3263     close OUT;
3264 }
3265
3266 sub chomp_config {
3267     my ($config) = @_;
3268
3269     $config =~ s/CONFIG_//;
3270
3271     return $config;
3272 }
3273
3274 sub get_depends {
3275     my ($dep) = @_;
3276
3277     my $kconfig = chomp_config $dep;
3278
3279     $dep = $depends{"$kconfig"};
3280
3281     # the dep string we have saves the dependencies as they
3282     # were found, including expressions like ! && ||. We
3283     # want to split this out into just an array of configs.
3284
3285     my $valid = "A-Za-z_0-9";
3286
3287     my @configs;
3288
3289     while ($dep =~ /[$valid]/) {
3290
3291         if ($dep =~ /^[^$valid]*([$valid]+)/) {
3292             my $conf = "CONFIG_" . $1;
3293
3294             $configs[$#configs + 1] = $conf;
3295
3296             $dep =~ s/^[^$valid]*[$valid]+//;
3297         } else {
3298             die "this should never happen";
3299         }
3300     }
3301
3302     return @configs;
3303 }
3304
3305 my %min_configs;
3306 my %keep_configs;
3307 my %save_configs;
3308 my %processed_configs;
3309 my %nochange_config;
3310
3311 sub test_this_config {
3312     my ($config) = @_;
3313
3314     my $found;
3315
3316     # if we already processed this config, skip it
3317     if (defined($processed_configs{$config})) {
3318         return undef;
3319     }
3320     $processed_configs{$config} = 1;
3321
3322     # if this config failed during this round, skip it
3323     if (defined($nochange_config{$config})) {
3324         return undef;
3325     }
3326
3327     my $kconfig = chomp_config $config;
3328
3329     # Test dependencies first
3330     if (defined($depends{"$kconfig"})) {
3331         my @parents = get_depends $config;
3332         foreach my $parent (@parents) {
3333             # if the parent is in the min config, check it first
3334             next if (!defined($min_configs{$parent}));
3335             $found = test_this_config($parent);
3336             if (defined($found)) {
3337                 return $found;
3338             }
3339         }
3340     }
3341
3342     # Remove this config from the list of configs
3343     # do a make olddefconfig and then read the resulting
3344     # .config to make sure it is missing the config that
3345     # we had before
3346     my %configs = %min_configs;
3347     delete $configs{$config};
3348     make_new_config ((values %configs), (values %keep_configs));
3349     make_oldconfig;
3350     undef %configs;
3351     assign_configs \%configs, $output_config;
3352
3353     return $config if (!defined($configs{$config}));
3354
3355     doprint "disabling config $config did not change .config\n";
3356
3357     $nochange_config{$config} = 1;
3358
3359     return undef;
3360 }
3361
3362 sub make_min_config {
3363     my ($i) = @_;
3364
3365     my $type = $minconfig_type;
3366     if ($type ne "boot" && $type ne "test") {
3367         fail "Invalid MIN_CONFIG_TYPE '$minconfig_type'\n" .
3368             " make_min_config works only with 'boot' and 'test'\n" and return;
3369     }
3370
3371     if (!defined($output_minconfig)) {
3372         fail "OUTPUT_MIN_CONFIG not defined" and return;
3373     }
3374
3375     # If output_minconfig exists, and the start_minconfig
3376     # came from min_config, than ask if we should use
3377     # that instead.
3378     if (-f $output_minconfig && !$start_minconfig_defined) {
3379         print "$output_minconfig exists\n";
3380         if (!defined($use_output_minconfig)) {
3381             if (read_yn " Use it as minconfig?") {
3382                 $start_minconfig = $output_minconfig;
3383             }
3384         } elsif ($use_output_minconfig > 0) {
3385             doprint "Using $output_minconfig as MIN_CONFIG\n";
3386             $start_minconfig = $output_minconfig;
3387         } else {
3388             doprint "Set to still use MIN_CONFIG as starting point\n";
3389         }
3390     }
3391
3392     if (!defined($start_minconfig)) {
3393         fail "START_MIN_CONFIG or MIN_CONFIG not defined" and return;
3394     }
3395
3396     my $temp_config = "$tmpdir/temp_config";
3397
3398     # First things first. We build an allnoconfig to find
3399     # out what the defaults are that we can't touch.
3400     # Some are selections, but we really can't handle selections.
3401
3402     my $save_minconfig = $minconfig;
3403     undef $minconfig;
3404
3405     run_command "$make allnoconfig" or return 0;
3406
3407     read_depends;
3408
3409     process_config_ignore $output_config;
3410
3411     undef %save_configs;
3412     undef %min_configs;
3413
3414     if (defined($ignore_config)) {
3415         # make sure the file exists
3416         `touch $ignore_config`;
3417         assign_configs \%save_configs, $ignore_config;
3418     }
3419
3420     %keep_configs = %save_configs;
3421
3422     doprint "Load initial configs from $start_minconfig\n";
3423
3424     # Look at the current min configs, and save off all the
3425     # ones that were set via the allnoconfig
3426     assign_configs \%min_configs, $start_minconfig;
3427
3428     my @config_keys = keys %min_configs;
3429
3430     # All configs need a depcount
3431     foreach my $config (@config_keys) {
3432         my $kconfig = chomp_config $config;
3433         if (!defined $depcount{$kconfig}) {
3434                 $depcount{$kconfig} = 0;
3435         }
3436     }
3437
3438     # Remove anything that was set by the make allnoconfig
3439     # we shouldn't need them as they get set for us anyway.
3440     foreach my $config (@config_keys) {
3441         # Remove anything in the ignore_config
3442         if (defined($keep_configs{$config})) {
3443             my $file = $ignore_config;
3444             $file =~ s,.*/(.*?)$,$1,;
3445             doprint "$config set by $file ... ignored\n";
3446             delete $min_configs{$config};
3447             next;
3448         }
3449         # But make sure the settings are the same. If a min config
3450         # sets a selection, we do not want to get rid of it if
3451         # it is not the same as what we have. Just move it into
3452         # the keep configs.
3453         if (defined($config_ignore{$config})) {
3454             if ($config_ignore{$config} ne $min_configs{$config}) {
3455                 doprint "$config is in allnoconfig as '$config_ignore{$config}'";
3456                 doprint " but it is '$min_configs{$config}' in minconfig .. keeping\n";
3457                 $keep_configs{$config} = $min_configs{$config};
3458             } else {
3459                 doprint "$config set by allnoconfig ... ignored\n";
3460             }
3461             delete $min_configs{$config};
3462         }
3463     }
3464
3465     my $done = 0;
3466     my $take_two = 0;
3467
3468     while (!$done) {
3469
3470         my $config;
3471         my $found;
3472
3473         # Now disable each config one by one and do a make oldconfig
3474         # till we find a config that changes our list.
3475
3476         my @test_configs = keys %min_configs;
3477
3478         # Sort keys by who is most dependent on
3479         @test_configs = sort  { $depcount{chomp_config($b)} <=> $depcount{chomp_config($a)} }
3480                           @test_configs ;
3481
3482         # Put configs that did not modify the config at the end.
3483         my $reset = 1;
3484         for (my $i = 0; $i < $#test_configs; $i++) {
3485             if (!defined($nochange_config{$test_configs[0]})) {
3486                 $reset = 0;
3487                 last;
3488             }
3489             # This config didn't change the .config last time.
3490             # Place it at the end
3491             my $config = shift @test_configs;
3492             push @test_configs, $config;
3493         }
3494
3495         # if every test config has failed to modify the .config file
3496         # in the past, then reset and start over.
3497         if ($reset) {
3498             undef %nochange_config;
3499         }
3500
3501         undef %processed_configs;
3502
3503         foreach my $config (@test_configs) {
3504
3505             $found = test_this_config $config;
3506
3507             last if (defined($found));
3508
3509             # oh well, try another config
3510         }
3511
3512         if (!defined($found)) {
3513             # we could have failed due to the nochange_config hash
3514             # reset and try again
3515             if (!$take_two) {
3516                 undef %nochange_config;
3517                 $take_two = 1;
3518                 next;
3519             }
3520             doprint "No more configs found that we can disable\n";
3521             $done = 1;
3522             last;
3523         }
3524         $take_two = 0;
3525
3526         $config = $found;
3527
3528         doprint "Test with $config disabled\n";
3529
3530         # set in_bisect to keep build and monitor from dieing
3531         $in_bisect = 1;
3532
3533         my $failed = 0;
3534         build "oldconfig" or $failed = 1;
3535         if (!$failed) {
3536                 start_monitor_and_boot or $failed = 1;
3537
3538                 if ($type eq "test" && !$failed) {
3539                     do_run_test or $failed = 1;
3540                 }
3541
3542                 end_monitor;
3543         }
3544
3545         $in_bisect = 0;
3546
3547         if ($failed) {
3548             doprint "$min_configs{$config} is needed to boot the box... keeping\n";
3549             # this config is needed, add it to the ignore list.
3550             $keep_configs{$config} = $min_configs{$config};
3551             $save_configs{$config} = $min_configs{$config};
3552             delete $min_configs{$config};
3553
3554             # update new ignore configs
3555             if (defined($ignore_config)) {
3556                 open (OUT, ">$temp_config")
3557                     or die "Can't write to $temp_config";
3558                 foreach my $config (keys %save_configs) {
3559                     print OUT "$save_configs{$config}\n";
3560                 }
3561                 close OUT;
3562                 run_command "mv $temp_config $ignore_config" or
3563                     dodie "failed to copy update to $ignore_config";
3564             }
3565
3566         } else {
3567             # We booted without this config, remove it from the minconfigs.
3568             doprint "$config is not needed, disabling\n";
3569
3570             delete $min_configs{$config};
3571
3572             # Also disable anything that is not enabled in this config
3573             my %configs;
3574             assign_configs \%configs, $output_config;
3575             my @config_keys = keys %min_configs;
3576             foreach my $config (@config_keys) {
3577                 if (!defined($configs{$config})) {
3578                     doprint "$config is not set, disabling\n";
3579                     delete $min_configs{$config};
3580                 }
3581             }
3582
3583             # Save off all the current mandidory configs
3584             open (OUT, ">$temp_config")
3585                 or die "Can't write to $temp_config";
3586             foreach my $config (keys %keep_configs) {
3587                 print OUT "$keep_configs{$config}\n";
3588             }
3589             foreach my $config (keys %min_configs) {
3590                 print OUT "$min_configs{$config}\n";
3591             }
3592             close OUT;
3593
3594             run_command "mv $temp_config $output_minconfig" or
3595                 dodie "failed to copy update to $output_minconfig";
3596         }
3597
3598         doprint "Reboot and wait $sleep_time seconds\n";
3599         reboot_to_good $sleep_time;
3600     }
3601
3602     success $i;
3603     return 1;
3604 }
3605
3606 $#ARGV < 1 or die "ktest.pl version: $VERSION\n   usage: ktest.pl config-file\n";
3607
3608 if ($#ARGV == 0) {
3609     $ktest_config = $ARGV[0];
3610     if (! -f $ktest_config) {
3611         print "$ktest_config does not exist.\n";
3612         if (!read_yn "Create it?") {
3613             exit 0;
3614         }
3615     }
3616 } else {
3617     $ktest_config = "ktest.conf";
3618 }
3619
3620 if (! -f $ktest_config) {
3621     $newconfig = 1;
3622     get_test_case;
3623     open(OUT, ">$ktest_config") or die "Can not create $ktest_config";
3624     print OUT << "EOF"
3625 # Generated by ktest.pl
3626 #
3627
3628 # PWD is a ktest.pl variable that will result in the process working
3629 # directory that ktest.pl is executed in.
3630
3631 # THIS_DIR is automatically assigned the PWD of the path that generated
3632 # the config file. It is best to use this variable when assigning other
3633 # directory paths within this directory. This allows you to easily
3634 # move the test cases to other locations or to other machines.
3635 #
3636 THIS_DIR := $variable{"PWD"}
3637
3638 # Define each test with TEST_START
3639 # The config options below it will override the defaults
3640 TEST_START
3641 TEST_TYPE = $default{"TEST_TYPE"}
3642
3643 DEFAULTS
3644 EOF
3645 ;
3646     close(OUT);
3647 }
3648 read_config $ktest_config;
3649
3650 if (defined($opt{"LOG_FILE"})) {
3651     $opt{"LOG_FILE"} = eval_option($opt{"LOG_FILE"}, -1);
3652 }
3653
3654 # Append any configs entered in manually to the config file.
3655 my @new_configs = keys %entered_configs;
3656 if ($#new_configs >= 0) {
3657     print "\nAppending entered in configs to $ktest_config\n";
3658     open(OUT, ">>$ktest_config") or die "Can not append to $ktest_config";
3659     foreach my $config (@new_configs) {
3660         print OUT "$config = $entered_configs{$config}\n";
3661         $opt{$config} = process_variables($entered_configs{$config});
3662     }
3663 }
3664
3665 if ($opt{"CLEAR_LOG"} && defined($opt{"LOG_FILE"})) {
3666     unlink $opt{"LOG_FILE"};
3667 }
3668
3669 doprint "\n\nSTARTING AUTOMATED TESTS\n\n";
3670
3671 for (my $i = 0, my $repeat = 1; $i <= $opt{"NUM_TESTS"}; $i += $repeat) {
3672
3673     if (!$i) {
3674         doprint "DEFAULT OPTIONS:\n";
3675     } else {
3676         doprint "\nTEST $i OPTIONS";
3677         if (defined($repeat_tests{$i})) {
3678             $repeat = $repeat_tests{$i};
3679             doprint " ITERATE $repeat";
3680         }
3681         doprint "\n";
3682     }
3683
3684     foreach my $option (sort keys %opt) {
3685
3686         if ($option =~ /\[(\d+)\]$/) {
3687             next if ($i != $1);
3688         } else {
3689             next if ($i);
3690         }
3691
3692         doprint "$option = $opt{$option}\n";
3693     }
3694 }
3695
3696 sub __set_test_option {
3697     my ($name, $i) = @_;
3698
3699     my $option = "$name\[$i\]";
3700
3701     if (defined($opt{$option})) {
3702         return $opt{$option};
3703     }
3704
3705     foreach my $test (keys %repeat_tests) {
3706         if ($i >= $test &&
3707             $i < $test + $repeat_tests{$test}) {
3708             $option = "$name\[$test\]";
3709             if (defined($opt{$option})) {
3710                 return $opt{$option};
3711             }
3712         }
3713     }
3714
3715     if (defined($opt{$name})) {
3716         return $opt{$name};
3717     }
3718
3719     return undef;
3720 }
3721
3722 sub set_test_option {
3723     my ($name, $i) = @_;
3724
3725     my $option = __set_test_option($name, $i);
3726     return $option if (!defined($option));
3727
3728     return eval_option($option, $i);
3729 }
3730
3731 # First we need to do is the builds
3732 for (my $i = 1; $i <= $opt{"NUM_TESTS"}; $i++) {
3733
3734     # Do not reboot on failing test options
3735     $no_reboot = 1;
3736     $reboot_success = 0;
3737
3738     $have_version = 0;
3739
3740     $iteration = $i;
3741
3742     undef %force_config;
3743
3744     my $makecmd = set_test_option("MAKE_CMD", $i);
3745
3746     # Load all the options into their mapped variable names
3747     foreach my $opt (keys %option_map) {
3748         ${$option_map{$opt}} = set_test_option($opt, $i);
3749     }
3750
3751     $start_minconfig_defined = 1;
3752
3753     # The first test may override the PRE_KTEST option
3754     if (defined($pre_ktest) && $i == 1) {
3755         doprint "\n";
3756         run_command $pre_ktest;
3757     }
3758
3759     # Any test can override the POST_KTEST option
3760     # The last test takes precedence.
3761     if (defined($post_ktest)) {
3762         $final_post_ktest = $post_ktest;
3763     }
3764
3765     if (!defined($start_minconfig)) {
3766         $start_minconfig_defined = 0;
3767         $start_minconfig = $minconfig;
3768     }
3769
3770     chdir $builddir || die "can't change directory to $builddir";
3771
3772     foreach my $dir ($tmpdir, $outputdir) {
3773         if (!-d $dir) {
3774             mkpath($dir) or
3775                 die "can't create $dir";
3776         }
3777     }
3778
3779     $ENV{"SSH_USER"} = $ssh_user;
3780     $ENV{"MACHINE"} = $machine;
3781
3782     $buildlog = "$tmpdir/buildlog-$machine";
3783     $testlog = "$tmpdir/testlog-$machine";
3784     $dmesg = "$tmpdir/dmesg-$machine";
3785     $make = "$makecmd O=$outputdir";
3786     $output_config = "$outputdir/.config";
3787
3788     if (!$buildonly) {
3789         $target = "$ssh_user\@$machine";
3790         if ($reboot_type eq "grub") {
3791             dodie "GRUB_MENU not defined" if (!defined($grub_menu));
3792         } elsif ($reboot_type eq "grub2") {
3793             dodie "GRUB_MENU not defined" if (!defined($grub_menu));
3794             dodie "GRUB_FILE not defined" if (!defined($grub_file));
3795         } elsif ($reboot_type eq "syslinux") {
3796             dodie "SYSLINUX_LABEL not defined" if (!defined($syslinux_label));
3797         }
3798     }
3799
3800     my $run_type = $build_type;
3801     if ($test_type eq "patchcheck") {
3802         $run_type = $patchcheck_type;
3803     } elsif ($test_type eq "bisect") {
3804         $run_type = $bisect_type;
3805     } elsif ($test_type eq "config_bisect") {
3806         $run_type = $config_bisect_type;
3807     }
3808
3809     if ($test_type eq "make_min_config") {
3810         $run_type = "";
3811     }
3812
3813     # mistake in config file?
3814     if (!defined($run_type)) {
3815         $run_type = "ERROR";
3816     }
3817
3818     my $installme = "";
3819     $installme = " no_install" if ($no_install);
3820
3821     doprint "\n\n";
3822     doprint "RUNNING TEST $i of $opt{NUM_TESTS} with option $test_type $run_type$installme\n\n";
3823
3824     if (defined($pre_test)) {
3825         run_command $pre_test;
3826     }
3827
3828     unlink $dmesg;
3829     unlink $buildlog;
3830     unlink $testlog;
3831
3832     if (defined($addconfig)) {
3833         my $min = $minconfig;
3834         if (!defined($minconfig)) {
3835             $min = "";
3836         }
3837         run_command "cat $addconfig $min > $tmpdir/add_config" or
3838             dodie "Failed to create temp config";
3839         $minconfig = "$tmpdir/add_config";
3840     }
3841
3842     if (defined($checkout)) {
3843         run_command "git checkout $checkout" or
3844             die "failed to checkout $checkout";
3845     }
3846
3847     $no_reboot = 0;
3848
3849     # A test may opt to not reboot the box
3850     if ($reboot_on_success) {
3851         $reboot_success = 1;
3852     }
3853
3854     if ($test_type eq "bisect") {
3855         bisect $i;
3856         next;
3857     } elsif ($test_type eq "config_bisect") {
3858         config_bisect $i;
3859         next;
3860     } elsif ($test_type eq "patchcheck") {
3861         patchcheck $i;
3862         next;
3863     } elsif ($test_type eq "make_min_config") {
3864         make_min_config $i;
3865         next;
3866     }
3867
3868     if ($build_type ne "nobuild") {
3869         build $build_type or next;
3870     }
3871
3872     if ($test_type eq "install") {
3873         get_version;
3874         install;
3875         success $i;
3876         next;
3877     }
3878
3879     if ($test_type ne "build") {
3880         my $failed = 0;
3881         start_monitor_and_boot or $failed = 1;
3882
3883         if (!$failed && $test_type ne "boot" && defined($run_test)) {
3884             do_run_test or $failed = 1;
3885         }
3886         end_monitor;
3887         next if ($failed);
3888     }
3889
3890     success $i;
3891 }
3892
3893 if (defined($final_post_ktest)) {
3894     run_command $final_post_ktest;
3895 }
3896
3897 if ($opt{"POWEROFF_ON_SUCCESS"}) {
3898     halt;
3899 } elsif ($opt{"REBOOT_ON_SUCCESS"} && !do_not_reboot && $reboot_success) {
3900     reboot_to_good;
3901 } elsif (defined($switch_to_good)) {
3902     # still need to get to the good kernel
3903     run_command $switch_to_good;
3904 }
3905
3906
3907 doprint "\n    $successes of $opt{NUM_TESTS} tests were successful\n\n";
3908
3909 exit 0;