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