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