blob: 538a4472e209bedac77edbef2c01f1cf8a4678e8 [file] [log] [blame]
Daniel Vetterd63fe152014-03-12 01:29:52 +01001/*
2 * Copyright © 2007, 2011, 2013, 2014 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 *
23 * Authors:
24 * Eric Anholt <eric@anholt.net>
25 * Daniel Vetter <daniel.vetter@ffwll.ch>
26 *
27 */
28
Daniel Vetter00215dd2017-09-05 14:36:05 +020029#ifdef HAVE_LIBGEN_H
Daniel Vetterd63fe152014-03-12 01:29:52 +010030#include <libgen.h>
31#endif
32#include <stdio.h>
Daniel Vetter0e22f142014-03-22 19:27:04 +010033#include <assert.h>
Daniel Vetterd63fe152014-03-12 01:29:52 +010034#include <fcntl.h>
35#include <sys/stat.h>
36#include <sys/ioctl.h>
37#include <string.h>
38#include <sys/mman.h>
39#include <signal.h>
40#include <pciaccess.h>
41#include <getopt.h>
42#include <stdlib.h>
43#include <unistd.h>
44#include <sys/wait.h>
45#include <sys/types.h>
Alan Coopersmith99e6def2014-12-23 19:07:10 -080046#ifdef __linux__
Daniel Vetterd63fe152014-03-12 01:29:52 +010047#include <sys/syscall.h>
Alan Coopersmith99e6def2014-12-23 19:07:10 -080048#endif
Thomas Wooda5f21722015-01-19 15:27:51 +000049#include <pthread.h>
Daniel Vetterd63fe152014-03-12 01:29:52 +010050#include <sys/utsname.h>
51#include <termios.h>
Daniel Vetter254f19b2014-03-22 21:29:01 +010052#include <errno.h>
Chris Wilson91a43272014-09-06 08:40:04 +010053#include <time.h>
Thomas Wood2b05ecf2015-01-26 16:59:53 +000054#include <ctype.h>
Joonas Lahtinena95033f2015-03-31 15:53:17 +030055#include <limits.h>
Chris Wilson453792c2015-06-24 11:26:33 +010056#include <locale.h>
Derek Mortonef724ab2016-02-04 12:06:57 +000057#include <uwildmat/uwildmat.h>
Petri Latvala08a2f882017-09-29 13:51:59 +030058#ifdef HAVE_GLIB
Paul Kocialkowskiebd6eb62017-07-04 16:33:19 +030059#include <glib.h>
Petri Latvala08a2f882017-09-29 13:51:59 +030060#endif
Daniel Vetterd63fe152014-03-12 01:29:52 +010061
62#include "drmtest.h"
Daniel Vetterd63fe152014-03-12 01:29:52 +010063#include "intel_chipset.h"
Daniel Vetterc03c6ce2014-03-22 21:34:29 +010064#include "intel_io.h"
Daniel Vetterd63fe152014-03-12 01:29:52 +010065#include "igt_debugfs.h"
Rodrigo Vivi82ad15f2014-06-09 11:15:47 -070066#include "version.h"
Daniel Vetterd63fe152014-03-12 01:29:52 +010067#include "config.h"
68
69#include "igt_core.h"
Daniel Vetterf5daeec2014-03-23 13:35:09 +010070#include "igt_aux.h"
Chris Wilson9c4114e2016-12-21 16:37:46 +000071#include "igt_sysfs.h"
Petri Latvala08a2f882017-09-29 13:51:59 +030072#include "igt_rc.h"
Daniel Vetterd63fe152014-03-12 01:29:52 +010073
Alan Coopersmithf04b9df2014-12-23 19:07:11 -080074#ifdef HAVE_LIBGEN_H
75#include <libgen.h> /* for basename() on Solaris */
76#endif
77
Daniel Vetterd63fe152014-03-12 01:29:52 +010078/**
79 * SECTION:igt_core
80 * @short_description: Core i-g-t testing support
Damien Lespiau6ebd8c22015-06-26 14:28:41 +010081 * @title: Core
Thomas Woodf0381d12015-09-07 09:26:01 +010082 * @include: igt.h
Daniel Vettercd6d5a62014-03-22 19:35:40 +010083 *
Thomas Wood519f3772014-09-26 14:24:52 +010084 * This library implements the core of the i-g-t test support infrastructure.
Daniel Vetterd63fe152014-03-12 01:29:52 +010085 * Main features are the subtest enumeration, cmdline option parsing helpers for
86 * subtest handling and various helpers to structure testcases with subtests and
87 * handle subtest test results.
88 *
89 * Auxiliary code provides exit handlers, support for forked processes with test
90 * result propagation. Other generally useful functionality includes optional
91 * structure logging infrastructure and some support code for running reduced
92 * test set on in simulated hardware environments.
Daniel Vetter55e64982014-03-12 02:34:40 +010093 *
94 * When writing tests with subtests it is extremely important that nothing
95 * interferes with the subtest enumeration. In i-g-t subtests are enumerated at
96 * runtime, which allows powerful testcase enumeration. But it makes subtest
97 * enumeration a bit more tricky since the test code needs to be careful to
98 * never run any code which might fail (like trying to do privileged operations
99 * or opening device driver nodes).
100 *
101 * To allow this i-g-t provides #igt_fixture code blocks for setup code outside
102 * of subtests and automatically skips the subtest code blocks themselves. For
Daniel Vetter72d04b82016-03-18 21:46:54 +0100103 * special cases igt_only_list_subtests() is also provided. For setup code only
104 * shared by a group of subtest encapsulate the #igt_fixture block and all the
105 * subtestest in a #igt_subtest_group block.
Daniel Vetter5cf8d8d2014-03-13 21:25:01 +0100106 *
107 * # Magic Control Blocks
108 *
109 * i-g-t makes heavy use of C macros which serve as magic control blocks. They
110 * work fairly well and transparently but since C doesn't have full-blown
111 * closures there are caveats:
112 *
113 * - Asynchronous blocks which are used to spawn children internally use fork().
114 * Which means that nonsensical control flow like jumping out of the control
115 * block is possible, but it will badly confuse the i-g-t library code. And of
116 * course all caveats of a real fork() call apply, namely that file
117 * descriptors are copied, but still point at the original file. This will
118 * terminally upset the libdrm buffer manager if both parent and child keep on
119 * using the same open instance of the drm device. Usually everything related
120 * to interacting with the kernel driver must be reinitialized to avoid such
121 * issues.
122 *
123 * - Code blocks with magic control flow are implemented with setjmp() and
124 * longjmp(). This applies to #igt_fixture and #igt_subtest blocks and all the
125 * three variants to finish test: igt_success(), igt_skip() and igt_fail().
126 * Mostly this is of no concern, except when such a control block changes
127 * stack variables defined in the same function as the control block resides.
128 * Any store/load behaviour after a longjmp() is ill-defined for these
129 * variables. Avoid such code.
130 *
131 * Quoting the man page for longjmp():
132 *
133 * "The values of automatic variables are unspecified after a call to
134 * longjmp() if they meet all the following criteria:"
135 * - "they are local to the function that made the corresponding setjmp() call;
136 * - "their values are changed between the calls to setjmp() and longjmp(); and
137 * - "they are not declared as volatile."
Daniel Vetter10571b82014-03-16 19:34:37 +0100138 *
139 * # Best Practices for Test Helper Libraries Design
140 *
141 * Kernel tests itself tend to have fairly complex logic already. It is
142 * therefore paramount that helper code, both in libraries and test-private
143 * functions, add as little boilerplate code to the main test logic as possible.
144 * But then dense code is hard to understand without constantly consulting
145 * the documentation and implementation of all the helper functions if it
146 * doesn't follow some clear patterns. Hence follow these established best
147 * practices:
148 *
149 * - Make extensive use of the implicit control flow afforded by igt_skip(),
150 * igt_fail and igt_success(). When dealing with optional kernel features
151 * combine igt_skip() with igt_fail() to skip when the kernel support isn't
152 * available but fail when anything else goes awry. void should be the most
153 * common return type in all your functions, except object constructors of
154 * course.
155 *
156 * - The main test logic should have no explicit control flow for failure
157 * conditions, but instead such assumptions should be written in a declarative
158 * style. Use one of the many macros which encapsulate i-g-t's implicit
159 * control flow. Pick the most suitable one to have as much debug output as
Thomas Wood519f3772014-09-26 14:24:52 +0100160 * possible without polluting the code unnecessarily. For example
Daniel Vetter10571b82014-03-16 19:34:37 +0100161 * igt_assert_cmpint() for comparing integers or do_ioctl() for running ioctls
Thomas Wood519f3772014-09-26 14:24:52 +0100162 * and checking their results. Feel free to add new ones to the library or
Daniel Vetter10571b82014-03-16 19:34:37 +0100163 * wrap up a set of checks into a private function to further condense your
164 * test logic.
165 *
166 * - When adding a new feature test function which uses igt_skip() internally,
Thomas Wood5b7edb92015-04-20 12:35:01 +0100167 * use the <prefix>_require_<feature_name> naming scheme. When you
Daniel Vetter10571b82014-03-16 19:34:37 +0100168 * instead add a feature test function which returns a boolean, because your
169 * main test logic must take different actions depending upon the feature's
Thomas Wood5b7edb92015-04-20 12:35:01 +0100170 * availability, then instead use the <prefix>_has_<feature_name>.
Daniel Vetter10571b82014-03-16 19:34:37 +0100171 *
172 * - As already mentioned eschew explicit error handling logic as much as
173 * possible. If your test absolutely has to handle the error of some function
174 * the customary naming pattern is to prefix those variants with __. Try to
175 * restrict explicit error handling to leaf functions. For the main test flow
176 * simply pass the expected error condition down into your helper code, which
177 * results in tidy and declarative test logic.
178 *
179 * - Make your library functions as simple to use as possible. Automatically
180 * register cleanup handlers through igt_install_exit_handler(). Reduce the
181 * amount of setup boilerplate needed by using implicit singletons and lazy
182 * structure initialization and similar design patterns.
183 *
184 * - Don't shy away from refactoring common code, even when there are just 2-3
185 * users and even if it's not a net reduction in code. As long as it helps to
186 * remove boilerplate and makes the code more declarative the resulting
187 * clearer test flow is worth it. All i-g-t library code has been organically
188 * extracted from testcases in this fashion.
189 *
190 * - For general coding style issues please follow the kernel's rules laid out
191 * in
192 * [CodingStyle](https://www.kernel.org/doc/Documentation/CodingStyle).
Daniel Vetter1503d172014-05-13 11:29:34 +0200193 *
194 * # Interface with Testrunners
195 *
196 * i-g-t testcase are all executables which should be run as root on an
197 * otherwise completely idle system. The test status is reflected in the
Daniel Vetter831eb212014-05-14 15:33:27 +0200198 * exitcode. #IGT_EXIT_SUCCESS means "success", #IGT_EXIT_SKIP "skip",
199 * #IGT_EXIT_TIMEOUT that some operation "timed out". All other exit codes
200 * encode a failed test result, including any abnormal termination of the test
201 * (e.g. by SIGKILL).
Daniel Vetter1503d172014-05-13 11:29:34 +0200202 *
203 * On top of that tests may report unexpected results and minor issues to
204 * stderr. If stderr is non-empty the test result should be treated as "warn".
205 *
206 * The test lists are generated at build time. Simple testcases are listed in
207 * tests/single-tests.txt and tests with subtests are listed in
208 * tests/multi-tests.txt. When running tests with subtest from a test runner it
209 * is recommend to run each subtest individually, since otherwise the return
210 * code will only reflect the overall result.
211 *
212 * To do that obtain the lists of subtests with "--list-subtests", which can be
213 * run as non-root and doesn't require the i915 driver to be loaded (or any
214 * intel gpu to be present). Then individual subtests can be run with
215 * "--run-subtest". Usage help for tests with subtests can be obtained with the
Thomas Wood519f3772014-09-26 14:24:52 +0100216 * "--help" command line option.
Derek Mortonef724ab2016-02-04 12:06:57 +0000217 *
218 * A wildcard expression can be given to --run-subtest to specify a subset of
219 * subtests to run. See https://tools.ietf.org/html/rfc3977#section-4 for a
220 * description of allowed wildcard expressions.
221 * Some examples of allowed wildcard expressions are:
222 *
223 * - '*basic*' match any subtest containing basic
224 * - 'basic-???' match any subtest named basic- with 3 characters after -
225 * - 'basic-[0-9]' match any subtest named basic- with a single number after -
226 * - 'basic-[^0-9]' match any subtest named basic- with a single non numerical character after -
227 * - 'basic*,advanced*' match any subtest starting basic or advanced
228 * - '*,!basic*' match any subtest not starting basic
229 * - 'basic*,!basic-render*' match any subtest starting basic but not starting basic-render
Paul Kocialkowskiebd6eb62017-07-04 16:33:19 +0300230 *
231 * # Configuration
232 *
233 * Some of IGT's behavior can be configured through a configuration file.
234 * By default, this file is expected to exist in ~/.igtrc . The directory for
235 * this can be overriden by setting the environment variable %IGT_CONFIG_PATH.
236 * An example configuration follows:
237 *
238 * |[<!-- language="plain" -->
Paul Kocialkowski73a3b0b2017-08-28 11:12:03 +0300239 * &num; The common configuration section follows.
Paul Kocialkowskiee31e0b2017-07-19 16:46:07 +0300240 * [Common]
241 * FrameDumpPath=/tmp # The path to dump frames that fail comparison checks
242 *
Paul Kocialkowski73a3b0b2017-08-28 11:12:03 +0300243 * &num; The following section is used for configuring the Device Under Test.
244 * &num; It is not mandatory and allows overriding default values.
Paul Kocialkowskiebd6eb62017-07-04 16:33:19 +0300245 * [DUT]
246 * SuspendResumeDelay=10
247 * ]|
248 *
249 * Some specific configuration options may be used by specific parts of IGT,
250 * such as those related to Chamelium support.
Daniel Vetterd63fe152014-03-12 01:29:52 +0100251 */
252
253static unsigned int exit_handler_count;
Thomas Wooda6c40c72015-03-12 14:59:20 +0000254const char *igt_interactive_debug;
Daniel Vetterd63fe152014-03-12 01:29:52 +0100255
256/* subtests helpers */
257static bool list_subtests = false;
258static char *run_single_subtest = NULL;
Thomas Woode057b862014-07-18 14:10:27 +0100259static bool run_single_subtest_found = false;
Daniel Vetterd63fe152014-03-12 01:29:52 +0100260static const char *in_subtest = NULL;
Chris Wilson91a43272014-09-06 08:40:04 +0100261static struct timespec subtest_time;
Joonas Lahtinend84e6242015-11-20 13:57:11 +0200262static clockid_t igt_clock = (clockid_t)-1;
Daniel Vetterd63fe152014-03-12 01:29:52 +0100263static bool in_fixture = false;
264static bool test_with_subtests = false;
Thomas Woode65c69b2015-07-16 17:39:59 +0100265static bool in_atexit_handler = false;
Daniel Vetterd63fe152014-03-12 01:29:52 +0100266static enum {
267 CONT = 0, SKIP, FAIL
268} skip_subtests_henceforth = CONT;
269
Thomas Wood790f1f82015-11-09 17:17:24 +0000270bool __igt_plain_output = false;
271
Daniel Vetterd63fe152014-03-12 01:29:52 +0100272/* fork support state */
273pid_t *test_children;
274int num_test_children;
275int test_children_sz;
276bool test_child;
277
Thomas Woodfc5e2572014-07-25 16:54:41 +0100278enum {
279 OPT_LIST_SUBTESTS,
280 OPT_RUN_SUBTEST,
Thomas Woodf8b3c702014-10-10 16:56:20 +0100281 OPT_DESCRIPTION,
Thomas Woodfc5e2572014-07-25 16:54:41 +0100282 OPT_DEBUG,
Rodrigo Vivi3d65ff72015-01-12 10:21:58 -0800283 OPT_INTERACTIVE_DEBUG,
Thomas Woodfc5e2572014-07-25 16:54:41 +0100284 OPT_HELP = 'h'
285};
286
Thomas Woodf8fd4c92015-01-20 15:31:51 +0000287static int igt_exitcode = IGT_EXIT_SUCCESS;
288static const char *command_str;
289
Thomas Wood5fe9c882014-12-02 11:37:26 +0000290static char* igt_log_domain_filter;
Thomas Wooda5f21722015-01-19 15:27:51 +0000291static struct {
292 char *entries[256];
293 uint8_t start, end;
294} log_buffer;
295static pthread_mutex_t log_buffer_mutex = PTHREAD_MUTEX_INITIALIZER;
296
Lyudede99e152017-07-19 13:46:01 -0400297#ifdef HAVE_GLIB
Paul Kocialkowskiebd6eb62017-07-04 16:33:19 +0300298GKeyFile *igt_key_file;
Lyudede99e152017-07-19 13:46:01 -0400299#endif
300
Daniel Vettera3a3e0f2017-09-05 14:36:08 +0200301char *igt_frame_dump_path;
Paul Kocialkowskiebd6eb62017-07-04 16:33:19 +0300302
Chris Wilson77633492015-03-26 08:11:43 +0000303const char *igt_test_name(void)
304{
305 return command_str;
306}
307
Thomas Wooda5f21722015-01-19 15:27:51 +0000308static void _igt_log_buffer_append(char *line)
309{
310 pthread_mutex_lock(&log_buffer_mutex);
311
312 free(log_buffer.entries[log_buffer.end]);
313 log_buffer.entries[log_buffer.end] = line;
314 log_buffer.end++;
315 if (log_buffer.end == log_buffer.start)
316 log_buffer.start++;
317
318 pthread_mutex_unlock(&log_buffer_mutex);
319}
320
321static void _igt_log_buffer_reset(void)
322{
323 pthread_mutex_lock(&log_buffer_mutex);
324
325 log_buffer.start = log_buffer.end = 0;
326
327 pthread_mutex_unlock(&log_buffer_mutex);
328}
329
Thomas Woodf8fd4c92015-01-20 15:31:51 +0000330static void _igt_log_buffer_dump(void)
331{
332 uint8_t i;
Thomas Wooda5f21722015-01-19 15:27:51 +0000333
Thomas Woodf8fd4c92015-01-20 15:31:51 +0000334 if (in_subtest)
335 fprintf(stderr, "Subtest %s failed.\n", in_subtest);
336 else
337 fprintf(stderr, "Test %s failed.\n", command_str);
338
339 if (log_buffer.start == log_buffer.end) {
340 fprintf(stderr, "No log.\n");
341 return;
342 }
343
344 pthread_mutex_lock(&log_buffer_mutex);
Chris Wilsonb8db5d62015-03-06 08:49:52 +0000345 fprintf(stderr, "**** DEBUG ****\n");
Thomas Woodf8fd4c92015-01-20 15:31:51 +0000346
347 i = log_buffer.start;
348 do {
349 char *last_line = log_buffer.entries[i];
Daniel Vetterf45698d2015-02-27 19:32:33 +0100350 fprintf(stderr, "%s", last_line);
Thomas Woodf8fd4c92015-01-20 15:31:51 +0000351 i++;
352 } while (i != log_buffer.start && i != log_buffer.end);
353
354 /* reset the buffer */
355 log_buffer.start = log_buffer.end = 0;
356
Chris Wilsonb8db5d62015-03-06 08:49:52 +0000357 fprintf(stderr, "**** END ****\n");
Thomas Woodf8fd4c92015-01-20 15:31:51 +0000358 pthread_mutex_unlock(&log_buffer_mutex);
Thomas Woodf8fd4c92015-01-20 15:31:51 +0000359}
Thomas Wood5fe9c882014-12-02 11:37:26 +0000360
Abdiel Janulgueef48fc82017-04-13 16:18:37 +0300361/**
362 * igt_log_buffer_inspect:
363 *
364 * Provides a way to replay the internal igt log buffer for inspection.
365 * @check: A user-specified handler that gets invoked for each line of
366 * the log buffer. The handler should return true to stop
367 * inspecting the rest of the buffer.
368 * @data: passed as a user argument to the inspection function.
369 */
370void igt_log_buffer_inspect(igt_buffer_log_handler_t check, void *data)
371{
372 uint8_t i;
373 pthread_mutex_lock(&log_buffer_mutex);
374
375 i = log_buffer.start;
376 do {
377 if (check(log_buffer.entries[i], data))
378 break;
379 i++;
380 } while (i != log_buffer.start && i != log_buffer.end);
381
382 pthread_mutex_unlock(&log_buffer_mutex);
383}
384
Chris Wilsonb9e76372014-07-25 14:29:47 +0100385__attribute__((format(printf, 1, 2)))
386static void kmsg(const char *format, ...)
Chris Wilsonde1e8772014-07-28 08:58:32 +0100387#define KERN_EMER "<0>"
388#define KERN_ALERT "<1>"
389#define KERN_CRIT "<2>"
390#define KERN_ERR "<3>"
391#define KERN_WARNING "<4>"
392#define KERN_NOTICE "<5>"
393#define KERN_INFO "<6>"
394#define KERN_DEBUG "<7>"
Chris Wilsonb9e76372014-07-25 14:29:47 +0100395{
396 va_list ap;
397 FILE *file;
398
399 file = fopen("/dev/kmsg", "w");
400 if (file == NULL)
401 return;
402
403 va_start(ap, format);
404 vfprintf(file, format, ap);
405 va_end(ap);
406
407 fclose(file);
408}
409
Joonas Lahtinend84e6242015-11-20 13:57:11 +0200410#define time_valid(ts) ((ts)->tv_sec || (ts)->tv_nsec)
411
412static double
413time_elapsed(struct timespec *then,
414 struct timespec* now)
415{
416 double elapsed = -1.;
417
418 if (time_valid(then) && time_valid(now)) {
419 elapsed = now->tv_sec - then->tv_sec;
420 elapsed += (now->tv_nsec - then->tv_nsec) * 1e-9;
421 }
422
423 return elapsed;
424}
425
426static int gettime(struct timespec *ts)
Chris Wilson91a43272014-09-06 08:40:04 +0100427{
428 memset(ts, 0, sizeof(*ts));
Joonas Lahtinend84e6242015-11-20 13:57:11 +0200429 errno = 0;
Chris Wilson91a43272014-09-06 08:40:04 +0100430
Joonas Lahtinend84e6242015-11-20 13:57:11 +0200431 /* Stay on the same clock for consistency. */
432 if (igt_clock != (clockid_t)-1) {
433 if (clock_gettime(igt_clock, ts))
434 goto error;
435 return 0;
436 }
437
438#ifdef CLOCK_MONOTONIC_RAW
439 if (!clock_gettime(igt_clock = CLOCK_MONOTONIC_RAW, ts))
440 return 0;
Alan Coopersmith843beb12014-12-23 19:07:13 -0800441#endif
Joonas Lahtinend84e6242015-11-20 13:57:11 +0200442#ifdef CLOCK_MONOTONIC_COARSE
443 if (!clock_gettime(igt_clock = CLOCK_MONOTONIC_COARSE, ts))
444 return 0;
445#endif
446 if (!clock_gettime(igt_clock = CLOCK_MONOTONIC, ts))
447 return 0;
448error:
449 igt_warn("Could not read monotonic time: %s\n",
450 strerror(errno));
451
452 return -errno;
Chris Wilson91a43272014-09-06 08:40:04 +0100453}
454
Chris Wilsondcb39b52016-03-18 09:04:07 +0000455uint64_t igt_nsec_elapsed(struct timespec *start)
456{
457 struct timespec now;
458
459 gettime(&now);
460 if ((start->tv_sec | start->tv_nsec) == 0) {
461 *start = now;
462 return 0;
463 }
464
465 return ((now.tv_nsec - start->tv_nsec) +
Chris Wilsoncf07aa22016-05-02 15:35:56 +0100466 (uint64_t)NSEC_PER_SEC*(now.tv_sec - start->tv_sec));
Chris Wilsondcb39b52016-03-18 09:04:07 +0000467}
468
Daniel Vetterd63fe152014-03-12 01:29:52 +0100469bool __igt_fixture(void)
470{
471 assert(!in_fixture);
472
473 if (igt_only_list_subtests())
474 return false;
475
476 if (skip_subtests_henceforth)
477 return false;
478
479 in_fixture = true;
480 return true;
481}
482
483void __igt_fixture_complete(void)
484{
485 assert(in_fixture);
486
487 in_fixture = false;
488}
489
490void __igt_fixture_end(void)
491{
492 assert(in_fixture);
493
494 in_fixture = false;
Chris Wilson578795f2015-05-08 14:35:37 +0100495 siglongjmp(igt_subtest_jmpbuf, 1);
Daniel Vetterd63fe152014-03-12 01:29:52 +0100496}
497
Tim Gore5782eca2014-10-01 13:25:20 +0100498/*
499 * Some of the IGT tests put quite a lot of pressure on memory and when
500 * running on Android they are sometimes killed by the Android low memory killer.
501 * This seems to be due to some incompatibility between the kswapd free memory
502 * targets and the way the lowmemorykiller assesses free memory.
503 * The low memory killer really isn't usefull in this context and has no
504 * interaction with the gpu driver that we are testing, so the following
505 * function is used to disable it by modifying one of its module parameters.
506 * We still have the normal linux oom killer to protect the kernel.
507 * Apparently it is also possible for the lowmemorykiller to get included
508 * in some linux distributions; so rather than check for Android we directly
509 * check for the existence of the module parameter we want to adjust.
510 *
511 * In future, if we can get the lowmemorykiller to play nicely then we can
512 * remove this hack.
513 */
514static void low_mem_killer_disable(bool disable)
Daniel Vetterd63fe152014-03-12 01:29:52 +0100515{
Tim Gore5782eca2014-10-01 13:25:20 +0100516 static const char* adj_fname="/sys/module/lowmemorykiller/parameters/adj";
517 static const char no_lowmem_killer[] = "9999";
518 int fd;
519 struct stat buf;
520 /* The following must persist across invocations */
521 static char prev_adj_scores[256];
522 static int adj_scores_len = 0;
Tim Gore48a27bc2015-04-27 16:17:50 +0100523 static bool is_disabled = false;
Tim Gore5782eca2014-10-01 13:25:20 +0100524
525 /* capture the permissions bits for the lowmemkiller adj pseudo-file.
526 * Bail out if the stat fails; it probably means that there is no
527 * lowmemorykiller, but in any case we're doomed. */
528 if (stat(adj_fname, &buf)) {
529 igt_assert(errno == ENOENT);
530 return;
531 }
532
533 /* make sure the file can be read/written - by default it is write-only */
534 chmod(adj_fname, S_IRUSR | S_IWUSR);
535
Tim Gore48a27bc2015-04-27 16:17:50 +0100536 if (disable && !is_disabled) {
Tim Gore5782eca2014-10-01 13:25:20 +0100537 /* read the current oom adj parameters for lowmemorykiller */
538 fd = open(adj_fname, O_RDWR);
539 igt_assert(fd != -1);
540 adj_scores_len = read(fd, (void*)prev_adj_scores, 255);
541 igt_assert(adj_scores_len > 0);
542
543 /* writing 9999 to this module parameter effectively diables the
544 * low memory killer. This is not a real file, so we dont need to
545 * seek to the start or truncate it */
Thomas Wood47f6b132015-03-25 16:42:57 +0000546 igt_assert_eq(write(fd, no_lowmem_killer, sizeof(no_lowmem_killer)),
547 sizeof(no_lowmem_killer));
Tim Gore5782eca2014-10-01 13:25:20 +0100548 close(fd);
Tim Gore48a27bc2015-04-27 16:17:50 +0100549 is_disabled = true;
550 } else if (is_disabled) {
Tim Gore5782eca2014-10-01 13:25:20 +0100551 /* just re-enstate the original settings */
552 fd = open(adj_fname, O_WRONLY);
553 igt_assert(fd != -1);
Thomas Wood47f6b132015-03-25 16:42:57 +0000554 igt_assert_eq(write(fd, prev_adj_scores, adj_scores_len),
555 adj_scores_len);
Tim Gore5782eca2014-10-01 13:25:20 +0100556 close(fd);
Tim Gore48a27bc2015-04-27 16:17:50 +0100557 is_disabled = false;
Tim Gore5782eca2014-10-01 13:25:20 +0100558 }
559
560 /* re-enstate the file permissions */
561 chmod(adj_fname, buf.st_mode);
562}
563
564bool igt_exit_called;
565static void common_exit_handler(int sig)
566{
Tim Gore48a27bc2015-04-27 16:17:50 +0100567 if (!igt_only_list_subtests()) {
568 low_mem_killer_disable(false);
Chris Wilson9c4114e2016-12-21 16:37:46 +0000569 kick_fbcon(true);
Tim Gore48a27bc2015-04-27 16:17:50 +0100570 }
Tim Gore5782eca2014-10-01 13:25:20 +0100571
Daniel Vetterd63fe152014-03-12 01:29:52 +0100572 /* When not killed by a signal check that igt_exit() has been properly
573 * called. */
574 assert(sig != 0 || igt_exit_called);
575}
576
Thomas Woodf8b3c702014-10-10 16:56:20 +0100577static void print_test_description(void)
578{
579 if (&__igt_test_description)
580 printf("%s\n", __igt_test_description);
581}
582
Daniel Vetterd63fe152014-03-12 01:29:52 +0100583static void print_version(void)
584{
585 struct utsname uts;
586
587 if (list_subtests)
588 return;
589
590 uname(&uts);
591
Daniel Vetter80cc5402017-08-23 15:30:44 +0200592 igt_info("IGT-Version: %s-%s (%s) (%s: %s %s)\n", PACKAGE_VERSION,
593 IGT_GIT_SHA1, TARGET_CPU_PLATFORM,
594 uts.sysname, uts.release, uts.machine);
Daniel Vetterd63fe152014-03-12 01:29:52 +0100595}
596
Chris Wilson52915fc2014-07-24 12:46:00 +0100597static void print_usage(const char *help_str, bool output_on_stderr)
Daniel Vetterd63fe152014-03-12 01:29:52 +0100598{
599 FILE *f = output_on_stderr ? stderr : stdout;
600
Thomas Woodf8b3c702014-10-10 16:56:20 +0100601 fprintf(f, "Usage: %s [OPTIONS]\n", command_str);
602 fprintf(f, " --list-subtests\n"
Thomas Wood561d5192014-07-23 10:38:24 +0100603 " --run-subtest <pattern>\n"
Thomas Wood5fe9c882014-12-02 11:37:26 +0000604 " --debug[=log-domain]\n"
Rodrigo Vivi3d65ff72015-01-12 10:21:58 -0800605 " --interactive-debug[=domain]\n"
Thomas Woodf8b3c702014-10-10 16:56:20 +0100606 " --help-description\n"
607 " --help\n");
Daniel Vetterd63fe152014-03-12 01:29:52 +0100608 if (help_str)
609 fprintf(f, "%s\n", help_str);
610}
611
Tim Gore5782eca2014-10-01 13:25:20 +0100612
Daniel Vetterd63fe152014-03-12 01:29:52 +0100613static void oom_adjust_for_doom(void)
614{
615 int fd;
616 const char always_kill[] = "1000";
617
618 fd = open("/proc/self/oom_score_adj", O_WRONLY);
619 igt_assert(fd != -1);
620 igt_assert(write(fd, always_kill, sizeof(always_kill)) == sizeof(always_kill));
Tim Gore5782eca2014-10-01 13:25:20 +0100621 close(fd);
622
Daniel Vetterd63fe152014-03-12 01:29:52 +0100623}
624
Lyudede99e152017-07-19 13:46:01 -0400625#ifdef HAVE_GLIB
Paul Kocialkowskif39be722017-07-20 17:11:26 +0300626static void common_init_config(void)
Paul Kocialkowskiebd6eb62017-07-04 16:33:19 +0300627{
Paul Kocialkowskif39be722017-07-20 17:11:26 +0300628 char *key_file_env = NULL;
629 char *key_file_loc = NULL;
Paul Kocialkowskiebd6eb62017-07-04 16:33:19 +0300630 GError *error = NULL;
Paul Kocialkowskif39be722017-07-20 17:11:26 +0300631 int ret;
Paul Kocialkowskiebd6eb62017-07-04 16:33:19 +0300632
Paul Kocialkowskif39be722017-07-20 17:11:26 +0300633 /* Determine igt config path */
634 key_file_env = getenv("IGT_CONFIG_PATH");
635 if (key_file_env) {
636 key_file_loc = key_file_env;
637 } else {
638 key_file_loc = malloc(100);
639 snprintf(key_file_loc, 100, "%s/.igtrc", g_get_home_dir());
640 }
641
642 /* Load igt config file */
643 igt_key_file = g_key_file_new();
644 ret = g_key_file_load_from_file(igt_key_file, key_file_loc,
645 G_KEY_FILE_NONE, &error);
646 if (error && error->code == G_KEY_FILE_ERROR) {
647 g_error_free(error);
648 g_key_file_free(igt_key_file);
649 igt_key_file = NULL;
650
651 goto out;
652 }
653
654 g_clear_error(&error);
Paul Kocialkowskiebd6eb62017-07-04 16:33:19 +0300655
Daniel Vettera3a3e0f2017-09-05 14:36:08 +0200656 if (!igt_frame_dump_path)
657 igt_frame_dump_path =
658 g_key_file_get_string(igt_key_file, "Common",
659 "FrameDumpPath", &error);
Paul Kocialkowskiee31e0b2017-07-19 16:46:07 +0300660
Paul Kocialkowskia865fee2017-07-20 11:07:42 +0300661 g_clear_error(&error);
662
Paul Kocialkowskif39be722017-07-20 17:11:26 +0300663 ret = g_key_file_get_integer(igt_key_file, "DUT", "SuspendResumeDelay",
664 &error);
665 assert(!error || error->code != G_KEY_FILE_ERROR_INVALID_VALUE);
Paul Kocialkowskia865fee2017-07-20 11:07:42 +0300666
667 g_clear_error(&error);
Paul Kocialkowskiebd6eb62017-07-04 16:33:19 +0300668
Paul Kocialkowskif39be722017-07-20 17:11:26 +0300669 if (ret != 0)
670 igt_set_autoresume_delay(ret);
Paul Kocialkowskiebd6eb62017-07-04 16:33:19 +0300671
Paul Kocialkowskif39be722017-07-20 17:11:26 +0300672out:
673 if (!key_file_env && key_file_loc)
674 free(key_file_loc);
Paul Kocialkowskiebd6eb62017-07-04 16:33:19 +0300675}
Lyudede99e152017-07-19 13:46:01 -0400676#endif
Paul Kocialkowskiebd6eb62017-07-04 16:33:19 +0300677
Paul Kocialkowski493151b2017-07-20 17:11:27 +0300678static void common_init_env(void)
679{
680 const char *env;
681
682 if (!isatty(STDOUT_FILENO) || getenv("IGT_PLAIN_OUTPUT"))
683 __igt_plain_output = true;
684
685 if (!__igt_plain_output)
686 setlocale(LC_ALL, "");
687
688 env = getenv("IGT_LOG_LEVEL");
689 if (env) {
690 if (strcmp(env, "debug") == 0)
691 igt_log_level = IGT_LOG_DEBUG;
692 else if (strcmp(env, "info") == 0)
693 igt_log_level = IGT_LOG_INFO;
694 else if (strcmp(env, "warn") == 0)
695 igt_log_level = IGT_LOG_WARN;
696 else if (strcmp(env, "none") == 0)
697 igt_log_level = IGT_LOG_NONE;
698 }
699
Daniel Vettera3a3e0f2017-09-05 14:36:08 +0200700 igt_frame_dump_path = getenv("IGT_FRAME_DUMP_PATH");
Paul Kocialkowski493151b2017-07-20 17:11:27 +0300701}
702
Thomas Wood8fb19782015-02-18 16:19:59 +0000703static int common_init(int *argc, char **argv,
Thomas Wood94ac74e2014-07-18 16:24:34 +0100704 const char *extra_short_opts,
Ville Syrjälä793aff12015-12-18 19:25:45 +0200705 const struct option *extra_long_opts,
Thomas Wood94ac74e2014-07-18 16:24:34 +0100706 const char *help_str,
Damien Lespiaufd6846c2015-05-14 14:19:01 +0100707 igt_opt_handler_t extra_opt_handler,
708 void *handler_data)
Daniel Vetterd63fe152014-03-12 01:29:52 +0100709{
Thomas Woodc3ba7742014-07-28 15:37:16 +0100710 int c, option_index = 0, i, x;
Daniel Vetterd63fe152014-03-12 01:29:52 +0100711 static struct option long_options[] = {
Thomas Woodfc5e2572014-07-25 16:54:41 +0100712 {"list-subtests", 0, 0, OPT_LIST_SUBTESTS},
713 {"run-subtest", 1, 0, OPT_RUN_SUBTEST},
Thomas Woodf8b3c702014-10-10 16:56:20 +0100714 {"help-description", 0, 0, OPT_DESCRIPTION},
Thomas Wood5fe9c882014-12-02 11:37:26 +0000715 {"debug", optional_argument, 0, OPT_DEBUG},
Rodrigo Vivi3d65ff72015-01-12 10:21:58 -0800716 {"interactive-debug", optional_argument, 0, OPT_INTERACTIVE_DEBUG},
Thomas Woodfc5e2572014-07-25 16:54:41 +0100717 {"help", 0, 0, OPT_HELP},
Thomas Woodc3ba7742014-07-28 15:37:16 +0100718 {0, 0, 0, 0}
Daniel Vetterd63fe152014-03-12 01:29:52 +0100719 };
Daniel Vetterd63fe152014-03-12 01:29:52 +0100720 char *short_opts;
Thomas Woodc3ba7742014-07-28 15:37:16 +0100721 const char *std_short_opts = "h";
Daniel Vetterd63fe152014-03-12 01:29:52 +0100722 struct option *combined_opts;
723 int extra_opt_count;
724 int all_opt_count;
725 int ret = 0;
726
Paul Kocialkowski493151b2017-07-20 17:11:27 +0300727 common_init_env();
Daniel Vetterd63fe152014-03-12 01:29:52 +0100728
729 command_str = argv[0];
730 if (strrchr(command_str, '/'))
731 command_str = strrchr(command_str, '/') + 1;
732
733 /* First calculate space for all passed-in extra long options */
734 all_opt_count = 0;
Thomas Woodc3ba7742014-07-28 15:37:16 +0100735 while (extra_long_opts && extra_long_opts[all_opt_count].name) {
736
737 /* check for conflicts with standard long option values */
738 for (i = 0; long_options[i].name; i++)
739 if (extra_long_opts[all_opt_count].val == long_options[i].val)
740 igt_warn("Conflicting long option values between --%s and --%s\n",
741 extra_long_opts[all_opt_count].name,
742 long_options[i].name);
743
744 /* check for conflicts with short options */
745 if (extra_long_opts[all_opt_count].val != ':'
746 && strchr(std_short_opts, extra_long_opts[all_opt_count].val)) {
747 igt_warn("Conflicting long and short option values between --%s and -%s\n",
748 extra_long_opts[all_opt_count].name,
749 long_options[i].name);
750 }
751
752
Daniel Vetterd63fe152014-03-12 01:29:52 +0100753 all_opt_count++;
Thomas Woodc3ba7742014-07-28 15:37:16 +0100754 }
Daniel Vetterd63fe152014-03-12 01:29:52 +0100755 extra_opt_count = all_opt_count;
756
Thomas Woodc3ba7742014-07-28 15:37:16 +0100757 /* check for conflicts in extra short options*/
758 for (i = 0; extra_short_opts && extra_short_opts[i]; i++) {
759
760 if (extra_short_opts[i] == ':')
761 continue;
762
763 /* check for conflicts with standard short options */
764 if (strchr(std_short_opts, extra_short_opts[i]))
765 igt_warn("Conflicting short option: -%c\n", std_short_opts[i]);
766
767 /* check for conflicts with standard long option values */
768 for (x = 0; long_options[x].name; x++)
769 if (long_options[x].val == extra_short_opts[i])
770 igt_warn("Conflicting short option and long option value: --%s and -%c\n",
771 long_options[x].name, extra_short_opts[i]);
772 }
773
Daniel Vetterd63fe152014-03-12 01:29:52 +0100774 all_opt_count += ARRAY_SIZE(long_options);
775
776 combined_opts = malloc(all_opt_count * sizeof(*combined_opts));
777 memcpy(combined_opts, extra_long_opts,
778 extra_opt_count * sizeof(*combined_opts));
779
780 /* Copy the subtest long options (and the final NULL entry) */
781 memcpy(&combined_opts[extra_opt_count], long_options,
782 ARRAY_SIZE(long_options) * sizeof(*combined_opts));
783
Thomas Woodc3ba7742014-07-28 15:37:16 +0100784 ret = asprintf(&short_opts, "%s%s",
785 extra_short_opts ? extra_short_opts : "",
786 std_short_opts);
Daniel Vetterd63fe152014-03-12 01:29:52 +0100787 assert(ret >= 0);
788
Thomas Wood8fb19782015-02-18 16:19:59 +0000789 while ((c = getopt_long(*argc, argv, short_opts, combined_opts,
Daniel Vetterd63fe152014-03-12 01:29:52 +0100790 &option_index)) != -1) {
791 switch(c) {
Rodrigo Vivi3d65ff72015-01-12 10:21:58 -0800792 case OPT_INTERACTIVE_DEBUG:
793 if (optarg && strlen(optarg) > 0)
794 igt_interactive_debug = strdup(optarg);
795 else
796 igt_interactive_debug = "all";
797 break;
Thomas Woodfc5e2572014-07-25 16:54:41 +0100798 case OPT_DEBUG:
Thomas Wood561d5192014-07-23 10:38:24 +0100799 igt_log_level = IGT_LOG_DEBUG;
Thomas Wood5fe9c882014-12-02 11:37:26 +0000800 if (optarg && strlen(optarg) > 0)
801 igt_log_domain_filter = strdup(optarg);
Thomas Wood561d5192014-07-23 10:38:24 +0100802 break;
Thomas Woodfc5e2572014-07-25 16:54:41 +0100803 case OPT_LIST_SUBTESTS:
Daniel Vetterd63fe152014-03-12 01:29:52 +0100804 if (!run_single_subtest)
805 list_subtests = true;
806 break;
Thomas Woodfc5e2572014-07-25 16:54:41 +0100807 case OPT_RUN_SUBTEST:
Daniel Vetterd63fe152014-03-12 01:29:52 +0100808 if (!list_subtests)
809 run_single_subtest = strdup(optarg);
810 break;
Thomas Woodf8b3c702014-10-10 16:56:20 +0100811 case OPT_DESCRIPTION:
812 print_test_description();
813 ret = -1;
814 goto out;
Thomas Woodfc5e2572014-07-25 16:54:41 +0100815 case OPT_HELP:
Chris Wilson52915fc2014-07-24 12:46:00 +0100816 print_usage(help_str, false);
Daniel Vetterd63fe152014-03-12 01:29:52 +0100817 ret = -1;
818 goto out;
819 case '?':
Chris Wilson52915fc2014-07-24 12:46:00 +0100820 print_usage(help_str, true);
Thomas Woodc584d5c2014-07-21 16:17:06 +0100821 ret = -2;
822 goto out;
Daniel Vetterd63fe152014-03-12 01:29:52 +0100823 default:
Damien Lespiaufd6846c2015-05-14 14:19:01 +0100824 ret = extra_opt_handler(c, option_index, handler_data);
Daniel Vetterd63fe152014-03-12 01:29:52 +0100825 if (ret)
826 goto out;
827 }
828 }
829
Lyudede99e152017-07-19 13:46:01 -0400830#ifdef HAVE_GLIB
Paul Kocialkowskif39be722017-07-20 17:11:26 +0300831 common_init_config();
Lyudede99e152017-07-19 13:46:01 -0400832#endif
Paul Kocialkowskiebd6eb62017-07-04 16:33:19 +0300833
Daniel Vetterd63fe152014-03-12 01:29:52 +0100834out:
835 free(short_opts);
836 free(combined_opts);
Thomas Wood94ac74e2014-07-18 16:24:34 +0100837
838 /* exit immediately if this test has no subtests and a subtest or the
839 * list of subtests has been requested */
840 if (!test_with_subtests) {
841 if (run_single_subtest) {
842 igt_warn("Unknown subtest: %s\n", run_single_subtest);
Thomas Wood784344e2014-07-23 16:29:39 +0100843 exit(IGT_EXIT_INVALID);
Thomas Wood94ac74e2014-07-18 16:24:34 +0100844 }
845 if (list_subtests)
Thomas Wood784344e2014-07-23 16:29:39 +0100846 exit(IGT_EXIT_INVALID);
Thomas Wood94ac74e2014-07-18 16:24:34 +0100847 }
848
849 if (ret < 0)
850 /* exit with no error for -h/--help */
Thomas Wood784344e2014-07-23 16:29:39 +0100851 exit(ret == -1 ? 0 : IGT_EXIT_INVALID);
Thomas Wood94ac74e2014-07-18 16:24:34 +0100852
Chris Wilsonb9e76372014-07-25 14:29:47 +0100853 if (!list_subtests) {
Chris Wilson9c4114e2016-12-21 16:37:46 +0000854 kick_fbcon(false);
Jani Nikula230df2d2016-10-14 12:52:00 +0300855 kmsg(KERN_INFO "[IGT] %s: executing\n", command_str);
Chris Wilsonb9e76372014-07-25 14:29:47 +0100856 print_version();
857
Tvrtko Ursulin00da3d12017-09-05 11:38:58 +0100858 sync();
Chris Wilsonb9e76372014-07-25 14:29:47 +0100859 oom_adjust_for_doom();
Tim Gore48a27bc2015-04-27 16:17:50 +0100860 low_mem_killer_disable(true);
Chris Wilsonb9e76372014-07-25 14:29:47 +0100861 }
Daniel Vetterd63fe152014-03-12 01:29:52 +0100862
Tim Gore5782eca2014-10-01 13:25:20 +0100863 /* install exit handler, to ensure we clean up */
864 igt_install_exit_handler(common_exit_handler);
865
Thomas Wood16cfa372015-01-27 14:12:27 +0000866 if (!test_with_subtests)
867 gettime(&subtest_time);
868
Thomas Wood8fb19782015-02-18 16:19:59 +0000869 for (i = 0; (optind + i) < *argc; i++)
870 argv[i + 1] = argv[optind + i];
871
872 *argc = *argc - optind + 1;
873
Daniel Vetterd63fe152014-03-12 01:29:52 +0100874 return ret;
875}
876
Daniel Vetterd63fe152014-03-12 01:29:52 +0100877
Thomas Wood94ac74e2014-07-18 16:24:34 +0100878/**
879 * igt_subtest_init_parse_opts:
880 * @argc: argc from the test's main()
881 * @argv: argv from the test's main()
882 * @extra_short_opts: getopt_long() compliant list with additional short options
883 * @extra_long_opts: getopt_long() compliant list with additional long options
884 * @help_str: help string for the additional options
885 * @extra_opt_handler: handler for the additional options
Damien Lespiaufd6846c2015-05-14 14:19:01 +0100886 * @handler_data: user data given to @extra_opt_handler when invoked
Thomas Wood94ac74e2014-07-18 16:24:34 +0100887 *
Thomas Woodd01ebbd2015-06-29 16:47:14 +0100888 * This function handles the subtest related command line options and allows an
Thomas Wood94ac74e2014-07-18 16:24:34 +0100889 * arbitrary set of additional options. This is useful for tests which have
890 * additional knobs to tune when run manually like the number of rounds execute
891 * or the size of the allocated buffer objects.
892 *
893 * Tests without special needs should just use igt_subtest_init() or use
894 * #igt_main directly instead of their own main() function.
895 *
896 * Returns: Forwards any option parsing errors from getopt_long.
897 */
Thomas Wood8fb19782015-02-18 16:19:59 +0000898int igt_subtest_init_parse_opts(int *argc, char **argv,
Thomas Wood94ac74e2014-07-18 16:24:34 +0100899 const char *extra_short_opts,
Ville Syrjälä793aff12015-12-18 19:25:45 +0200900 const struct option *extra_long_opts,
Thomas Wood94ac74e2014-07-18 16:24:34 +0100901 const char *help_str,
Damien Lespiaufd6846c2015-05-14 14:19:01 +0100902 igt_opt_handler_t extra_opt_handler,
903 void *handler_data)
Daniel Vetterd63fe152014-03-12 01:29:52 +0100904{
Thomas Wood94ac74e2014-07-18 16:24:34 +0100905 int ret;
Daniel Vetterd63fe152014-03-12 01:29:52 +0100906
Thomas Wood94ac74e2014-07-18 16:24:34 +0100907 test_with_subtests = true;
908 ret = common_init(argc, argv, extra_short_opts, extra_long_opts,
Damien Lespiaufd6846c2015-05-14 14:19:01 +0100909 help_str, extra_opt_handler, handler_data);
Daniel Vetterd63fe152014-03-12 01:29:52 +0100910
Thomas Wood94ac74e2014-07-18 16:24:34 +0100911 return ret;
Daniel Vetterd63fe152014-03-12 01:29:52 +0100912}
913
Thomas Wood94ac74e2014-07-18 16:24:34 +0100914enum igt_log_level igt_log_level = IGT_LOG_INFO;
915
Daniel Vetter55e64982014-03-12 02:34:40 +0100916/**
Thomas Woode2cef002014-07-18 16:49:07 +0100917 * igt_simple_init_parse_opts:
918 * @argc: argc from the test's main()
919 * @argv: argv from the test's main()
920 * @extra_short_opts: getopt_long() compliant list with additional short options
921 * @extra_long_opts: getopt_long() compliant list with additional long options
922 * @help_str: help string for the additional options
923 * @extra_opt_handler: handler for the additional options
Damien Lespiaufd6846c2015-05-14 14:19:01 +0100924 * @handler_data: user data given to @extra_opt_handler when invoked
Thomas Woode2cef002014-07-18 16:49:07 +0100925 *
926 * This initializes a simple test without any support for subtests and allows
927 * an arbitrary set of additional options.
928 */
Thomas Wood8fb19782015-02-18 16:19:59 +0000929void igt_simple_init_parse_opts(int *argc, char **argv,
Thomas Woode2cef002014-07-18 16:49:07 +0100930 const char *extra_short_opts,
Ville Syrjälä793aff12015-12-18 19:25:45 +0200931 const struct option *extra_long_opts,
Thomas Woode2cef002014-07-18 16:49:07 +0100932 const char *help_str,
Damien Lespiaufd6846c2015-05-14 14:19:01 +0100933 igt_opt_handler_t extra_opt_handler,
934 void *handler_data)
Thomas Woode2cef002014-07-18 16:49:07 +0100935{
936 common_init(argc, argv, extra_short_opts, extra_long_opts, help_str,
Damien Lespiaufd6846c2015-05-14 14:19:01 +0100937 extra_opt_handler, handler_data);
Thomas Woode2cef002014-07-18 16:49:07 +0100938}
939
Daniel Vetterd63fe152014-03-12 01:29:52 +0100940/*
941 * Note: Testcases which use these helpers MUST NOT output anything to stdout
942 * outside of places protected by igt_run_subtest checks - the piglit
943 * runner adds every line to the subtest list.
944 */
945bool __igt_run_subtest(const char *subtest_name)
946{
Thomas Wood2b05ecf2015-01-26 16:59:53 +0000947 int i;
948
Daniel Vetterd63fe152014-03-12 01:29:52 +0100949 assert(!in_subtest);
950 assert(!in_fixture);
Thomas Wooddbac9052014-11-25 14:10:04 +0000951 assert(test_with_subtests);
Daniel Vetterd63fe152014-03-12 01:29:52 +0100952
Thomas Wood2b05ecf2015-01-26 16:59:53 +0000953 /* check the subtest name only contains a-z, A-Z, 0-9, '-' and '_' */
954 for (i = 0; subtest_name[i] != '\0'; i++)
955 if (subtest_name[i] != '_' && subtest_name[i] != '-'
956 && !isalnum(subtest_name[i])) {
957 igt_critical("Invalid subtest name \"%s\".\n",
958 subtest_name);
959 igt_exit();
960 }
961
Daniel Vetterd63fe152014-03-12 01:29:52 +0100962 if (list_subtests) {
963 printf("%s\n", subtest_name);
964 return false;
965 }
966
Thomas Woode057b862014-07-18 14:10:27 +0100967 if (run_single_subtest) {
Derek Mortonef724ab2016-02-04 12:06:57 +0000968 if (uwildmat(subtest_name, run_single_subtest) == 0)
Thomas Woode057b862014-07-18 14:10:27 +0100969 return false;
970 else
971 run_single_subtest_found = true;
972 }
973
Daniel Vetterd63fe152014-03-12 01:29:52 +0100974 if (skip_subtests_henceforth) {
Thomas Woodfca7b1b2015-10-29 17:01:17 +0000975 printf("%sSubtest %s: %s%s\n",
Thomas Wood790f1f82015-11-09 17:17:24 +0000976 (!__igt_plain_output) ? "\x1b[1m" : "", subtest_name,
Daniel Vetterd63fe152014-03-12 01:29:52 +0100977 skip_subtests_henceforth == SKIP ?
Thomas Wood790f1f82015-11-09 17:17:24 +0000978 "SKIP" : "FAIL", (!__igt_plain_output) ? "\x1b[0m" : "");
Daniel Vetterd63fe152014-03-12 01:29:52 +0100979 return false;
980 }
981
Jani Nikula230df2d2016-10-14 12:52:00 +0300982 kmsg(KERN_INFO "[IGT] %s: starting subtest %s\n", command_str, subtest_name);
Thomas Wood9942a402015-01-27 14:10:15 +0000983 igt_debug("Starting subtest: %s\n", subtest_name);
Chris Wilson52915fc2014-07-24 12:46:00 +0100984
Thomas Wooda5f21722015-01-19 15:27:51 +0000985 _igt_log_buffer_reset();
986
Chris Wilson91a43272014-09-06 08:40:04 +0100987 gettime(&subtest_time);
Daniel Vetterd63fe152014-03-12 01:29:52 +0100988 return (in_subtest = subtest_name);
989}
990
Daniel Vetter55e64982014-03-12 02:34:40 +0100991/**
992 * igt_subtest_name:
993 *
994 * Returns: The name of the currently executed subtest or NULL if called from
995 * outside a subtest block.
996 */
Daniel Vetterd63fe152014-03-12 01:29:52 +0100997const char *igt_subtest_name(void)
998{
999 return in_subtest;
1000}
1001
Daniel Vetter55e64982014-03-12 02:34:40 +01001002/**
1003 * igt_only_list_subtests:
1004 *
1005 * Returns: Returns true if only subtest should be listed and any setup code
1006 * must be skipped, false otherwise.
1007 */
Daniel Vetterd63fe152014-03-12 01:29:52 +01001008bool igt_only_list_subtests(void)
1009{
1010 return list_subtests;
1011}
1012
Daniel Vetter72d04b82016-03-18 21:46:54 +01001013void __igt_subtest_group_save(int *save)
1014{
1015 *save = skip_subtests_henceforth;
1016}
1017
1018void __igt_subtest_group_restore(int save)
1019{
1020 skip_subtests_henceforth = save;
1021}
1022
Daniel Vetterd63fe152014-03-12 01:29:52 +01001023static bool skipped_one = false;
1024static bool succeeded_one = false;
1025static bool failed_one = false;
Daniel Vetterd63fe152014-03-12 01:29:52 +01001026
1027static void exit_subtest(const char *) __attribute__((noreturn));
1028static void exit_subtest(const char *result)
1029{
Chris Wilson91a43272014-09-06 08:40:04 +01001030 struct timespec now;
Chris Wilson91a43272014-09-06 08:40:04 +01001031
1032 gettime(&now);
Daniel Vetter80cc5402017-08-23 15:30:44 +02001033 igt_info("%sSubtest %s: %s (%.3fs)%s\n",
1034 (!__igt_plain_output) ? "\x1b[1m" : "",
1035 in_subtest, result, time_elapsed(&subtest_time, &now),
1036 (!__igt_plain_output) ? "\x1b[0m" : "");
Paulo Zanoni6cc553a2015-06-25 14:12:56 -03001037 fflush(stdout);
1038
Daniel Vetterd63fe152014-03-12 01:29:52 +01001039 in_subtest = NULL;
Chris Wilson578795f2015-05-08 14:35:37 +01001040 siglongjmp(igt_subtest_jmpbuf, 1);
Daniel Vetterd63fe152014-03-12 01:29:52 +01001041}
1042
Daniel Vetter55e64982014-03-12 02:34:40 +01001043/**
1044 * igt_skip:
1045 * @f: format string
1046 * @...: optional arguments used in the format string
1047 *
1048 * Subtest aware test skipping. The format string is printed to stderr as the
1049 * reason why the test skipped.
1050 *
1051 * For tests with subtests this will either bail out of the current subtest or
1052 * mark all subsequent subtests as SKIP (presuming some global setup code
1053 * failed).
1054 *
1055 * For normal tests without subtest it will directly exit.
1056 */
Daniel Vetterd63fe152014-03-12 01:29:52 +01001057void igt_skip(const char *f, ...)
1058{
1059 va_list args;
1060 skipped_one = true;
1061
1062 assert(!test_child);
1063
1064 if (!igt_only_list_subtests()) {
1065 va_start(args, f);
1066 vprintf(f, args);
1067 va_end(args);
1068 }
1069
1070 if (in_subtest) {
1071 exit_subtest("SKIP");
1072 } else if (test_with_subtests) {
1073 skip_subtests_henceforth = SKIP;
1074 assert(in_fixture);
1075 __igt_fixture_end();
1076 } else {
Tim Goref33fa712014-09-29 13:34:30 +01001077 igt_exitcode = IGT_EXIT_SKIP;
1078 igt_exit();
Daniel Vetterd63fe152014-03-12 01:29:52 +01001079 }
1080}
1081
1082void __igt_skip_check(const char *file, const int line,
1083 const char *func, const char *check,
1084 const char *f, ...)
1085{
1086 va_list args;
1087 int err = errno;
Damien Lespiau41454622014-07-09 11:36:27 +01001088 char *err_str = NULL;
1089
1090 if (err)
Thomas Wood47f6b132015-03-25 16:42:57 +00001091 igt_assert_neq(asprintf(&err_str, "Last errno: %i, %s\n", err, strerror(err)),
1092 -1);
Daniel Vetterd63fe152014-03-12 01:29:52 +01001093
1094 if (f) {
1095 static char *buf;
1096
1097 /* igt_skip never returns, so try to not leak too badly. */
1098 if (buf)
1099 free(buf);
1100
1101 va_start(args, f);
Thomas Wood47f6b132015-03-25 16:42:57 +00001102 igt_assert_neq(vasprintf(&buf, f, args), -1);
Daniel Vetterd63fe152014-03-12 01:29:52 +01001103 va_end(args);
1104
1105 igt_skip("Test requirement not met in function %s, file %s:%i:\n"
Chris Wilsone0dffbd2014-07-25 14:28:51 +01001106 "Test requirement: %s\n%s"
Damien Lespiau41454622014-07-09 11:36:27 +01001107 "%s",
1108 func, file, line, check, buf, err_str ?: "");
Daniel Vetterd63fe152014-03-12 01:29:52 +01001109 } else {
1110 igt_skip("Test requirement not met in function %s, file %s:%i:\n"
Chris Wilsone0dffbd2014-07-25 14:28:51 +01001111 "Test requirement: %s\n"
Damien Lespiau41454622014-07-09 11:36:27 +01001112 "%s",
1113 func, file, line, check, err_str ?: "");
Daniel Vetterd63fe152014-03-12 01:29:52 +01001114 }
1115}
1116
Daniel Vetter55e64982014-03-12 02:34:40 +01001117/**
1118 * igt_success:
1119 *
Thomas Wood519f3772014-09-26 14:24:52 +01001120 * Complete a (subtest) as successful
Daniel Vetter55e64982014-03-12 02:34:40 +01001121 *
1122 * This bails out of a subtests and marks it as successful. For global tests it
1123 * it won't bail out of anything.
1124 */
Daniel Vetterd63fe152014-03-12 01:29:52 +01001125void igt_success(void)
1126{
1127 succeeded_one = true;
1128 if (in_subtest)
1129 exit_subtest("SUCCESS");
1130}
1131
Daniel Vetter55e64982014-03-12 02:34:40 +01001132/**
1133 * igt_fail:
1134 * @exitcode: exitcode
1135 *
1136 * Fail a testcase. The exitcode is used as the exit code of the test process.
1137 * It may not be 0 (which indicates success) or 77 (which indicates a skipped
1138 * test).
1139 *
1140 * For tests with subtests this will either bail out of the current subtest or
1141 * mark all subsequent subtests as FAIL (presuming some global setup code
1142 * failed).
1143 *
1144 * For normal tests without subtest it will directly exit with the given
1145 * exitcode.
1146 */
Daniel Vetterd63fe152014-03-12 01:29:52 +01001147void igt_fail(int exitcode)
1148{
Thomas Wood17eb0622014-05-13 15:22:52 +01001149 assert(exitcode != IGT_EXIT_SUCCESS && exitcode != IGT_EXIT_SKIP);
Daniel Vetterd63fe152014-03-12 01:29:52 +01001150
Daniel Vetter4fec18e2015-02-27 20:24:15 +01001151 igt_debug_wait_for_keypress("failure");
1152
Thomas Woode65c69b2015-07-16 17:39:59 +01001153 /* Exit immediately if the test is already exiting and igt_fail is
1154 * called. This can happen if an igt_assert fails in an exit handler */
1155 if (in_atexit_handler)
1156 _exit(IGT_EXIT_FAILURE);
1157
Daniel Vetterd63fe152014-03-12 01:29:52 +01001158 if (!failed_one)
1159 igt_exitcode = exitcode;
1160
1161 failed_one = true;
1162
1163 /* Silent exit, parent will do the yelling. */
1164 if (test_child)
1165 exit(exitcode);
1166
Thomas Woodf8fd4c92015-01-20 15:31:51 +00001167 _igt_log_buffer_dump();
1168
Thomas Woodd8e53132014-05-12 10:19:52 +01001169 if (in_subtest) {
Thomas Wood17eb0622014-05-13 15:22:52 +01001170 if (exitcode == IGT_EXIT_TIMEOUT)
Thomas Woodd8e53132014-05-12 10:19:52 +01001171 exit_subtest("TIMEOUT");
1172 else
1173 exit_subtest("FAIL");
1174 } else {
Daniel Vetter2459b802017-08-14 11:32:04 +02001175 assert(igt_can_fail());
Daniel Vetterd63fe152014-03-12 01:29:52 +01001176
1177 if (in_fixture) {
1178 skip_subtests_henceforth = FAIL;
1179 __igt_fixture_end();
1180 }
1181
Tim Goref33fa712014-09-29 13:34:30 +01001182 igt_exit();
Daniel Vetterd63fe152014-03-12 01:29:52 +01001183 }
1184}
1185
Daniel Vetter2459b802017-08-14 11:32:04 +02001186/**
1187 * igt_can_fail:
1188 *
1189 * Returns true if called from either an #igt_fixture, #igt_subtest or a
1190 * testcase without subtests, i.e. #igt_simple_main. Returns false otherwise. In
1191 * other words, it checks whether it's legal to call igt_fail(), igt_skip_on()
1192 * and all the convenience macros build around those.
1193 *
1194 * This is useful to make sure that library code is called from the right
1195 * places.
1196 */
1197bool igt_can_fail(void)
1198{
1199 return !test_with_subtests || in_fixture || in_subtest;
1200}
1201
Daniel Vetterd63fe152014-03-12 01:29:52 +01001202static bool run_under_gdb(void)
1203{
1204 char buf[1024];
1205
1206 sprintf(buf, "/proc/%d/exe", getppid());
1207 return (readlink (buf, buf, sizeof (buf)) != -1 &&
1208 strncmp(basename(buf), "gdb", 3) == 0);
1209}
1210
Thomas Wood277ca2b2015-03-13 17:02:12 +00001211#ifdef HAVE_LIBUNWIND
1212#define UNW_LOCAL_ONLY
1213#include <libunwind.h>
1214
1215static void print_backtrace(void)
1216{
1217 unw_cursor_t cursor;
1218 unw_context_t uc;
1219 int stack_num = 0;
1220
Daniel Vetter80cc5402017-08-23 15:30:44 +02001221 igt_info("Stack trace:\n");
Thomas Wood277ca2b2015-03-13 17:02:12 +00001222
1223 unw_getcontext(&uc);
1224 unw_init_local(&cursor, &uc);
1225 while (unw_step(&cursor) > 0) {
1226 char name[255];
1227 unw_word_t off;
1228
1229 if (unw_get_proc_name(&cursor, name, 255, &off) < 0)
1230 strcpy(name, "<unknown>");
1231
Daniel Vetter80cc5402017-08-23 15:30:44 +02001232 igt_info(" #%d [%s+0x%x]\n", stack_num++, name,
1233 (unsigned int) off);
Thomas Wood277ca2b2015-03-13 17:02:12 +00001234 }
1235}
marius vlad1ae41a52016-08-24 11:44:07 +03001236
1237static const char hex[] = "0123456789abcdef";
1238
1239static void
1240xputch(int c)
1241{
1242 write(STDERR_FILENO, (const void *) &c, 1);
1243}
1244
1245static int
1246xpow(int base, int pow)
1247{
1248 int i, r = 1;
1249
1250 for (i = 0; i < pow; i++)
1251 r *= base;
1252
1253 return r;
1254}
1255
1256static void
1257printnum(unsigned long long num, unsigned base)
1258{
1259 int i = 0;
Marius Vlad75cba292016-09-19 18:38:56 +03001260 unsigned long long __num = num;
marius vlad1ae41a52016-08-24 11:44:07 +03001261
1262 /* determine from where we should start dividing */
1263 do {
1264 __num /= base;
1265 i++;
1266 } while (__num);
1267
1268 while (i--)
1269 xputch(hex[num / xpow(base, i) % base]);
1270}
1271
1272static size_t
1273xstrlcpy(char *dst, const char *src, size_t size)
1274{
1275 char *dst_in;
1276
1277 dst_in = dst;
1278 if (size > 0) {
1279 while (--size > 0 && *src != '\0')
1280 *dst++ = *src++;
1281 *dst = '\0';
1282 }
1283
1284 return dst - dst_in;
1285}
1286
1287static void
1288xprintfmt(const char *fmt, va_list ap)
1289{
1290 const char *p;
1291 int ch, base;
1292 unsigned long long num;
1293
1294 while (1) {
Chris Wilsondc3fcd92016-11-30 19:37:37 +00001295 while ((ch = *(const unsigned char *) fmt++) != '%') {
marius vlad1ae41a52016-08-24 11:44:07 +03001296 if (ch == '\0') {
1297 return;
1298 }
1299 xputch(ch);
1300 }
1301
Chris Wilsondc3fcd92016-11-30 19:37:37 +00001302 ch = *(const unsigned char *) fmt++;
marius vlad1ae41a52016-08-24 11:44:07 +03001303 switch (ch) {
1304 /* character */
1305 case 'c':
1306 xputch(va_arg(ap, int));
1307 break;
1308 /* string */
1309 case 's':
1310 if ((p = va_arg(ap, char *)) == NULL) {
1311 p = "(null)";
1312 }
1313
1314 for (; (ch = *p++) != '\0';) {
1315 if (ch < ' ' || ch > '~') {
1316 xputch('?');
1317 } else {
1318 xputch(ch);
1319 }
1320 }
1321 break;
1322 /* (signed) decimal */
1323 case 'd':
1324 num = va_arg(ap, int);
1325 if ((long long) num < 0) {
1326 xputch('-');
1327 num = -(long long) num;
1328 }
1329 base = 10;
1330 goto number;
1331 /* unsigned decimal */
1332 case 'u':
1333 num = va_arg(ap, unsigned int);
1334 base = 10;
1335 goto number;
1336 /* (unsigned) hexadecimal */
1337 case 'x':
1338 num = va_arg(ap, unsigned int);
1339 base = 16;
1340number:
1341 printnum(num, base);
1342 break;
1343
1344 /* The following are not implemented */
1345
1346 /* width field */
1347 case '1': case '2':
1348 case '3': case '4':
1349 case '5': case '6':
1350 case '7': case '8':
1351 case '9':
1352 case '.': case '#':
1353 /* long */
1354 case 'l':
1355 /* octal */
1356 case 'o':
1357 /* pointer */
1358 case 'p':
1359 /* float */
1360 case 'f':
1361 abort();
1362 /* escaped '%' character */
1363 case '%':
1364 xputch(ch);
1365 break;
1366 /* unrecognized escape sequence - just print it literally */
1367 default:
1368 xputch('%');
1369 for (fmt--; fmt[-1] != '%'; fmt--)
1370 ; /* do nothing */
1371 break;
1372 }
1373 }
1374}
1375
1376/* async-safe printf */
1377static void
1378xprintf(const char *fmt, ...)
1379{
1380 va_list ap;
1381
1382 va_start(ap, fmt);
1383 xprintfmt(fmt, ap);
1384 va_end(ap);
1385}
1386
1387static void print_backtrace_sig_safe(void)
1388{
1389 unw_cursor_t cursor;
1390 unw_context_t uc;
1391 int stack_num = 0;
1392
1393 write(STDERR_FILENO, "Stack trace: \n", 15);
1394
1395 unw_getcontext(&uc);
1396 unw_init_local(&cursor, &uc);
1397 while (unw_step(&cursor) > 0) {
1398 char name[255];
1399 unw_word_t off;
1400
1401 if (unw_get_proc_name(&cursor, name, 255, &off) < 0)
Marius Vlad75cba292016-09-19 18:38:56 +03001402 xstrlcpy(name, "<unknown>", 10);
marius vlad1ae41a52016-08-24 11:44:07 +03001403
1404 xprintf(" #%d [%s+0x%x]\n", stack_num++, name,
1405 (unsigned int) off);
1406
1407 }
1408}
Thomas Wood277ca2b2015-03-13 17:02:12 +00001409#endif
1410
Thomas Woodb47032e2015-04-09 09:24:12 +01001411void __igt_fail_assert(const char *domain, const char *file, const int line,
1412 const char *func, const char *assertion,
Daniel Vetterd63fe152014-03-12 01:29:52 +01001413 const char *f, ...)
1414{
1415 va_list args;
1416 int err = errno;
Damien Lespiaue16d4a22014-07-09 11:40:16 +01001417
Thomas Wood01676192014-12-17 11:37:31 +00001418 igt_log(domain, IGT_LOG_CRITICAL,
1419 "Test assertion failure function %s, file %s:%i:\n", func, file,
1420 line);
1421 igt_log(domain, IGT_LOG_CRITICAL, "Failed assertion: %s\n", assertion);
Damien Lespiaue16d4a22014-07-09 11:40:16 +01001422 if (err)
Thomas Wood01676192014-12-17 11:37:31 +00001423 igt_log(domain, IGT_LOG_CRITICAL, "Last errno: %i, %s\n", err,
1424 strerror(err));
Daniel Vetterd63fe152014-03-12 01:29:52 +01001425
1426 if (f) {
1427 va_start(args, f);
Thomas Wood01676192014-12-17 11:37:31 +00001428 igt_vlog(domain, IGT_LOG_CRITICAL, f, args);
Daniel Vetterd63fe152014-03-12 01:29:52 +01001429 va_end(args);
1430 }
1431
Thomas Wood277ca2b2015-03-13 17:02:12 +00001432#ifdef HAVE_LIBUNWIND
1433 print_backtrace();
1434#endif
1435
Daniel Vetterd63fe152014-03-12 01:29:52 +01001436 if (run_under_gdb())
1437 abort();
Thomas Woodb47032e2015-04-09 09:24:12 +01001438 igt_fail(IGT_EXIT_FAILURE);
Daniel Vetterd63fe152014-03-12 01:29:52 +01001439}
1440
Daniel Vetter55e64982014-03-12 02:34:40 +01001441/**
1442 * igt_exit:
1443 *
1444 * exit() for both types (simple and with subtests) of i-g-t tests.
1445 *
1446 * This will exit the test with the right exit code when subtests have been
1447 * skipped. For normal tests it exits with a successful exit code, presuming
1448 * everything has worked out. For subtests it also checks that at least one
1449 * subtest has been run (save when only listing subtests.
1450 *
Tim Goref33fa712014-09-29 13:34:30 +01001451 * It is an error to normally exit a test calling igt_exit() - without it the
1452 * result reporting will be wrong. To avoid such issues it is highly recommended
1453 * to use #igt_main or #igt_simple_main instead of a hand-rolled main() function.
Daniel Vetter55e64982014-03-12 02:34:40 +01001454 */
Daniel Vetterd63fe152014-03-12 01:29:52 +01001455void igt_exit(void)
1456{
1457 igt_exit_called = true;
1458
Lyudede99e152017-07-19 13:46:01 -04001459#ifdef HAVE_GLIB
Paul Kocialkowskiebd6eb62017-07-04 16:33:19 +03001460 if (igt_key_file)
1461 g_key_file_free(igt_key_file);
Lyudede99e152017-07-19 13:46:01 -04001462#endif
Paul Kocialkowskiebd6eb62017-07-04 16:33:19 +03001463
Thomas Woode057b862014-07-18 14:10:27 +01001464 if (run_single_subtest && !run_single_subtest_found) {
1465 igt_warn("Unknown subtest: %s\n", run_single_subtest);
Thomas Wood784344e2014-07-23 16:29:39 +01001466 exit(IGT_EXIT_INVALID);
Thomas Woode057b862014-07-18 14:10:27 +01001467 }
1468
Daniel Vetterd63fe152014-03-12 01:29:52 +01001469 if (igt_only_list_subtests())
Thomas Wood17eb0622014-05-13 15:22:52 +01001470 exit(IGT_EXIT_SUCCESS);
Daniel Vetterd63fe152014-03-12 01:29:52 +01001471
Chris Wilsonf2014952016-05-03 11:04:00 +01001472 /* Calling this without calling one of the above is a failure */
1473 assert(!test_with_subtests ||
1474 skipped_one ||
1475 succeeded_one ||
1476 failed_one);
1477
1478 if (test_with_subtests && !failed_one) {
1479 if (succeeded_one)
1480 igt_exitcode = IGT_EXIT_SUCCESS;
1481 else
1482 igt_exitcode = IGT_EXIT_SKIP;
1483 }
1484
Chris Wilson362da342016-06-24 08:30:09 +01001485 if (command_str)
Jani Nikula230df2d2016-10-14 12:52:00 +03001486 kmsg(KERN_INFO "[IGT] %s: exiting, ret=%d\n",
Chris Wilson362da342016-06-24 08:30:09 +01001487 command_str, igt_exitcode);
Thomas Wood9942a402015-01-27 14:10:15 +00001488 igt_debug("Exiting with status code %d\n", igt_exitcode);
Chris Wilsond8bf7e12015-01-05 14:07:31 +00001489
Chris Wilson75487632016-02-26 22:11:10 +00001490 for (int c = 0; c < num_test_children; c++)
1491 kill(test_children[c], SIGKILL);
1492
Thomas Wood16cfa372015-01-27 14:12:27 +00001493 if (!test_with_subtests) {
1494 struct timespec now;
Thomas Wood16cfa372015-01-27 14:12:27 +00001495 const char *result;
1496
1497 gettime(&now);
Thomas Wood16cfa372015-01-27 14:12:27 +00001498
1499 switch (igt_exitcode) {
1500 case IGT_EXIT_SUCCESS:
1501 result = "SUCCESS";
1502 break;
1503 case IGT_EXIT_TIMEOUT:
1504 result = "TIMEOUT";
1505 break;
1506 case IGT_EXIT_SKIP:
1507 result = "SKIP";
1508 break;
1509 default:
1510 result = "FAIL";
1511 }
1512
Chris Wilsonf2014952016-05-03 11:04:00 +01001513 printf("%s (%.3fs)\n",
1514 result, time_elapsed(&subtest_time, &now));
Thomas Wood16cfa372015-01-27 14:12:27 +00001515 }
Daniel Vetterd63fe152014-03-12 01:29:52 +01001516
Chris Wilsonf2014952016-05-03 11:04:00 +01001517 exit(igt_exitcode);
Daniel Vetterd63fe152014-03-12 01:29:52 +01001518}
1519
1520/* fork support code */
1521static int helper_process_count;
1522static pid_t helper_process_pids[] =
1523{ -1, -1, -1, -1};
1524
1525static void reset_helper_process_list(void)
1526{
1527 for (int i = 0; i < ARRAY_SIZE(helper_process_pids); i++)
1528 helper_process_pids[i] = -1;
1529 helper_process_count = 0;
1530}
1531
Chris Wilson66e46632014-07-24 12:00:57 +01001532static int __waitpid(pid_t pid)
1533{
1534 int status = -1;
1535 while (waitpid(pid, &status, 0) == -1 &&
1536 errno == EINTR)
1537 ;
1538
1539 return status;
1540}
1541
Daniel Vetterd63fe152014-03-12 01:29:52 +01001542static void fork_helper_exit_handler(int sig)
1543{
Chris Wilsonbd3cf812014-07-24 11:41:59 +01001544 /* Inside a signal handler, play safe */
Daniel Vetterd63fe152014-03-12 01:29:52 +01001545 for (int i = 0; i < ARRAY_SIZE(helper_process_pids); i++) {
1546 pid_t pid = helper_process_pids[i];
Daniel Vetterd63fe152014-03-12 01:29:52 +01001547 if (pid != -1) {
Chris Wilsonbd3cf812014-07-24 11:41:59 +01001548 kill(pid, SIGTERM);
Chris Wilson66e46632014-07-24 12:00:57 +01001549 __waitpid(pid);
Daniel Vetterd63fe152014-03-12 01:29:52 +01001550 helper_process_count--;
1551 }
1552 }
1553
1554 assert(helper_process_count == 0);
1555}
1556
1557bool __igt_fork_helper(struct igt_helper_process *proc)
1558{
1559 pid_t pid;
1560 int id;
Paulo Zanonia16ebcc2014-09-03 14:47:21 -03001561 int tmp_count;
Daniel Vetterd63fe152014-03-12 01:29:52 +01001562
1563 assert(!proc->running);
1564 assert(helper_process_count < ARRAY_SIZE(helper_process_pids));
1565
1566 for (id = 0; helper_process_pids[id] != -1; id++)
1567 ;
1568
1569 igt_install_exit_handler(fork_helper_exit_handler);
1570
Paulo Zanonia16ebcc2014-09-03 14:47:21 -03001571 /*
1572 * Avoid races when the parent stops the child before the setup code
1573 * had a chance to run. This happens e.g. when skipping tests wrapped in
1574 * the signal helper.
1575 */
1576 tmp_count = exit_handler_count;
1577 exit_handler_count = 0;
Thomas Wood756764a2014-09-26 15:16:21 +01001578
1579 /* ensure any buffers are flushed before fork */
1580 fflush(NULL);
1581
Daniel Vetterd63fe152014-03-12 01:29:52 +01001582 switch (pid = fork()) {
1583 case -1:
Paulo Zanonia16ebcc2014-09-03 14:47:21 -03001584 exit_handler_count = tmp_count;
Daniel Vetterd63fe152014-03-12 01:29:52 +01001585 igt_assert(0);
1586 case 0:
Daniel Vetterd63fe152014-03-12 01:29:52 +01001587 reset_helper_process_list();
1588 oom_adjust_for_doom();
1589
1590 return true;
1591 default:
Paulo Zanonia16ebcc2014-09-03 14:47:21 -03001592 exit_handler_count = tmp_count;
Daniel Vetterd63fe152014-03-12 01:29:52 +01001593 proc->running = true;
1594 proc->pid = pid;
1595 proc->id = id;
1596 helper_process_pids[id] = pid;
1597 helper_process_count++;
1598
1599 return false;
1600 }
1601
1602}
1603
Daniel Vetter55e64982014-03-12 02:34:40 +01001604/**
Chris Wilson74594552014-07-24 11:44:45 +01001605 * igt_wait_helper:
1606 * @proc: #igt_helper_process structure
1607 *
1608 * Joins a helper process. It is an error to call this on a helper process which
1609 * hasn't been spawned yet.
1610 */
1611int igt_wait_helper(struct igt_helper_process *proc)
1612{
Chris Wilson66e46632014-07-24 12:00:57 +01001613 int status;
Chris Wilson74594552014-07-24 11:44:45 +01001614
1615 assert(proc->running);
1616
Chris Wilson66e46632014-07-24 12:00:57 +01001617 status = __waitpid(proc->pid);
Chris Wilson74594552014-07-24 11:44:45 +01001618
1619 proc->running = false;
1620
1621 helper_process_pids[proc->id] = -1;
1622 helper_process_count--;
1623
1624 return status;
1625}
1626
Chris Wilson2b804c32016-03-29 17:19:31 +01001627static bool helper_was_alive(struct igt_helper_process *proc,
1628 int status)
1629{
1630 return (WIFSIGNALED(status) &&
1631 WTERMSIG(status) == (proc->use_SIGKILL ? SIGKILL : SIGTERM));
1632}
1633
Chris Wilson74594552014-07-24 11:44:45 +01001634/**
Daniel Vetter55e64982014-03-12 02:34:40 +01001635 * igt_stop_helper:
1636 * @proc: #igt_helper_process structure
1637 *
1638 * Terminates a helper process. It is an error to call this on a helper process
1639 * which hasn't been spawned yet.
1640 */
Daniel Vetterd63fe152014-03-12 01:29:52 +01001641void igt_stop_helper(struct igt_helper_process *proc)
1642{
Daniel Vetterd63fe152014-03-12 01:29:52 +01001643 int status;
1644
Chris Wilson74594552014-07-24 11:44:45 +01001645 /* failure here means the pid is already dead and so waiting is safe */
1646 kill(proc->pid, proc->use_SIGKILL ? SIGKILL : SIGTERM);
Daniel Vetterd63fe152014-03-12 01:29:52 +01001647
Chris Wilson74594552014-07-24 11:44:45 +01001648 status = igt_wait_helper(proc);
Chris Wilson2b804c32016-03-29 17:19:31 +01001649 if (!helper_was_alive(proc, status))
1650 igt_debug("Helper died too early with status=%d\n", status);
1651 assert(helper_was_alive(proc, status));
Daniel Vetterd63fe152014-03-12 01:29:52 +01001652}
1653
1654static void children_exit_handler(int sig)
1655{
Chris Wilsonbd3cf812014-07-24 11:41:59 +01001656 int status;
Daniel Vetterd63fe152014-03-12 01:29:52 +01001657
Chris Wilsonbd3cf812014-07-24 11:41:59 +01001658 /* The exit handler can be called from a fatal signal, so play safe */
1659 while (num_test_children-- && wait(&status))
1660 ;
Daniel Vetterd63fe152014-03-12 01:29:52 +01001661}
1662
1663bool __igt_fork(void)
1664{
1665 assert(!test_with_subtests || in_subtest);
1666 assert(!test_child);
1667
1668 igt_install_exit_handler(children_exit_handler);
1669
1670 if (num_test_children >= test_children_sz) {
1671 if (!test_children_sz)
1672 test_children_sz = 4;
1673 else
1674 test_children_sz *= 2;
1675
1676 test_children = realloc(test_children,
1677 sizeof(pid_t)*test_children_sz);
1678 igt_assert(test_children);
1679 }
1680
Thomas Wood756764a2014-09-26 15:16:21 +01001681 /* ensure any buffers are flushed before fork */
1682 fflush(NULL);
1683
Daniel Vetterd63fe152014-03-12 01:29:52 +01001684 switch (test_children[num_test_children++] = fork()) {
1685 case -1:
1686 igt_assert(0);
1687 case 0:
1688 test_child = true;
1689 exit_handler_count = 0;
1690 reset_helper_process_list();
1691 oom_adjust_for_doom();
1692
1693 return true;
1694 default:
1695 return false;
1696 }
1697
1698}
1699
1700/**
Tvrtko Ursulin054eb1a2017-03-30 14:32:29 +01001701 * igt_child_done:
1702 *
1703 * Lets the IGT core know that one of the children has exited.
1704 */
1705void igt_child_done(pid_t pid)
1706{
1707 int i = 0;
1708 int found = -1;
1709
1710 igt_assert(num_test_children > 1);
1711
1712 for (i = 0; i < num_test_children; i++) {
1713 if (pid == test_children[i]) {
1714 found = i;
1715 break;
1716 }
1717 }
1718
1719 igt_assert(found >= 0);
1720
1721 num_test_children--;
1722 for (i = found; i < num_test_children; i++)
1723 test_children[i] = test_children[i + 1];
1724}
1725
1726/**
Daniel Vetterd63fe152014-03-12 01:29:52 +01001727 * igt_waitchildren:
1728 *
Daniel Vetter55e64982014-03-12 02:34:40 +01001729 * Wait for all children forked with igt_fork.
Daniel Vetterd63fe152014-03-12 01:29:52 +01001730 *
1731 * The magic here is that exit codes from children will be correctly propagated
Thomas Wood519f3772014-09-26 14:24:52 +01001732 * to the main thread, including the relevant exit code if a child thread failed.
1733 * Of course if multiple children failed with different exit codes the resulting
1734 * exit code will be non-deterministic.
Daniel Vetter55e64982014-03-12 02:34:40 +01001735 *
1736 * Note that igt_skip() will not be forwarded, feature tests need to be done
1737 * before spawning threads with igt_fork().
Daniel Vetterd63fe152014-03-12 01:29:52 +01001738 */
1739void igt_waitchildren(void)
1740{
Chris Wilsonf47ee312014-07-11 10:15:19 +01001741 int err = 0;
1742 int count;
1743
Daniel Vetterd63fe152014-03-12 01:29:52 +01001744 assert(!test_child);
1745
Chris Wilsonf47ee312014-07-11 10:15:19 +01001746 count = 0;
1747 while (count < num_test_children) {
Daniel Vetterd63fe152014-03-12 01:29:52 +01001748 int status = -1;
Chris Wilsonf47ee312014-07-11 10:15:19 +01001749 pid_t pid;
1750 int c;
Daniel Vetterd63fe152014-03-12 01:29:52 +01001751
Chris Wilsonf47ee312014-07-11 10:15:19 +01001752 pid = wait(&status);
1753 if (pid == -1)
1754 continue;
1755
1756 for (c = 0; c < num_test_children; c++)
1757 if (pid == test_children[c])
1758 break;
1759 if (c == num_test_children)
1760 continue;
1761
1762 if (err == 0 && status != 0) {
Daniel Vetterd63fe152014-03-12 01:29:52 +01001763 if (WIFEXITED(status)) {
1764 printf("child %i failed with exit status %i\n",
Chris Wilsonf47ee312014-07-11 10:15:19 +01001765 c, WEXITSTATUS(status));
1766 err = WEXITSTATUS(status);
Daniel Vetterd63fe152014-03-12 01:29:52 +01001767 } else if (WIFSIGNALED(status)) {
1768 printf("child %i died with signal %i, %s\n",
Chris Wilsonf47ee312014-07-11 10:15:19 +01001769 c, WTERMSIG(status),
Daniel Vetterd63fe152014-03-12 01:29:52 +01001770 strsignal(WTERMSIG(status)));
Chris Wilsonf47ee312014-07-11 10:15:19 +01001771 err = 128 + WTERMSIG(status);
Daniel Vetterd63fe152014-03-12 01:29:52 +01001772 } else {
Chris Wilsonf47ee312014-07-11 10:15:19 +01001773 printf("Unhandled failure [%d] in child %i\n", status, c);
1774 err = 256;
Daniel Vetterd63fe152014-03-12 01:29:52 +01001775 }
Chris Wilsonf47ee312014-07-11 10:15:19 +01001776
1777 for (c = 0; c < num_test_children; c++)
1778 kill(test_children[c], SIGKILL);
Daniel Vetterd63fe152014-03-12 01:29:52 +01001779 }
Chris Wilsonf47ee312014-07-11 10:15:19 +01001780
1781 count++;
Daniel Vetterd63fe152014-03-12 01:29:52 +01001782 }
1783
1784 num_test_children = 0;
Chris Wilsonf47ee312014-07-11 10:15:19 +01001785 if (err)
1786 igt_fail(err);
Daniel Vetterd63fe152014-03-12 01:29:52 +01001787}
1788
Chris Wilson75487632016-02-26 22:11:10 +00001789/**
1790 * igt_waitchildren_timeout:
Daniel Vetter483d1c02016-03-19 12:12:47 +01001791 * @seconds: timeout in seconds to wait
Daniel Vetter28699212016-03-19 15:14:19 +01001792 * @reason: debug string explaining what timedout
Chris Wilson75487632016-02-26 22:11:10 +00001793 *
1794 * Wait for all children forked with igt_fork, for a maximum of @seconds.
1795 *
1796 * Wraps igt_waitchildren() and igt_set_timeout()
1797 */
1798void igt_waitchildren_timeout(int seconds, const char *reason)
1799{
1800 igt_set_timeout(seconds, reason);
1801 igt_waitchildren();
1802 igt_reset_timeout();
1803}
1804
Daniel Vetterd63fe152014-03-12 01:29:52 +01001805/* exit handler code */
1806#define MAX_SIGNALS 32
Thomas Wood8a3853c2014-07-17 11:19:04 +01001807#define MAX_EXIT_HANDLERS 10
Daniel Vetterd63fe152014-03-12 01:29:52 +01001808
Alan Coopersmith95ea5d52014-12-23 19:07:12 -08001809#ifndef HAVE_SIGHANDLER_T
1810typedef void (*sighandler_t)(int);
1811#endif
1812
Daniel Vetterd63fe152014-03-12 01:29:52 +01001813static struct {
1814 sighandler_t handler;
1815 bool installed;
1816} orig_sig[MAX_SIGNALS];
1817
1818static igt_exit_handler_t exit_handler_fn[MAX_EXIT_HANDLERS];
1819static bool exit_handler_disabled;
Thomas Wood4ff4ea62015-02-19 13:58:06 +00001820#define SIGDEF(x) { x, #x, sizeof(#x) - 1 }
Chris Wilson2fa35c72015-03-19 08:29:51 +00001821#define SILENT(x) { x, NULL, 0 }
Thomas Wood4ff4ea62015-02-19 13:58:06 +00001822static const struct { int number; const char *name; size_t name_len; } handled_signals[] =
Chris Wilson2fa35c72015-03-19 08:29:51 +00001823 { SILENT(SIGINT), SILENT(SIGHUP), SILENT(SIGTERM), SILENT(SIGQUIT),
marius vlad1ae41a52016-08-24 11:44:07 +03001824 SILENT(SIGPIPE), SIGDEF(SIGABRT), SIGDEF(SIGSEGV), SIGDEF(SIGBUS),
1825 SIGDEF(SIGFPE) };
Chris Wilson2fa35c72015-03-19 08:29:51 +00001826#undef SILENT
1827#undef SIGDEF
Daniel Vetterd63fe152014-03-12 01:29:52 +01001828
1829static int install_sig_handler(int sig_num, sighandler_t handler)
1830{
1831 orig_sig[sig_num].handler = signal(sig_num, handler);
1832
1833 if (orig_sig[sig_num].handler == SIG_ERR)
1834 return -1;
1835
1836 orig_sig[sig_num].installed = true;
1837
1838 return 0;
1839}
1840
1841static void restore_sig_handler(int sig_num)
1842{
1843 /* Just restore the default so that we properly fall over. */
1844 signal(sig_num, SIG_DFL);
1845}
1846
1847static void restore_all_sig_handler(void)
1848{
1849 int i;
1850
1851 for (i = 0; i < ARRAY_SIZE(orig_sig); i++)
1852 restore_sig_handler(i);
1853}
1854
1855static void call_exit_handlers(int sig)
1856{
1857 int i;
1858
1859 if (!exit_handler_count) {
1860 return;
1861 }
1862
1863 for (i = exit_handler_count - 1; i >= 0; i--)
1864 exit_handler_fn[i](sig);
1865
1866 /* ensure we don't get called twice */
1867 exit_handler_count = 0;
1868}
1869
1870static void igt_atexit_handler(void)
1871{
Thomas Woode65c69b2015-07-16 17:39:59 +01001872 in_atexit_handler = true;
1873
Daniel Vetterd63fe152014-03-12 01:29:52 +01001874 restore_all_sig_handler();
1875
1876 if (!exit_handler_disabled)
1877 call_exit_handlers(0);
1878}
1879
Chris Wilson9b0a32d2015-05-10 09:09:54 +01001880static bool crash_signal(int sig)
1881{
1882 switch (sig) {
1883 case SIGILL:
1884 case SIGBUS:
marius vlad1ae41a52016-08-24 11:44:07 +03001885 case SIGFPE:
Chris Wilson9b0a32d2015-05-10 09:09:54 +01001886 case SIGSEGV:
1887 return true;
1888 default:
1889 return false;
1890 }
1891}
1892
Daniel Vetterd63fe152014-03-12 01:29:52 +01001893static void fatal_sig_handler(int sig)
1894{
Thomas Wood4ff4ea62015-02-19 13:58:06 +00001895 int i;
1896
Thomas Wood4ff4ea62015-02-19 13:58:06 +00001897 for (i = 0; i < ARRAY_SIZE(handled_signals); i++) {
Chris Wilson2fa35c72015-03-19 08:29:51 +00001898 if (handled_signals[i].number != sig)
1899 continue;
1900
1901 if (handled_signals[i].name_len) {
Thomas Wood47f6b132015-03-25 16:42:57 +00001902 igt_assert_eq(write(STDERR_FILENO, "Received signal ", 16),
1903 16);
1904 igt_assert_eq(write(STDERR_FILENO, handled_signals[i].name, handled_signals[i].name_len),
1905 handled_signals[i].name_len);
1906 igt_assert_eq(write(STDERR_FILENO, ".\n", 2), 2);
Thomas Wood4ff4ea62015-02-19 13:58:06 +00001907 }
Chris Wilson2fa35c72015-03-19 08:29:51 +00001908
Marius Vlad75cba292016-09-19 18:38:56 +03001909 if (crash_signal(sig)) {
Derek Mortonf4972382015-05-18 14:37:31 +01001910 /* Linux standard to return exit code as 128 + signal */
1911 if (!failed_one)
1912 igt_exitcode = 128 + sig;
1913
1914 failed_one = true;
Marius Vlad8da2b542016-09-02 14:34:46 +03001915#ifdef HAVE_LIBUNWIND
marius vlad1ae41a52016-08-24 11:44:07 +03001916 print_backtrace_sig_safe();
Marius Vlad8da2b542016-09-02 14:34:46 +03001917#endif
Marius Vlad75cba292016-09-19 18:38:56 +03001918 if (in_subtest)
1919 exit_subtest("CRASH");
Derek Mortonf4972382015-05-18 14:37:31 +01001920 }
Chris Wilson2fa35c72015-03-19 08:29:51 +00001921 break;
Thomas Wood4ff4ea62015-02-19 13:58:06 +00001922 }
1923
Chris Wilson578795f2015-05-08 14:35:37 +01001924 restore_all_sig_handler();
1925
Daniel Vetterd63fe152014-03-12 01:29:52 +01001926 /*
1927 * exit_handler_disabled is always false here, since when we set it
1928 * we also block signals.
1929 */
1930 call_exit_handlers(sig);
1931
Alan Coopersmith99e6def2014-12-23 19:07:10 -08001932 {
1933#ifdef __linux__
Daniel Vetterd63fe152014-03-12 01:29:52 +01001934 /* Workaround cached PID and TID races on glibc and Bionic libc. */
Alan Coopersmith99e6def2014-12-23 19:07:10 -08001935 pid_t pid = syscall(SYS_getpid);
1936 pid_t tid = syscall(SYS_gettid);
Daniel Vetterd63fe152014-03-12 01:29:52 +01001937
Alan Coopersmith99e6def2014-12-23 19:07:10 -08001938 syscall(SYS_tgkill, pid, tid, sig);
1939#else
1940 pthread_t tid = pthread_self();
1941 union sigval value = { .sival_ptr = NULL };
1942
1943 pthread_sigqueue(tid, sig, value);
1944#endif
1945 }
Daniel Vetterd63fe152014-03-12 01:29:52 +01001946}
1947
Daniel Vetter55e64982014-03-12 02:34:40 +01001948/**
1949 * igt_install_exit_handler:
1950 * @fn: exit handler function
1951 *
Daniel Vetterd63fe152014-03-12 01:29:52 +01001952 * Set a handler that will be called either when the process calls exit() or
Thomas Wood52a3a2e2014-06-09 17:23:21 +01001953 * <!-- -->returns from the main function, or one of the signals in
1954 * 'handled_signals' is raised. MAX_EXIT_HANDLERS handlers can be installed,
1955 * each of which will be called only once, even if a subsequent signal is
1956 * raised. If the exit handlers are called due to a signal, the signal will be
1957 * re-raised with the original signal disposition after all handlers returned.
Daniel Vetterd63fe152014-03-12 01:29:52 +01001958 *
1959 * The handler will be passed the signal number if called due to a signal, or
Daniel Vetter55e64982014-03-12 02:34:40 +01001960 * 0 otherwise. Exit handlers can also be used from test children spawned with
1961 * igt_fork(), but not from within helper processes spawned with
Daniel Vetter3ea97f22014-03-16 18:56:14 +01001962 * igt_fork_helper(). The list of exit handlers is reset when forking to
Daniel Vetter55e64982014-03-12 02:34:40 +01001963 * avoid issues with children cleanup up the parent's state too early.
Daniel Vetterd63fe152014-03-12 01:29:52 +01001964 */
1965void igt_install_exit_handler(igt_exit_handler_t fn)
1966{
1967 int i;
1968
1969 for (i = 0; i < exit_handler_count; i++)
1970 if (exit_handler_fn[i] == fn)
1971 return;
1972
1973 igt_assert(exit_handler_count < MAX_EXIT_HANDLERS);
1974
1975 exit_handler_fn[exit_handler_count] = fn;
1976 exit_handler_count++;
1977
1978 if (exit_handler_count > 1)
1979 return;
1980
1981 for (i = 0; i < ARRAY_SIZE(handled_signals); i++) {
Thomas Wood4ff4ea62015-02-19 13:58:06 +00001982 if (install_sig_handler(handled_signals[i].number,
Daniel Vetterd63fe152014-03-12 01:29:52 +01001983 fatal_sig_handler))
1984 goto err;
1985 }
1986
1987 if (atexit(igt_atexit_handler))
1988 goto err;
1989
1990 return;
1991err:
1992 restore_all_sig_handler();
1993 exit_handler_count--;
1994
1995 igt_assert_f(0, "failed to install the signal handler\n");
1996}
1997
Daniel Vetterd63fe152014-03-12 01:29:52 +01001998/* simulation enviroment support */
Daniel Vetter55e64982014-03-12 02:34:40 +01001999
2000/**
2001 * igt_run_in_simulation:
2002 *
2003 * This function can be used to select a reduced test set when running in
Thomas Wood519f3772014-09-26 14:24:52 +01002004 * simulation environments. This i-g-t mode is selected by setting the
2005 * INTEL_SIMULATION environment variable to 1.
Daniel Vetter55e64982014-03-12 02:34:40 +01002006 *
2007 * Returns: True when run in simulation mode, false otherwise.
2008 */
Daniel Vetterd63fe152014-03-12 01:29:52 +01002009bool igt_run_in_simulation(void)
2010{
2011 static int simulation = -1;
2012
2013 if (simulation == -1)
Daniel Vetter8221fda2014-03-23 14:38:17 +01002014 simulation = igt_check_boolean_env_var("INTEL_SIMULATION", false);
Daniel Vetterd63fe152014-03-12 01:29:52 +01002015
2016 return simulation;
2017}
2018
2019/**
2020 * igt_skip_on_simulation:
2021 *
Daniel Vetter55e64982014-03-12 02:34:40 +01002022 * Skip tests when INTEL_SIMULATION environment variable is set. It uses
2023 * igt_skip() internally and hence is fully subtest aware.
Daniel Vettera388f3b2014-03-22 13:22:11 +01002024 *
2025 * Note that in contrast to all other functions which use igt_skip() internally
2026 * it is allowed to use this outside of an #igt_fixture block in a test with
2027 * subtests. This is because in contrast to most other test requirements,
2028 * checking for simulation mode doesn't depend upon the present hardware and it
2029 * so makes a lot of sense to have this check in the outermost #igt_main block.
Daniel Vetterd63fe152014-03-12 01:29:52 +01002030 */
2031void igt_skip_on_simulation(void)
2032{
2033 if (igt_only_list_subtests())
2034 return;
2035
Daniel Vetter2459b802017-08-14 11:32:04 +02002036 if (!igt_can_fail()) {
Daniel Vettera388f3b2014-03-22 13:22:11 +01002037 igt_fixture
2038 igt_require(!igt_run_in_simulation());
2039 } else
2040 igt_require(!igt_run_in_simulation());
Daniel Vetterd63fe152014-03-12 01:29:52 +01002041}
2042
2043/* structured logging */
Daniel Vetter55e64982014-03-12 02:34:40 +01002044
2045/**
2046 * igt_log:
Thomas Woodf59bbf72014-12-12 14:18:07 +00002047 * @domain: the log domain, or NULL for no domain
Daniel Vetter55e64982014-03-12 02:34:40 +01002048 * @level: #igt_log_level
2049 * @format: format string
2050 * @...: optional arguments used in the format string
2051 *
Daniel Vetter126b8ba2014-05-13 12:28:26 +02002052 * This is the generic structured logging helper function. i-g-t testcase should
Daniel Vetter55e64982014-03-12 02:34:40 +01002053 * output all normal message to stdout. Warning level message should be printed
2054 * to stderr and the test runner should treat this as an intermediate result
Thomas Woodd01ebbd2015-06-29 16:47:14 +01002055 * between SUCCESS and FAILURE.
Daniel Vetter55e64982014-03-12 02:34:40 +01002056 *
Thomas Wood519f3772014-09-26 14:24:52 +01002057 * The log level can be set through the IGT_LOG_LEVEL environment variable with
Thomas Wooddf11a0f2014-12-16 15:18:20 +00002058 * values "debug", "info", "warn", "critical" and "none". By default verbose
2059 * debug message are disabled. "none" completely disables all output and is not
2060 * recommended since crucial issues only reported at the IGT_LOG_WARN level are
2061 * ignored.
Daniel Vetter55e64982014-03-12 02:34:40 +01002062 */
Thomas Wood8161a212014-12-02 10:54:54 +00002063void igt_log(const char *domain, enum igt_log_level level, const char *format, ...)
Daniel Vetterd63fe152014-03-12 01:29:52 +01002064{
2065 va_list args;
2066
Daniel Vetterd63fe152014-03-12 01:29:52 +01002067 va_start(args, format);
Thomas Wood8161a212014-12-02 10:54:54 +00002068 igt_vlog(domain, level, format, args);
Daniel Vetterd63fe152014-03-12 01:29:52 +01002069 va_end(args);
2070}
Daniel Vetterbd53d722014-03-13 17:27:47 +01002071
2072/**
2073 * igt_vlog:
Thomas Woodf59bbf72014-12-12 14:18:07 +00002074 * @domain: the log domain, or NULL for no domain
Daniel Vetterbd53d722014-03-13 17:27:47 +01002075 * @level: #igt_log_level
2076 * @format: format string
2077 * @args: variable arguments lists
2078 *
2079 * This is the generic logging helper function using an explicit varargs
2080 * structure and hence useful to implement domain-specific logging
2081 * functions.
2082 *
2083 * If there is no need to wrap up a vararg list in the caller it is simpler to
2084 * just use igt_log().
2085 */
Thomas Wood8161a212014-12-02 10:54:54 +00002086void igt_vlog(const char *domain, enum igt_log_level level, const char *format, va_list args)
Daniel Vetterbd53d722014-03-13 17:27:47 +01002087{
Thomas Wood8161a212014-12-02 10:54:54 +00002088 FILE *file;
Thomas Wooda5f21722015-01-19 15:27:51 +00002089 char *line, *formatted_line;
Thomas Wood8161a212014-12-02 10:54:54 +00002090 const char *program_name;
2091 const char *igt_log_level_str[] = {
2092 "DEBUG",
2093 "INFO",
2094 "WARNING",
Thomas Wooddf11a0f2014-12-16 15:18:20 +00002095 "CRITICAL",
Thomas Wood8161a212014-12-02 10:54:54 +00002096 "NONE"
2097 };
Daniel Vetterf45698d2015-02-27 19:32:33 +01002098 static bool line_continuation = false;
Thomas Wood8161a212014-12-02 10:54:54 +00002099
Daniel Vetterbd53d722014-03-13 17:27:47 +01002100 assert(format);
2101
Thomas Wood8161a212014-12-02 10:54:54 +00002102#ifdef __GLIBC__
2103 program_name = program_invocation_short_name;
2104#else
2105 program_name = command_str;
2106#endif
2107
Thomas Wood61737902015-01-26 16:09:40 +00002108 if (list_subtests && level <= IGT_LOG_WARN)
Daniel Vetterbebcb582014-07-11 10:24:30 +02002109 return;
2110
Thomas Wooda5f21722015-01-19 15:27:51 +00002111 if (vasprintf(&line, format, args) == -1)
Daniel Vetterbd53d722014-03-13 17:27:47 +01002112 return;
2113
Daniel Vetterf45698d2015-02-27 19:32:33 +01002114 if (line_continuation) {
2115 formatted_line = strdup(line);
2116 if (!formatted_line)
2117 goto out;
2118 } else if (asprintf(&formatted_line, "(%s:%d) %s%s%s: %s", program_name,
Thomas Wooda5f21722015-01-19 15:27:51 +00002119 getpid(), (domain) ? domain : "", (domain) ? "-" : "",
2120 igt_log_level_str[level], line) == -1) {
2121 goto out;
2122 }
2123
Derek Morton8528b482015-12-23 15:34:48 +00002124 line_continuation = line[strlen(line) - 1] != '\n';
Daniel Vetterf45698d2015-02-27 19:32:33 +01002125
Thomas Wooda5f21722015-01-19 15:27:51 +00002126 /* append log buffer */
2127 _igt_log_buffer_append(formatted_line);
2128
2129 /* check print log level */
2130 if (igt_log_level > level)
2131 goto out;
2132
2133 /* check domain filter */
Thomas Wood5fe9c882014-12-02 11:37:26 +00002134 if (igt_log_domain_filter) {
2135 /* if null domain and filter is not "application", return */
2136 if (!domain && strcmp(igt_log_domain_filter, "application"))
Thomas Wooda5f21722015-01-19 15:27:51 +00002137 goto out;
Thomas Wood5fe9c882014-12-02 11:37:26 +00002138 /* else if domain and filter do not match, return */
2139 else if (domain && strcmp(igt_log_domain_filter, domain))
Thomas Wooda5f21722015-01-19 15:27:51 +00002140 goto out;
Thomas Wood5fe9c882014-12-02 11:37:26 +00002141 }
2142
Thomas Wooda5f21722015-01-19 15:27:51 +00002143 /* use stderr for warning messages and above */
Thomas Wooda2282232015-01-26 16:09:09 +00002144 if (level >= IGT_LOG_WARN) {
Thomas Wood8161a212014-12-02 10:54:54 +00002145 file = stderr;
Daniel Vetterbd53d722014-03-13 17:27:47 +01002146 fflush(stdout);
Thomas Wood8161a212014-12-02 10:54:54 +00002147 }
2148 else
2149 file = stdout;
2150
Thomas Wooda5f21722015-01-19 15:27:51 +00002151 /* prepend all except information messages with process, domain and log
2152 * level information */
2153 if (level != IGT_LOG_INFO)
2154 fwrite(formatted_line, sizeof(char), strlen(formatted_line),
2155 file);
2156 else
2157 fwrite(line, sizeof(char), strlen(line), file);
2158
2159out:
2160 free(line);
Daniel Vetterbd53d722014-03-13 17:27:47 +01002161}
Thomas Woodd8e53132014-05-12 10:19:52 +01002162
Daniel Vetter370c9892015-08-07 19:01:23 +02002163static const char *timeout_op;
Thomas Wood36b81432015-11-02 10:02:08 +00002164static void __attribute__((noreturn)) igt_alarm_handler(int signal)
Thomas Woodd8e53132014-05-12 10:19:52 +01002165{
Daniel Vetter370c9892015-08-07 19:01:23 +02002166 if (timeout_op)
2167 igt_info("Timed out: %s\n", timeout_op);
2168 else
2169 igt_info("Timed out\n");
Thomas Woodcff102e2015-04-09 09:27:54 +01002170
2171 /* exit with failure status */
2172 igt_fail(IGT_EXIT_FAILURE);
Thomas Woodd8e53132014-05-12 10:19:52 +01002173}
2174
2175/**
2176 * igt_set_timeout:
2177 * @seconds: number of seconds before timeout
Daniel Vetter370c9892015-08-07 19:01:23 +02002178 * @op: Optional string to explain what operation has timed out in the debug log
Thomas Woodd8e53132014-05-12 10:19:52 +01002179 *
Thomas Woodcff102e2015-04-09 09:27:54 +01002180 * Fail a test and exit with #IGT_EXIT_FAILURE status after the specified
Thomas Woodebab9f02014-11-13 11:47:19 +00002181 * number of seconds have elapsed. If the current test has subtests and the
2182 * timeout occurs outside a subtest, subsequent subtests will be skipped and
2183 * marked as failed.
Thomas Woodd8e53132014-05-12 10:19:52 +01002184 *
Thomas Woodebab9f02014-11-13 11:47:19 +00002185 * Any previous timer is cancelled and no timeout is scheduled if @seconds is
Daniel Vetter5b0a8432015-08-07 19:12:07 +02002186 * zero. But for clarity the timeout set with this function should be cleared
2187 * with igt_reset_timeout().
Thomas Woodd8e53132014-05-12 10:19:52 +01002188 */
Daniel Vetter370c9892015-08-07 19:01:23 +02002189void igt_set_timeout(unsigned int seconds,
2190 const char *op)
Thomas Woodd8e53132014-05-12 10:19:52 +01002191{
2192 struct sigaction sa;
2193
2194 sa.sa_handler = igt_alarm_handler;
2195 sigemptyset(&sa.sa_mask);
2196 sa.sa_flags = 0;
2197
Daniel Vetter370c9892015-08-07 19:01:23 +02002198 timeout_op = op;
2199
Thomas Woodd8e53132014-05-12 10:19:52 +01002200 if (seconds == 0)
2201 sigaction(SIGALRM, NULL, NULL);
2202 else
2203 sigaction(SIGALRM, &sa, NULL);
2204
2205 alarm(seconds);
2206}
Joonas Lahtinena95033f2015-03-31 15:53:17 +03002207
Daniel Vetter5b0a8432015-08-07 19:12:07 +02002208/**
Thomas Woodf0381d12015-09-07 09:26:01 +01002209 * igt_reset_timeout:
Daniel Vetter5b0a8432015-08-07 19:12:07 +02002210 *
2211 * This function resets a timeout set by igt_set_timeout() and disables any
2212 * timer set up by the former function.
2213 */
2214void igt_reset_timeout(void)
2215{
2216 igt_set_timeout(0, NULL);
2217}
2218
Joonas Lahtinena95033f2015-03-31 15:53:17 +03002219FILE *__igt_fopen_data(const char* igt_srcdir, const char* igt_datadir,
2220 const char* filename)
2221{
2222 char path[PATH_MAX];
2223 FILE *fp;
2224
2225 snprintf(path, sizeof(path), "%s/%s", igt_datadir, filename);
2226 fp = fopen(path, "r");
2227 if (!fp) {
2228 snprintf(path, sizeof(path), "%s/%s", igt_srcdir, filename);
2229 fp = fopen(path, "r");
2230 }
Matt Roper303b3802016-05-26 16:02:05 -07002231 if (!fp) {
2232 snprintf(path, sizeof(path), "./%s", filename);
2233 fp = fopen(path, "r");
2234 }
Thomas Wood90dadcd2015-04-13 12:09:48 +01002235
2236 if (!fp)
2237 igt_critical("Could not open data file \"%s\": %s", filename,
2238 strerror(errno));
2239
Joonas Lahtinena95033f2015-03-31 15:53:17 +03002240 return fp;
2241}
Abdiel Janulgue51f4f9f2017-04-13 13:43:20 +03002242
Petri Latvalaf16a7992017-09-21 15:52:28 +03002243static void log_output(int *fd, enum igt_log_level level)
Abdiel Janulgue51f4f9f2017-04-13 13:43:20 +03002244{
Petri Latvalaf16a7992017-09-21 15:52:28 +03002245 ssize_t len;
2246 char buf[PIPE_BUF];
Abdiel Janulgue51f4f9f2017-04-13 13:43:20 +03002247
Petri Latvalaf16a7992017-09-21 15:52:28 +03002248 if (*fd < 0)
Abdiel Janulgue51f4f9f2017-04-13 13:43:20 +03002249 return;
2250
Petri Latvalaf16a7992017-09-21 15:52:28 +03002251 memset(buf, 0, sizeof(buf));
2252 len = read(*fd, buf, sizeof(buf));
2253 if (len <= 0) {
2254 close(*fd);
2255 *fd = -1;
2256 return;
2257 }
2258
2259 igt_log(IGT_LOG_DOMAIN, level, "[cmd] %s", buf);
Abdiel Janulgue51f4f9f2017-04-13 13:43:20 +03002260}
2261
2262/**
2263 * igt_system:
2264 *
2265 * An improved replacement of the system() call.
2266 *
2267 * Executes the shell command specified in @command with the added feature of
2268 * concurrently capturing its stdout and stderr to igt_log and igt_warn
2269 * respectively.
2270 *
2271 * Returns: The exit status of the executed process. -1 for failure.
2272 */
2273int igt_system(const char *command)
2274{
Petri Latvalaf16a7992017-09-21 15:52:28 +03002275 int outpipe[2] = { -1, -1 };
2276 int errpipe[2] = { -1, -1 };
2277 int status;
Abdiel Janulgue51f4f9f2017-04-13 13:43:20 +03002278 struct igt_helper_process process = {};
Abdiel Janulgue51f4f9f2017-04-13 13:43:20 +03002279
Petri Latvalaf16a7992017-09-21 15:52:28 +03002280 if (pipe(outpipe) < 0)
Abdiel Janulgue51f4f9f2017-04-13 13:43:20 +03002281 goto err;
Petri Latvalaf16a7992017-09-21 15:52:28 +03002282 if (pipe(errpipe) < 0)
Abdiel Janulgue51f4f9f2017-04-13 13:43:20 +03002283 goto err;
2284
Imre Deak40d6f192017-10-13 14:30:08 +03002285 /*
2286 * The clone() system call called from a largish executable has
2287 * difficulty to make progress if interrupted too frequently, so
2288 * suspend the signal helper for the time of the syscall.
2289 */
2290 igt_suspend_signal_helper();
2291
Abdiel Janulgue51f4f9f2017-04-13 13:43:20 +03002292 igt_fork_helper(&process) {
Petri Latvalaf16a7992017-09-21 15:52:28 +03002293 close(outpipe[0]);
2294 close(errpipe[0]);
2295
2296 if (dup2(outpipe[1], STDOUT_FILENO) < 0)
2297 goto child_err;
2298 if (dup2(errpipe[1], STDERR_FILENO) < 0)
2299 goto child_err;
2300
2301 execl("/bin/sh", "sh", "-c", command,
2302 (char *) NULL);
2303
2304 child_err:
2305 exit(EXIT_FAILURE);
Abdiel Janulgue51f4f9f2017-04-13 13:43:20 +03002306 }
2307
Imre Deak40d6f192017-10-13 14:30:08 +03002308 igt_resume_signal_helper();
2309
Petri Latvalaf16a7992017-09-21 15:52:28 +03002310 close(outpipe[1]);
2311 close(errpipe[1]);
Abdiel Janulgue51f4f9f2017-04-13 13:43:20 +03002312
Petri Latvalaf16a7992017-09-21 15:52:28 +03002313 while (outpipe[0] >= 0 || errpipe[0] >= 0) {
2314 log_output(&outpipe[0], IGT_LOG_INFO);
2315 log_output(&errpipe[0], IGT_LOG_WARN);
Abdiel Janulgue51f4f9f2017-04-13 13:43:20 +03002316 }
Petri Latvalaf16a7992017-09-21 15:52:28 +03002317
Abdiel Janulgue51f4f9f2017-04-13 13:43:20 +03002318 status = igt_wait_helper(&process);
2319
2320 return WEXITSTATUS(status);
2321err:
Petri Latvalaf16a7992017-09-21 15:52:28 +03002322 close(outpipe[0]);
2323 close(outpipe[1]);
2324 close(errpipe[0]);
2325 close(errpipe[1]);
Abdiel Janulgue51f4f9f2017-04-13 13:43:20 +03002326 return -1;
2327}
2328
2329/**
2330 * igt_system_quiet:
2331 * Similar to igt_system(), except redirect output to /dev/null
2332 *
2333 * Returns: The exit status of the executed process. -1 for failure.
2334 */
2335int igt_system_quiet(const char *command)
2336{
2337 int stderr_fd_copy, stdout_fd_copy, status, nullfd;
2338
2339 /* redirect */
2340 if ((nullfd = open("/dev/null", O_WRONLY)) == -1)
2341 goto err;
2342 if ((stdout_fd_copy = dup(STDOUT_FILENO)) == -1)
2343 goto err;
2344 if ((stderr_fd_copy = dup(STDERR_FILENO)) == -1)
2345 goto err;
2346
2347 if (dup2(nullfd, STDOUT_FILENO) == -1)
2348 goto err;
2349 if (dup2(nullfd, STDERR_FILENO) == -1)
2350 goto err;
2351
Imre Deak40d6f192017-10-13 14:30:08 +03002352 /* See igt_system() for the reason for suspending the signal helper. */
2353 igt_suspend_signal_helper();
2354
Abdiel Janulgue51f4f9f2017-04-13 13:43:20 +03002355 if ((status = system(command)) == -1)
2356 goto err;
2357
Imre Deak40d6f192017-10-13 14:30:08 +03002358 igt_resume_signal_helper();
2359
Abdiel Janulgue51f4f9f2017-04-13 13:43:20 +03002360 /* restore */
2361 if (dup2(stdout_fd_copy, STDOUT_FILENO) == -1)
2362 goto err;
2363 if (dup2(stderr_fd_copy, STDERR_FILENO) == -1)
2364 goto err;
2365
2366 close(stdout_fd_copy);
2367 close(stderr_fd_copy);
2368 close(nullfd);
2369
2370 return WEXITSTATUS(status);
2371err:
Imre Deak40d6f192017-10-13 14:30:08 +03002372 igt_resume_signal_helper();
2373
Abdiel Janulgue51f4f9f2017-04-13 13:43:20 +03002374 close(stderr_fd_copy);
2375 close(stdout_fd_copy);
2376 close(nullfd);
2377
2378 return -1;
2379}