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