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