igt_core.c 60 KB
Newer Older
Daniel Vetter's avatar
Daniel Vetter committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
/*
 * Copyright © 2007, 2011, 2013, 2014 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 *
 * Authors:
 *    Eric Anholt <eric@anholt.net>
 *    Daniel Vetter <daniel.vetter@ffwll.ch>
 *
 */

29
#ifdef HAVE_LIBGEN_H
Daniel Vetter's avatar
Daniel Vetter committed
30 31 32
#include <libgen.h>
#endif
#include <stdio.h>
33
#include <assert.h>
Daniel Vetter's avatar
Daniel Vetter committed
34 35 36 37 38 39 40 41 42 43 44 45
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <string.h>
#include <sys/mman.h>
#include <signal.h>
#include <pciaccess.h>
#include <getopt.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
46
#ifdef __linux__
Daniel Vetter's avatar
Daniel Vetter committed
47
#include <sys/syscall.h>
48
#endif
49
#include <pthread.h>
Daniel Vetter's avatar
Daniel Vetter committed
50 51
#include <sys/utsname.h>
#include <termios.h>
52
#include <errno.h>
53
#include <time.h>
54
#include <ctype.h>
55
#include <limits.h>
56
#include <locale.h>
57
#include <uwildmat/uwildmat.h>
58
#include <glib.h>
Daniel Vetter's avatar
Daniel Vetter committed
59 60 61

#include "drmtest.h"
#include "intel_chipset.h"
62
#include "intel_io.h"
Daniel Vetter's avatar
Daniel Vetter committed
63
#include "igt_debugfs.h"
64
#include "igt_dummyload.h"
65
#include "version.h"
Daniel Vetter's avatar
Daniel Vetter committed
66 67 68
#include "config.h"

#include "igt_core.h"
69
#include "igt_aux.h"
70
#include "igt_sysfs.h"
71
#include "igt_sysrq.h"
72
#include "igt_rc.h"
Daniel Vetter's avatar
Daniel Vetter committed
73

74 75
#define UNW_LOCAL_ONLY
#include <libunwind.h>
76
#include <elfutils/libdwfl.h>
77

78 79 80 81
#ifdef HAVE_LIBGEN_H
#include <libgen.h>   /* for basename() on Solaris */
#endif

Daniel Vetter's avatar
Daniel Vetter committed
82 83 84
/**
 * SECTION:igt_core
 * @short_description: Core i-g-t testing support
85
 * @title: Core
86
 * @include: igt.h
87
 *
88
 * This library implements the core of the i-g-t test support infrastructure.
Daniel Vetter's avatar
Daniel Vetter committed
89 90 91 92 93 94 95 96
 * Main features are the subtest enumeration, cmdline option parsing helpers for
 * subtest handling and various helpers to structure testcases with subtests and
 * handle subtest test results.
 *
 * Auxiliary code provides exit handlers, support for forked processes with test
 * result propagation. Other generally useful functionality includes optional
 * structure logging infrastructure and some support code for running reduced
 * test set on in simulated hardware environments.
97 98 99 100 101 102 103 104 105 106
 *
 * When writing tests with subtests it is extremely important that nothing
 * interferes with the subtest enumeration. In i-g-t subtests are enumerated at
 * runtime, which allows powerful testcase enumeration. But it makes subtest
 * enumeration a bit more tricky since the test code needs to be careful to
 * never run any code which might fail (like trying to do privileged operations
 * or opening device driver nodes).
 *
 * To allow this i-g-t provides #igt_fixture code blocks for setup code outside
 * of subtests and automatically skips the subtest code blocks themselves. For
107 108 109
 * special cases igt_only_list_subtests() is also provided. For setup code only
 * shared by a group of subtest encapsulate the #igt_fixture block and all the
 * subtestest in a #igt_subtest_group block.
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
 *
 * # Magic Control Blocks
 *
 * i-g-t makes heavy use of C macros which serve as magic control blocks. They
 * work fairly well and transparently but since C doesn't have full-blown
 * closures there are caveats:
 *
 * - Asynchronous blocks which are used to spawn children internally use fork().
 *   Which means that nonsensical control flow like jumping out of the control
 *   block is possible, but it will badly confuse the i-g-t library code. And of
 *   course all caveats of a real fork() call apply, namely that file
 *   descriptors are copied, but still point at the original file. This will
 *   terminally upset the libdrm buffer manager if both parent and child keep on
 *   using the same open instance of the drm device. Usually everything related
 *   to interacting with the kernel driver must be reinitialized to avoid such
 *   issues.
 *
 * - Code blocks with magic control flow are implemented with setjmp() and
 *   longjmp(). This applies to #igt_fixture and #igt_subtest blocks and all the
 *   three variants to finish test: igt_success(), igt_skip() and igt_fail().
 *   Mostly this is of no concern, except when such a control block changes
 *   stack variables defined in the same function as the control block resides.
 *   Any store/load behaviour after a longjmp() is ill-defined for these
 *   variables. Avoid such code.
 *
 *   Quoting the man page for longjmp():
 *
 *   "The values of automatic variables are unspecified after a call to
 *   longjmp() if they meet all the following criteria:"
 *    - "they are local to the function that made the corresponding setjmp() call;
 *    - "their values are changed between the calls to setjmp() and longjmp(); and
 *    - "they are not declared as volatile."
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
 *
 * # Best Practices for Test Helper Libraries Design
 *
 * Kernel tests itself tend to have fairly complex logic already. It is
 * therefore paramount that helper code, both in libraries and test-private
 * functions, add as little boilerplate code to the main test logic as possible.
 * But then dense code is hard to understand without constantly consulting
 * the documentation and implementation of all the helper functions if it
 * doesn't follow some clear patterns. Hence follow these established best
 * practices:
 *
 * - Make extensive use of the implicit control flow afforded by igt_skip(),
 *   igt_fail and igt_success(). When dealing with optional kernel features
 *   combine igt_skip() with igt_fail() to skip when the kernel support isn't
 *   available but fail when anything else goes awry. void should be the most
 *   common return type in all your functions, except object constructors of
 *   course.
 *
 * - The main test logic should have no explicit control flow for failure
 *   conditions, but instead such assumptions should be written in a declarative
 *   style.  Use one of the many macros which encapsulate i-g-t's implicit
 *   control flow.  Pick the most suitable one to have as much debug output as
164
 *   possible without polluting the code unnecessarily. For example
165
 *   igt_assert_cmpint() for comparing integers or do_ioctl() for running ioctls
166
 *   and checking their results.  Feel free to add new ones to the library or
167 168 169 170
 *   wrap up a set of checks into a private function to further condense your
 *   test logic.
 *
 * - When adding a new feature test function which uses igt_skip() internally,
171
 *   use the {prefix}_require_{feature_name} naming scheme. When you
172 173
 *   instead add a feature test function which returns a boolean, because your
 *   main test logic must take different actions depending upon the feature's
174
 *   availability, then instead use the {prefix}_has_{feature_name}.
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
 *
 * - As already mentioned eschew explicit error handling logic as much as
 *   possible. If your test absolutely has to handle the error of some function
 *   the customary naming pattern is to prefix those variants with __. Try to
 *   restrict explicit error handling to leaf functions. For the main test flow
 *   simply pass the expected error condition down into your helper code, which
 *   results in tidy and declarative test logic.
 *
 * - Make your library functions as simple to use as possible. Automatically
 *   register cleanup handlers through igt_install_exit_handler(). Reduce the
 *   amount of setup boilerplate needed by using implicit singletons and lazy
 *   structure initialization and similar design patterns.
 *
 * - Don't shy away from refactoring common code, even when there are just 2-3
 *   users and even if it's not a net reduction in code. As long as it helps to
 *   remove boilerplate and makes the code more declarative the resulting
 *   clearer test flow is worth it. All i-g-t library code has been organically
 *   extracted from testcases in this fashion.
 *
 * - For general coding style issues please follow the kernel's rules laid out
 *   in
 *   [CodingStyle](https://www.kernel.org/doc/Documentation/CodingStyle).
197 198 199 200 201
 *
 * # Interface with Testrunners
 *
 * i-g-t testcase are all executables which should be run as root on an
 * otherwise completely idle system. The test status is reflected in the
202 203 204 205
 * exitcode. #IGT_EXIT_SUCCESS means "success", #IGT_EXIT_SKIP "skip",
 * #IGT_EXIT_TIMEOUT that some operation "timed out".  All other exit codes
 * encode a failed test result, including any abnormal termination of the test
 * (e.g. by SIGKILL).
206 207 208 209 210 211 212 213 214 215 216
 *
 * On top of that tests may report unexpected results and minor issues to
 * stderr. If stderr is non-empty the test result should be treated as "warn".
 *
 * The test lists are generated at build time. Simple testcases are listed in
 * tests/single-tests.txt and tests with subtests are listed in
 * tests/multi-tests.txt. When running tests with subtest from a test runner it
 * is recommend to run each subtest individually, since otherwise the return
 * code will only reflect the overall result.
 *
 * To do that obtain the lists of subtests with "--list-subtests", which can be
217 218 219 220
 * run as non-root and doesn't require a DRM driver to be loaded (or any GPU to
 * be present). Then individual subtests can be run with "--run-subtest". Usage
 * help for tests with subtests can be obtained with the "--help" command line
 * option.
221 222 223 224 225 226 227 228 229 230 231 232 233
 *
 * A wildcard expression can be given to --run-subtest to specify a subset of
 * subtests to run. See https://tools.ietf.org/html/rfc3977#section-4 for a
 * description of allowed wildcard expressions.
 * Some examples of allowed wildcard expressions are:
 *
 * - '*basic*' match any subtest containing basic
 * - 'basic-???' match any subtest named basic- with 3 characters after -
 * - 'basic-[0-9]' match any subtest named basic- with a single number after -
 * - 'basic-[^0-9]' match any subtest named basic- with a single non numerical character after -
 * - 'basic*,advanced*' match any subtest starting basic or advanced
 * - '*,!basic*' match any subtest not starting basic
 * - 'basic*,!basic-render*' match any subtest starting basic but not starting basic-render
234 235 236 237 238
 *
 * # Configuration
 *
 * Some of IGT's behavior can be configured through a configuration file.
 * By default, this file is expected to exist in ~/.igtrc . The directory for
Gwan-gyeong Mun's avatar
Gwan-gyeong Mun committed
239
 * this can be overridden by setting the environment variable %IGT_CONFIG_PATH.
240 241 242
 * An example configuration follows:
 *
 * |[<!-- language="plain" -->
243
 *	&num; The common configuration section follows.
244 245 246
 *	[Common]
 *	FrameDumpPath=/tmp # The path to dump frames that fail comparison checks
 *
247 248
 *	&num; The following section is used for configuring the Device Under Test.
 *	&num; It is not mandatory and allows overriding default values.
249 250 251 252 253 254
 *	[DUT]
 *	SuspendResumeDelay=10
 * ]|
 *
 * Some specific configuration options may be used by specific parts of IGT,
 * such as those related to Chamelium support.
Daniel Vetter's avatar
Daniel Vetter committed
255 256 257
 */

static unsigned int exit_handler_count;
258
const char *igt_interactive_debug;
Daniel Vetter's avatar
Daniel Vetter committed
259 260 261 262

/* subtests helpers */
static bool list_subtests = false;
static char *run_single_subtest = NULL;
263
static bool run_single_subtest_found = false;
Daniel Vetter's avatar
Daniel Vetter committed
264
static const char *in_subtest = NULL;
265
static struct timespec subtest_time;
266
static clockid_t igt_clock = (clockid_t)-1;
Daniel Vetter's avatar
Daniel Vetter committed
267 268
static bool in_fixture = false;
static bool test_with_subtests = false;
269
static bool in_atexit_handler = false;
Daniel Vetter's avatar
Daniel Vetter committed
270 271 272 273
static enum {
	CONT = 0, SKIP, FAIL
} skip_subtests_henceforth = CONT;

274 275
bool __igt_plain_output = false;

Daniel Vetter's avatar
Daniel Vetter committed
276 277 278 279 280 281
/* fork support state */
pid_t *test_children;
int num_test_children;
int test_children_sz;
bool test_child;

282 283 284
enum {
 OPT_LIST_SUBTESTS,
 OPT_RUN_SUBTEST,
285
 OPT_DESCRIPTION,
286
 OPT_DEBUG,
287
 OPT_INTERACTIVE_DEBUG,
288 289 290
 OPT_HELP = 'h'
};

291 292 293
static int igt_exitcode = IGT_EXIT_SUCCESS;
static const char *command_str;

294
static char* igt_log_domain_filter;
295 296 297 298 299 300
static struct {
	char *entries[256];
	uint8_t start, end;
} log_buffer;
static pthread_mutex_t log_buffer_mutex = PTHREAD_MUTEX_INITIALIZER;

301
GKeyFile *igt_key_file;
302

303
char *igt_frame_dump_path;
304

305 306
static bool stderr_needs_sentinel = false;

307 308 309 310 311
const char *igt_test_name(void)
{
	return command_str;
}

312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
static void _igt_log_buffer_append(char *line)
{
	pthread_mutex_lock(&log_buffer_mutex);

	free(log_buffer.entries[log_buffer.end]);
	log_buffer.entries[log_buffer.end] = line;
	log_buffer.end++;
	if (log_buffer.end == log_buffer.start)
		log_buffer.start++;

	pthread_mutex_unlock(&log_buffer_mutex);
}

static void _igt_log_buffer_reset(void)
{
	pthread_mutex_lock(&log_buffer_mutex);

	log_buffer.start = log_buffer.end = 0;

	pthread_mutex_unlock(&log_buffer_mutex);
}

334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
static void _igt_log_buffer_dump(void)
{
	uint8_t i;

	if (in_subtest)
		fprintf(stderr, "Subtest %s failed.\n", in_subtest);
	else
		fprintf(stderr, "Test %s failed.\n", command_str);

	if (log_buffer.start == log_buffer.end) {
		fprintf(stderr, "No log.\n");
		return;
	}

	pthread_mutex_lock(&log_buffer_mutex);
349
	fprintf(stderr, "**** DEBUG ****\n");
350 351 352 353

	i = log_buffer.start;
	do {
		char *last_line = log_buffer.entries[i];
354
		fprintf(stderr, "%s", last_line);
355 356 357 358 359
		i++;
	} while (i != log_buffer.start && i != log_buffer.end);

	/* reset the buffer */
	log_buffer.start = log_buffer.end = 0;
360

361
	fprintf(stderr, "****  END  ****\n");
362 363
	pthread_mutex_unlock(&log_buffer_mutex);
}
364

365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
/**
 * igt_log_buffer_inspect:
 *
 * Provides a way to replay the internal igt log buffer for inspection.
 * @check: A user-specified handler that gets invoked for each line of
 *         the log buffer. The handler should return true to stop
 *         inspecting the rest of the buffer.
 * @data: passed as a user argument to the inspection function.
 */
void igt_log_buffer_inspect(igt_buffer_log_handler_t check, void *data)
{
	uint8_t i;
	pthread_mutex_lock(&log_buffer_mutex);

	i = log_buffer.start;
	do {
		if (check(log_buffer.entries[i], data))
			break;
		i++;
	} while (i != log_buffer.start && i != log_buffer.end);

	pthread_mutex_unlock(&log_buffer_mutex);
}

Chris Wilson's avatar
Chris Wilson committed
389
void igt_kmsg(const char *format, ...)
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
{
	va_list ap;
	FILE *file;

	file = fopen("/dev/kmsg", "w");
	if (file == NULL)
		return;

	va_start(ap, format);
	vfprintf(file, format, ap);
	va_end(ap);

	fclose(file);
}

405 406
#define time_valid(ts) ((ts)->tv_sec || (ts)->tv_nsec)

407 408
double igt_time_elapsed(struct timespec *then,
			struct timespec *now)
409 410 411 412 413 414 415 416 417 418 419
{
	double elapsed = -1.;

	if (time_valid(then) && time_valid(now)) {
		elapsed = now->tv_sec - then->tv_sec;
		elapsed += (now->tv_nsec - then->tv_nsec) * 1e-9;
	}

	return elapsed;
}

420
int igt_gettime(struct timespec *ts)
421 422
{
	memset(ts, 0, sizeof(*ts));
423
	errno = 0;
424

425 426 427 428 429 430 431 432 433 434 435
	/* Stay on the same clock for consistency. */
	if (igt_clock != (clockid_t)-1) {
		if (clock_gettime(igt_clock, ts))
			goto error;
		return 0;
	}

#ifdef CLOCK_MONOTONIC_RAW
	if (!clock_gettime(igt_clock = CLOCK_MONOTONIC_RAW, ts))
		return 0;
#endif
436
#ifdef CLOCK_MONOTONIC_COARSE
437 438
	if (!clock_gettime(igt_clock = CLOCK_MONOTONIC_COARSE, ts))
		return 0;
439
#endif
440 441 442 443 444 445 446
	if (!clock_gettime(igt_clock = CLOCK_MONOTONIC, ts))
		return 0;
error:
	igt_warn("Could not read monotonic time: %s\n",
		 strerror(errno));

	return -errno;
447 448
}

449 450 451 452
uint64_t igt_nsec_elapsed(struct timespec *start)
{
	struct timespec now;

453
	igt_gettime(&now);
454 455 456 457 458 459
	if ((start->tv_sec | start->tv_nsec) == 0) {
		*start = now;
		return 0;
	}

	return ((now.tv_nsec - start->tv_nsec) +
460
		(uint64_t)NSEC_PER_SEC*(now.tv_sec - start->tv_sec));
461 462
}

Daniel Vetter's avatar
Daniel Vetter committed
463 464 465
bool __igt_fixture(void)
{
	assert(!in_fixture);
466
	assert(test_with_subtests);
Daniel Vetter's avatar
Daniel Vetter committed
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489

	if (igt_only_list_subtests())
		return false;

	if (skip_subtests_henceforth)
		return false;

	in_fixture = true;
	return true;
}

void __igt_fixture_complete(void)
{
	assert(in_fixture);

	in_fixture = false;
}

void __igt_fixture_end(void)
{
	assert(in_fixture);

	in_fixture = false;
490
	siglongjmp(igt_subtest_jmpbuf, 1);
Daniel Vetter's avatar
Daniel Vetter committed
491 492
}

493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
/*
 * If the test takes out the machine, in addition to the usual dmesg
 * spam, the kernel may also emit a "death rattle" -- extra debug
 * information that is overkill for normal successful tests, but
 * vital for post-mortem analysis.
 */
static void ftrace_dump_on_oops(bool enable)
{
	int fd;

	fd = open("/proc/sys/kernel/ftrace_dump_on_oops", O_WRONLY);
	if (fd < 0)
		return;

	/*
	 * If we fail, we do not get the death rattle we wish, but we
	 * still want to run the tests anyway.
	 */
	igt_ignore_warn(write(fd, enable ? "1\n" : "0\n", 2));
	close(fd);
}

Daniel Vetter's avatar
Daniel Vetter committed
515
bool igt_exit_called;
516
static void common_exit_handler(int sig)
Daniel Vetter's avatar
Daniel Vetter committed
517
{
518
	if (!igt_only_list_subtests()) {
519
		bind_fbcon(true);
520
	}
521

Daniel Vetter's avatar
Daniel Vetter committed
522 523 524 525 526
	/* When not killed by a signal check that igt_exit() has been properly
	 * called. */
	assert(sig != 0 || igt_exit_called);
}

527 528 529 530 531 532
static void print_test_description(void)
{
	if (&__igt_test_description)
		printf("%s\n", __igt_test_description);
}

Daniel Vetter's avatar
Daniel Vetter committed
533 534 535 536 537 538 539 540 541
static void print_version(void)
{
	struct utsname uts;

	if (list_subtests)
		return;

	uname(&uts);

542 543 544
	igt_info("IGT-Version: %s-%s (%s) (%s: %s %s)\n", PACKAGE_VERSION,
		 IGT_GIT_SHA1, TARGET_CPU_PLATFORM,
		 uts.sysname, uts.release, uts.machine);
Daniel Vetter's avatar
Daniel Vetter committed
545 546
}

547
static void print_usage(const char *help_str, bool output_on_stderr)
Daniel Vetter's avatar
Daniel Vetter committed
548 549 550
{
	FILE *f = output_on_stderr ? stderr : stdout;

551 552
	fprintf(f, "Usage: %s [OPTIONS]\n", command_str);
	fprintf(f, "  --list-subtests\n"
553
		   "  --run-subtest <pattern>\n"
554
		   "  --debug[=log-domain]\n"
555
		   "  --interactive-debug[=domain]\n"
556 557
		   "  --help-description\n"
		   "  --help\n");
Daniel Vetter's avatar
Daniel Vetter committed
558 559 560 561
	if (help_str)
		fprintf(f, "%s\n", help_str);
}

562

Daniel Vetter's avatar
Daniel Vetter committed
563 564 565 566 567 568 569 570
static void oom_adjust_for_doom(void)
{
	int fd;
	const char always_kill[] = "1000";

	fd = open("/proc/self/oom_score_adj", O_WRONLY);
	igt_assert(fd != -1);
	igt_assert(write(fd, always_kill, sizeof(always_kill)) == sizeof(always_kill));
571 572
	close(fd);

Daniel Vetter's avatar
Daniel Vetter committed
573 574
}

575
static void common_init_config(void)
576
{
577 578
	char *key_file_env = NULL;
	char *key_file_loc = NULL;
579
	GError *error = NULL;
580
	int ret;
581

582 583 584 585 586 587 588 589 590 591 592 593 594
	/* Determine igt config path */
	key_file_env = getenv("IGT_CONFIG_PATH");
	if (key_file_env) {
		key_file_loc = key_file_env;
	} else {
		key_file_loc = malloc(100);
		snprintf(key_file_loc, 100, "%s/.igtrc", g_get_home_dir());
	}

	/* Load igt config file */
	igt_key_file = g_key_file_new();
	ret = g_key_file_load_from_file(igt_key_file, key_file_loc,
					G_KEY_FILE_NONE, &error);
595
	if (!ret) {
596 597 598 599 600 601 602 603
		g_error_free(error);
		g_key_file_free(igt_key_file);
		igt_key_file = NULL;

		goto out;
	}

	g_clear_error(&error);
604

605 606 607 608
	if (!igt_frame_dump_path)
		igt_frame_dump_path =
			g_key_file_get_string(igt_key_file, "Common",
					      "FrameDumpPath", &error);
609

610 611
	g_clear_error(&error);

612 613 614
	ret = g_key_file_get_integer(igt_key_file, "DUT", "SuspendResumeDelay",
				     &error);
	assert(!error || error->code != G_KEY_FILE_ERROR_INVALID_VALUE);
615 616

	g_clear_error(&error);
617

618 619
	if (ret != 0)
		igt_set_autoresume_delay(ret);
620

621 622 623
out:
	if (!key_file_env && key_file_loc)
		free(key_file_loc);
624 625
}

626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
static void common_init_env(void)
{
	const char *env;

	if (!isatty(STDOUT_FILENO) || getenv("IGT_PLAIN_OUTPUT"))
		__igt_plain_output = true;

	if (!__igt_plain_output)
		setlocale(LC_ALL, "");

	env = getenv("IGT_LOG_LEVEL");
	if (env) {
		if (strcmp(env, "debug") == 0)
			igt_log_level = IGT_LOG_DEBUG;
		else if (strcmp(env, "info") == 0)
			igt_log_level = IGT_LOG_INFO;
		else if (strcmp(env, "warn") == 0)
			igt_log_level = IGT_LOG_WARN;
		else if (strcmp(env, "none") == 0)
			igt_log_level = IGT_LOG_NONE;
	}

648
	igt_frame_dump_path = getenv("IGT_FRAME_DUMP_PATH");
649 650

	stderr_needs_sentinel = getenv("IGT_SENTINEL_ON_STDERR") != NULL;
651 652 653 654 655

	env = getenv("IGT_FORCE_DRIVER");
	if (env) {
		__set_forced_driver(env);
	}
656 657
}

658
static int common_init(int *argc, char **argv,
659
		       const char *extra_short_opts,
660
		       const struct option *extra_long_opts,
661
		       const char *help_str,
662 663
		       igt_opt_handler_t extra_opt_handler,
		       void *handler_data)
Daniel Vetter's avatar
Daniel Vetter committed
664
{
665
	int c, option_index = 0, i, x;
Daniel Vetter's avatar
Daniel Vetter committed
666
	static struct option long_options[] = {
667 668
		{"list-subtests", 0, 0, OPT_LIST_SUBTESTS},
		{"run-subtest", 1, 0, OPT_RUN_SUBTEST},
669
		{"help-description", 0, 0, OPT_DESCRIPTION},
670
		{"debug", optional_argument, 0, OPT_DEBUG},
671
		{"interactive-debug", optional_argument, 0, OPT_INTERACTIVE_DEBUG},
672
		{"help", 0, 0, OPT_HELP},
673
		{0, 0, 0, 0}
Daniel Vetter's avatar
Daniel Vetter committed
674 675
	};
	char *short_opts;
676
	const char *std_short_opts = "h";
Daniel Vetter's avatar
Daniel Vetter committed
677 678 679 680
	struct option *combined_opts;
	int extra_opt_count;
	int all_opt_count;
	int ret = 0;
681

682
	common_init_env();
Daniel Vetter's avatar
Daniel Vetter committed
683 684 685 686 687 688 689

	command_str = argv[0];
	if (strrchr(command_str, '/'))
		command_str = strrchr(command_str, '/') + 1;

	/* First calculate space for all passed-in extra long options */
	all_opt_count = 0;
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
	while (extra_long_opts && extra_long_opts[all_opt_count].name) {

		/* check for conflicts with standard long option values */
		for (i = 0; long_options[i].name; i++)
			if (extra_long_opts[all_opt_count].val == long_options[i].val)
				igt_warn("Conflicting long option values between --%s and --%s\n",
					 extra_long_opts[all_opt_count].name,
					 long_options[i].name);

		/* check for conflicts with short options */
		if (extra_long_opts[all_opt_count].val != ':'
		    && strchr(std_short_opts, extra_long_opts[all_opt_count].val)) {
			igt_warn("Conflicting long and short option values between --%s and -%s\n",
				 extra_long_opts[all_opt_count].name,
				 long_options[i].name);
		}


Daniel Vetter's avatar
Daniel Vetter committed
708
		all_opt_count++;
709
	}
Daniel Vetter's avatar
Daniel Vetter committed
710 711
	extra_opt_count = all_opt_count;

712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
	/* check for conflicts in extra short options*/
	for (i = 0; extra_short_opts && extra_short_opts[i]; i++) {

		if (extra_short_opts[i] == ':')
			continue;

		/* check for conflicts with standard short options */
		if (strchr(std_short_opts, extra_short_opts[i]))
			igt_warn("Conflicting short option: -%c\n", std_short_opts[i]);

		/* check for conflicts with standard long option values */
		for (x = 0; long_options[x].name; x++)
			if (long_options[x].val == extra_short_opts[i])
				igt_warn("Conflicting short option and long option value: --%s and -%c\n",
					 long_options[x].name, extra_short_opts[i]);
	}

Daniel Vetter's avatar
Daniel Vetter committed
729 730 731
	all_opt_count += ARRAY_SIZE(long_options);

	combined_opts = malloc(all_opt_count * sizeof(*combined_opts));
732 733 734
	if (extra_opt_count > 0)
		memcpy(combined_opts, extra_long_opts,
		       extra_opt_count * sizeof(*combined_opts));
Daniel Vetter's avatar
Daniel Vetter committed
735 736 737 738 739

	/* Copy the subtest long options (and the final NULL entry) */
	memcpy(&combined_opts[extra_opt_count], long_options,
		ARRAY_SIZE(long_options) * sizeof(*combined_opts));

740 741 742
	ret = asprintf(&short_opts, "%s%s",
		       extra_short_opts ? extra_short_opts : "",
		       std_short_opts);
Daniel Vetter's avatar
Daniel Vetter committed
743 744
	assert(ret >= 0);

745
	while ((c = getopt_long(*argc, argv, short_opts, combined_opts,
Daniel Vetter's avatar
Daniel Vetter committed
746 747
			       &option_index)) != -1) {
		switch(c) {
748 749 750 751 752 753
		case OPT_INTERACTIVE_DEBUG:
			if (optarg && strlen(optarg) > 0)
				igt_interactive_debug = strdup(optarg);
			else
				igt_interactive_debug = "all";
			break;
754
		case OPT_DEBUG:
755
			igt_log_level = IGT_LOG_DEBUG;
756 757
			if (optarg && strlen(optarg) > 0)
				igt_log_domain_filter = strdup(optarg);
758
			break;
759
		case OPT_LIST_SUBTESTS:
Daniel Vetter's avatar
Daniel Vetter committed
760 761 762
			if (!run_single_subtest)
				list_subtests = true;
			break;
763
		case OPT_RUN_SUBTEST:
764
			assert(optarg);
Daniel Vetter's avatar
Daniel Vetter committed
765 766 767
			if (!list_subtests)
				run_single_subtest = strdup(optarg);
			break;
768 769 770 771
		case OPT_DESCRIPTION:
			print_test_description();
			ret = -1;
			goto out;
772
		case OPT_HELP:
773
			print_usage(help_str, false);
Daniel Vetter's avatar
Daniel Vetter committed
774 775 776
			ret = -1;
			goto out;
		case '?':
777
			print_usage(help_str, true);
778 779
			ret = -2;
			goto out;
Daniel Vetter's avatar
Daniel Vetter committed
780
		default:
781
			ret = extra_opt_handler(c, option_index, handler_data);
Daniel Vetter's avatar
Daniel Vetter committed
782 783 784 785 786
			if (ret)
				goto out;
		}
	}

787
	common_init_config();
788

Daniel Vetter's avatar
Daniel Vetter committed
789 790 791
out:
	free(short_opts);
	free(combined_opts);
792 793 794 795 796 797

	/* exit immediately if this test has no subtests and a subtest or the
	 * list of subtests has been requested */
	if (!test_with_subtests) {
		if (run_single_subtest) {
			igt_warn("Unknown subtest: %s\n", run_single_subtest);
798
			exit(IGT_EXIT_INVALID);
799 800
		}
		if (list_subtests)
801
			exit(IGT_EXIT_INVALID);
802 803 804 805
	}

	if (ret < 0)
		/* exit with no error for -h/--help */
806
		exit(ret == -1 ? 0 : IGT_EXIT_INVALID);
807

808
	if (!list_subtests) {
809
		bind_fbcon(false);
Chris Wilson's avatar
Chris Wilson committed
810
		igt_kmsg(KMSG_INFO "%s: executing\n", command_str);
811 812
		print_version();

813
		sync();
814
		oom_adjust_for_doom();
815
		ftrace_dump_on_oops(true);
816
	}
Daniel Vetter's avatar
Daniel Vetter committed
817

818 819 820
	/* install exit handler, to ensure we clean up */
	igt_install_exit_handler(common_exit_handler);

821
	if (!test_with_subtests)
822
		igt_gettime(&subtest_time);
823

824 825 826 827 828
	for (i = 0; (optind + i) < *argc; i++)
		argv[i + 1] = argv[optind + i];

	*argc = *argc - optind + 1;

Daniel Vetter's avatar
Daniel Vetter committed
829 830 831 832
	return ret;
}


833 834 835 836 837 838 839 840
/**
 * igt_subtest_init_parse_opts:
 * @argc: argc from the test's main()
 * @argv: argv from the test's main()
 * @extra_short_opts: getopt_long() compliant list with additional short options
 * @extra_long_opts: getopt_long() compliant list with additional long options
 * @help_str: help string for the additional options
 * @extra_opt_handler: handler for the additional options
841
 * @handler_data: user data given to @extra_opt_handler when invoked
842
 *
843
 * This function handles the subtest related command line options and allows an
844 845 846 847 848 849 850 851 852
 * arbitrary set of additional options. This is useful for tests which have
 * additional knobs to tune when run manually like the number of rounds execute
 * or the size of the allocated buffer objects.
 *
 * Tests without special needs should just use igt_subtest_init() or use
 * #igt_main directly instead of their own main() function.
 *
 * Returns: Forwards any option parsing errors from getopt_long.
 */
853
int igt_subtest_init_parse_opts(int *argc, char **argv,
854
				const char *extra_short_opts,
855
				const struct option *extra_long_opts,
856
				const char *help_str,
857 858
				igt_opt_handler_t extra_opt_handler,
				void *handler_data)
Daniel Vetter's avatar
Daniel Vetter committed
859
{
860
	int ret;
Daniel Vetter's avatar
Daniel Vetter committed
861

862 863
	test_with_subtests = true;
	ret = common_init(argc, argv, extra_short_opts, extra_long_opts,
864
			  help_str, extra_opt_handler, handler_data);
Daniel Vetter's avatar
Daniel Vetter committed
865

866
	return ret;
Daniel Vetter's avatar
Daniel Vetter committed
867 868
}

869 870
enum igt_log_level igt_log_level = IGT_LOG_INFO;

871 872 873 874 875 876 877 878
/**
 * igt_simple_init_parse_opts:
 * @argc: argc from the test's main()
 * @argv: argv from the test's main()
 * @extra_short_opts: getopt_long() compliant list with additional short options
 * @extra_long_opts: getopt_long() compliant list with additional long options
 * @help_str: help string for the additional options
 * @extra_opt_handler: handler for the additional options
879
 * @handler_data: user data given to @extra_opt_handler when invoked
880 881 882 883
 *
 * This initializes a simple test without any support for subtests and allows
 * an arbitrary set of additional options.
 */
884
void igt_simple_init_parse_opts(int *argc, char **argv,
885
				const char *extra_short_opts,
886
				const struct option *extra_long_opts,
887
				const char *help_str,
888 889
				igt_opt_handler_t extra_opt_handler,
				void *handler_data)
890 891
{
	common_init(argc, argv, extra_short_opts, extra_long_opts, help_str,
892
		    extra_opt_handler, handler_data);
893 894
}

Daniel Vetter's avatar
Daniel Vetter committed
895 896 897 898 899 900 901
/*
 * Note: Testcases which use these helpers MUST NOT output anything to stdout
 * outside of places protected by igt_run_subtest checks - the piglit
 * runner adds every line to the subtest list.
 */
bool __igt_run_subtest(const char *subtest_name)
{
902 903
	int i;

Daniel Vetter's avatar
Daniel Vetter committed
904 905
	assert(!in_subtest);
	assert(!in_fixture);
906
	assert(test_with_subtests);
Daniel Vetter's avatar
Daniel Vetter committed
907

908 909 910 911 912 913 914 915 916
	/* check the subtest name only contains a-z, A-Z, 0-9, '-' and '_' */
	for (i = 0; subtest_name[i] != '\0'; i++)
		if (subtest_name[i] != '_' && subtest_name[i] != '-'
		    && !isalnum(subtest_name[i])) {
			igt_critical("Invalid subtest name \"%s\".\n",
				     subtest_name);
			igt_exit();
		}

Daniel Vetter's avatar
Daniel Vetter committed
917 918 919 920 921
	if (list_subtests) {
		printf("%s\n", subtest_name);
		return false;
	}

922
	if (run_single_subtest) {
923
		if (uwildmat(subtest_name, run_single_subtest) == 0)
924 925 926 927 928
			return false;
		else
			run_single_subtest_found = true;
	}

Daniel Vetter's avatar
Daniel Vetter committed
929
	if (skip_subtests_henceforth) {
930
		printf("%sSubtest %s: %s%s\n",
931
		       (!__igt_plain_output) ? "\x1b[1m" : "", subtest_name,
Daniel Vetter's avatar
Daniel Vetter committed
932
		       skip_subtests_henceforth == SKIP ?
933
		       "SKIP" : "FAIL", (!__igt_plain_output) ? "\x1b[0m" : "");
934 935 936 937 938
		fflush(stdout);
		if (stderr_needs_sentinel)
			fprintf(stderr, "Subtest %s: %s\n", subtest_name,
				skip_subtests_henceforth == SKIP ?
				"SKIP" : "FAIL");
Daniel Vetter's avatar
Daniel Vetter committed
939 940 941
		return false;
	}

Chris Wilson's avatar
Chris Wilson committed
942 943
	igt_kmsg(KMSG_INFO "%s: starting subtest %s\n",
		 command_str, subtest_name);
944 945 946 947
	igt_info("Starting subtest: %s\n", subtest_name);
	fflush(stdout);
	if (stderr_needs_sentinel)
		fprintf(stderr, "Starting subtest: %s\n", subtest_name);
948

949 950
	_igt_log_buffer_reset();

951
	igt_gettime(&subtest_time);
Daniel Vetter's avatar
Daniel Vetter committed
952 953 954
	return (in_subtest = subtest_name);
}

955 956 957 958 959 960
/**
 * igt_subtest_name:
 *
 * Returns: The name of the currently executed subtest or NULL if called from
 * outside a subtest block.
 */
Daniel Vetter's avatar
Daniel Vetter committed
961 962 963 964 965
const char *igt_subtest_name(void)
{
	return in_subtest;
}

966 967 968 969 970 971
/**
 * igt_only_list_subtests:
 *
 * Returns: Returns true if only subtest should be listed and any setup code
 * must be skipped, false otherwise.
 */
Daniel Vetter's avatar
Daniel Vetter committed
972 973 974 975 976
bool igt_only_list_subtests(void)
{
	return list_subtests;
}

977 978
void __igt_subtest_group_save(int *save)
{
979 980
	assert(test_with_subtests);

981 982 983 984 985 986 987 988
	*save = skip_subtests_henceforth;
}

void __igt_subtest_group_restore(int save)
{
	skip_subtests_henceforth = save;
}

Daniel Vetter's avatar
Daniel Vetter committed
989 990 991 992 993 994 995
static bool skipped_one = false;
static bool succeeded_one = false;
static bool failed_one = false;

static void exit_subtest(const char *) __attribute__((noreturn));
static void exit_subtest(const char *result)
{
996 997
	struct timespec now;

998
	igt_gettime(&now);
999 1000
	igt_info("%sSubtest %s: %s (%.3fs)%s\n",
		 (!__igt_plain_output) ? "\x1b[1m" : "",
1001
		 in_subtest, result, igt_time_elapsed(&subtest_time, &now),
1002
		 (!__igt_plain_output) ? "\x1b[0m" : "");
1003
	fflush(stdout);
1004 1005
	if (stderr_needs_sentinel)
		fprintf(stderr, "Subtest %s: %s (%.3fs)\n",
1006
			in_subtest, result, igt_time_elapsed(&subtest_time, &now));
1007

1008 1009
	igt_terminate_spin_batches();

Daniel Vetter's avatar
Daniel Vetter committed
1010
	in_subtest = NULL;
1011
	siglongjmp(igt_subtest_jmpbuf, 1);
Daniel Vetter's avatar
Daniel Vetter committed
1012 1013
}

1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
/**
 * igt_skip:
 * @f: format string
 * @...: optional arguments used in the format string
 *
 * Subtest aware test skipping. The format string is printed to stderr as the
 * reason why the test skipped.
 *
 * For tests with subtests this will either bail out of the current subtest or
 * mark all subsequent subtests as SKIP (presuming some global setup code
 * failed).
 *
 * For normal tests without subtest it will directly exit.
 */
Daniel Vetter's avatar
Daniel Vetter committed
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
void igt_skip(const char *f, ...)
{
	va_list args;
	skipped_one = true;

	assert(!test_child);

	if (!igt_only_list_subtests()) {
		va_start(args, f);
		vprintf(f, args);
		va_end(args);
	}

	if (in_subtest) {
		exit_subtest("SKIP");
	} else if (test_with_subtests) {
		skip_subtests_henceforth = SKIP;
		assert(in_fixture);
		__igt_fixture_end();
	} else {
1048 1049
		igt_exitcode = IGT_EXIT_SKIP;
		igt_exit();
Daniel Vetter's avatar
Daniel Vetter committed
1050 1051 1052 1053 1054 1055 1056 1057 1058
	}
}

void __igt_skip_check(const char *file, const int line,
		      const char *func, const char *check,
		      const char *f, ...)
{
	va_list args;
	int err = errno;
1059 1060 1061
	char *err_str = NULL;

	if (err)
1062 1063
		igt_assert_neq(asprintf(&err_str, "Last errno: %i, %s\n", err, strerror(err)),
			       -1);
Daniel Vetter's avatar
Daniel Vetter committed
1064 1065 1066 1067 1068 1069 1070 1071 1072

	if (f) {
		static char *buf;

		/* igt_skip never returns, so try to not leak too badly. */
		if (buf)
			free(buf);

		va_start(args, f);
1073
		igt_assert_neq(vasprintf(&buf, f, args), -1);
Daniel Vetter's avatar
Daniel Vetter committed
1074 1075 1076
		va_end(args);

		igt_skip("Test requirement not met in function %s, file %s:%i:\n"
1077
			 "Test requirement: %s\n%s"
1078 1079
			 "%s",
			 func, file, line, check, buf, err_str ?: "");
Daniel Vetter's avatar
Daniel Vetter committed
1080 1081
	} else {
		igt_skip("Test requirement not met in function %s, file %s:%i:\n"
1082
			 "Test requirement: %s\n"
1083 1084
			 "%s",
			 func, file, line, check, err_str ?: "");
Daniel Vetter's avatar
Daniel Vetter committed
1085 1086 1087
	}
}

1088 1089 1090
/**
 * igt_success:
 *
1091
 * Complete a (subtest) as successful
1092 1093 1094 1095
 *
 * This bails out of a subtests and marks it as successful. For global tests it
 * it won't bail out of anything.
 */
Daniel Vetter's avatar
Daniel Vetter committed
1096 1097 1098 1099 1100 1101 1102
void igt_success(void)
{
	succeeded_one = true;
	if (in_subtest)
		exit_subtest("SUCCESS");
}

1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
/**
 * igt_fail:
 * @exitcode: exitcode
 *
 * Fail a testcase. The exitcode is used as the exit code of the test process.
 * It may not be 0 (which indicates success) or 77 (which indicates a skipped
 * test).
 *
 * For tests with subtests this will either bail out of the current subtest or
 * mark all subsequent subtests as FAIL (presuming some global setup code
 * failed).
 *
 * For normal tests without subtest it will directly exit with the given
 * exitcode.
 */
Daniel Vetter's avatar
Daniel Vetter committed
1118 1119
void igt_fail(int exitcode)
{
1120
	assert(exitcode != IGT_EXIT_SUCCESS && exitcode != IGT_EXIT_SKIP);
Daniel Vetter's avatar
Daniel Vetter committed
1121

1122 1123
	igt_debug_wait_for_keypress("failure");

1124 1125 1126 1127 1128
	/* Exit immediately if the test is already exiting and igt_fail is
	 * called. This can happen if an igt_assert fails in an exit handler */
	if (in_atexit_handler)
		_exit(IGT_EXIT_FAILURE);

Daniel Vetter's avatar
Daniel Vetter committed
1129 1130 1131 1132 1133 1134 1135 1136 1137
	if (!failed_one)
		igt_exitcode = exitcode;

	failed_one = true;

	/* Silent exit, parent will do the yelling. */
	if (test_child)
		exit(exitcode);

1138 1139
	_igt_log_buffer_dump();

Thomas Wood's avatar
Thomas Wood committed
1140
	if (in_subtest) {
1141
		exit_subtest("FAIL");
Thomas Wood's avatar
Thomas Wood committed
1142
	} else {
Daniel Vetter's avatar
Daniel Vetter committed
1143
		assert(igt_can_fail());
Daniel Vetter's avatar
Daniel Vetter committed
1144 1145 1146 1147 1148 1149

		if (in_fixture) {
			skip_subtests_henceforth = FAIL;
			__igt_fixture_end();
		}

1150
		igt_exit();
Daniel Vetter's avatar
Daniel Vetter committed
1151 1152 1153
	}
}

1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
/**
 * igt_fatal_error: Stop test execution on fatal errors
 *
 * Stop test execution or optionally, if the IGT_REBOOT_ON_FATAL_ERROR
 * environment variable is set, reboot the machine.
 *
 * Since out test runner (piglit) does support fatal test exit codes, we
 * implement the default behaviour by waiting endlessly.
 */
void  __attribute__((noreturn)) igt_fatal_error(void)
{
	if (igt_check_boolean_env_var("IGT_REBOOT_ON_FATAL_ERROR", false)) {
		igt_warn("FATAL ERROR - REBOOTING\n");
		igt_sysrq_reboot();
	} else {
		igt_warn("FATAL ERROR\n");
		for (;;)
			pause();
	}
}


Daniel Vetter's avatar
Daniel Vetter committed
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
/**
 * igt_can_fail:
 *
 * Returns true if called from either an #igt_fixture, #igt_subtest or a
 * testcase without subtests, i.e. #igt_simple_main. Returns false otherwise. In
 * other words, it checks whether it's legal to call igt_fail(), igt_skip_on()
 * and all the convenience macros build around those.
 *
 * This is useful to make sure that library code is called from the right
 * places.
 */
bool igt_can_fail(void)
{
	return !test_with_subtests || in_fixture || in_subtest;
}

1192
static bool running_under_gdb(void)
Daniel Vetter's avatar
Daniel Vetter committed
1193
{
1194
	char pathname[30], buf[1024];
1195
	ssize_t len;
Daniel Vetter's avatar
Daniel Vetter committed
1196

1197
	sprintf(pathname, "/proc/%d/exe", getppid());
1198 1199 1200 1201 1202 1203 1204
	len = readlink(pathname, buf, sizeof(buf) - 1);
	if (len < 0)
		return false;

	buf[len] = '\0';

	return strncmp(basename(buf), "gdb", 3) == 0;
Daniel Vetter's avatar
Daniel Vetter committed
1205 1206
}

1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
static void __write_stderr(const char *str, size_t len)
{
	igt_ignore_warn(write(STDERR_FILENO, str, len));
}

static void write_stderr(const char *str)
{
	__write_stderr(str, strlen(str));
}

1217 1218 1219 1220 1221 1222
static void print_backtrace(void)
{
	unw_cursor_t cursor;
	unw_context_t uc;
	int stack_num = 0;

1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
	Dwfl_Callbacks cbs = {
		.find_elf = dwfl_linux_proc_find_elf,
		.find_debuginfo = dwfl_standard_find_debuginfo,
	};

	Dwfl *dwfl = dwfl_begin(&cbs);

	if (dwfl_linux_proc_report(dwfl, getpid())) {
		dwfl_end(dwfl);
		dwfl = NULL;
	} else
		dwfl_report_end(dwfl, NULL, NULL);

1236
	igt_info("Stack trace:\n");
1237 1238 1239 1240 1241

	unw_getcontext(&uc);
	unw_init_local(&cursor, &uc);
	while (unw_step(&cursor) > 0) {
		char name[255];
1242 1243
		unw_word_t off, ip;
		Dwfl_Module *mod = NULL;
1244

1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
		unw_get_reg(&cursor, UNW_REG_IP, &ip);

		if (dwfl)
			mod = dwfl_addrmodule(dwfl, ip);

		if (mod) {
			const char *src, *dwfl_name;
			Dwfl_Line *line;
			int lineno;
			GElf_Sym sym;
1255

1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
			line = dwfl_module_getsrc(mod, ip);
			dwfl_name = dwfl_module_addrsym(mod, ip, &sym, NULL);

			if (line && dwfl_name) {
				src = dwfl_lineinfo(line, NULL, &lineno, NULL, NULL, NULL);
				igt_info("  #%d %s:%d %s()\n", stack_num++, src, lineno, dwfl_name);
				continue;
			}
		}

		if (unw_get_proc_name(&cursor, name, 255, &off) < 0)
			igt_info("  #%d [<unknown>+0x%x]\n", stack_num++,
				 (unsigned int) ip);
		else
			igt_info("  #%d [%s+0x%x]\n", stack_num++, name,
				 (unsigned int) off);
1272
	}
1273 1274 1275

	if (dwfl)
		dwfl_end(dwfl);
1276
}
1277 1278 1279 1280 1281 1282

static const char hex[] = "0123456789abcdef";

static void
xputch(int c)
{
1283
	igt_ignore_warn(write(STDERR_FILENO, (const void *) &c, 1));
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
}

static int
xpow(int base, int pow)
{
	int i, r = 1;

	for (i = 0; i < pow; i++)
		r *= base;

	return r;
}

static void
printnum(unsigned long long num, unsigned base)
{
	int i = 0;
1301
	unsigned long long __num = num;
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335

	/* determine from where we should start dividing */
	do {
		__num /= base;
		i++;
	} while (__num);

	while (i--)
		xputch(hex[num / xpow(base, i) % base]);
}

static size_t
xstrlcpy(char *dst, const char *src, size_t size)
{
	char *dst_in;

	dst_in = dst;
	if (size > 0) {
		while (--size > 0 && *src != '\0')
			*dst++ = *src++;
		*dst = '\0';
	}

	return dst - dst_in;
}

static void
xprintfmt(const char *fmt, va_list ap)
{
	const char *p;
	int ch, base;
	unsigned long long num;

	while (1) {
1336
		while ((ch = *(const unsigned char *) fmt++) != '%') {
1337 1338 1339 1340 1341 1342
			if (ch == '\0') {
				return;
			}
			xputch(ch);
		}

1343
		ch = *(const unsigned char *) fmt++;
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
		switch (ch) {
		/* character */
		case 'c':
			xputch(va_arg(ap, int));
			break;
		/* string */
		case 's':
			if ((p = va_arg(ap, char *)) == NULL) {
				p = "(null)";
			}

			for (; (ch = *p++) != '\0';) {
				if (ch < ' ' || ch > '~') {
					xputch('?');
				} else {
					xputch(ch);
				}
			}
			break;
		/* (signed) decimal */
		case 'd':
			num = va_arg(ap, int);
			if ((long long) num < 0) {
				xputch('-');
				num = -(long long) num;
			}
			base = 10;
			goto number;
		/* unsigned decimal */
		case 'u':
			num = va_arg(ap, unsigned int);
			base = 10;
			goto number;
		/* (unsigned) hexadecimal */
		case 'x':
			num = va_arg(ap, unsigned int);
			base = 16;
number:
			printnum(num, base);
			break;

		/* The following are not implemented */

		/* width field */
		case '1': case '2':
		case '3': case '4':
		case '5': case '6':
		case '7': case '8':
		case '9':
		case '.': case '#':
		/* long */
		case 'l':
		/* octal */
		case 'o':
		/* pointer */
		case 'p':
		/* float */
		case 'f':
			abort();
		/* escaped '%' character */
		case '%':
			xputch(ch);
			break;
		/* unrecognized escape sequence - just print it literally */
		default:
			xputch('%');
			for (fmt--; fmt[-1] != '%'; fmt--)
				; /* do nothing */
			break;
		}
	}
}

/* async-safe printf */
static void
xprintf(const char *fmt, ...)
{
	va_list ap;

	va_start(ap, fmt);
	xprintfmt(fmt, ap);
	va_end(ap);
}

static void print_backtrace_sig_safe(void)
{
	unw_cursor_t cursor;
	unw_context_t uc;
	int stack_num = 0;

1434
	write_stderr("Stack trace: \n");
1435 1436 1437 1438 1439 1440 1441 1442

	unw_getcontext(&uc);
	unw_init_local(&cursor, &uc);
	while (unw_step(&cursor) > 0) {
		char name[255];
		unw_word_t off;

		if (unw_get_proc_name(&cursor, name, 255, &off) < 0)
1443
			xstrlcpy(name, "<unknown>", 10);
1444 1445 1446 1447 1448 1449

		xprintf(" #%d [%s+0x%x]\n", stack_num++, name,
				(unsigned int) off);

	}
}
1450

1451 1452
void __igt_fail_assert(const char *domain, const char *file, const int line,
		       const char *func, const char *assertion,
Daniel Vetter's avatar
Daniel Vetter committed
1453 1454 1455 1456
		       const char *f, ...)
{
	va_list args;
	int err = errno;
1457

1458 1459 1460 1461
	igt_log(domain, IGT_LOG_CRITICAL,
		"Test assertion failure function %s, file %s:%i:\n", func, file,
		line);
	igt_log(domain, IGT_LOG_CRITICAL, "Failed assertion: %s\n", assertion);
1462
	if (err)
1463 1464
		igt_log(domain, IGT_LOG_CRITICAL, "Last errno: %i, %s\n", err,
			strerror(err));
Daniel Vetter's avatar
Daniel Vetter committed
1465 1466 1467

	if (f) {
		va_start(args, f);
1468
		igt_vlog(domain, IGT_LOG_CRITICAL, f, args);
Daniel Vetter's avatar
Daniel Vetter committed
1469 1470 1471
		va_end(args);
	}

1472 1473
	print_backtrace();

1474
	if (running_under_gdb())
Daniel Vetter's avatar
Daniel Vetter committed
1475
		abort();
1476
	igt_fail(IGT_EXIT_FAILURE);
Daniel Vetter's avatar
Daniel Vetter committed
1477 1478
}

1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
/**
 * igt_exit:
 *
 * exit() for both types (simple and with subtests) of i-g-t tests.
 *
 * This will exit the test with the right exit code when subtests have been
 * skipped. For normal tests it exits with a successful exit code, presuming
 * everything has worked out. For subtests it also checks that at least one
 * subtest has been run (save when only listing subtests.
 *
1489 1490 1491
 * It is an error to normally exit a test calling igt_exit() - without it the
 * result reporting will be wrong. To avoid such issues it is highly recommended
 * to use #igt_main or #igt_simple_main instead of a hand-rolled main() function.
1492
 */
Daniel Vetter's avatar
Daniel Vetter committed
1493 1494
void igt_exit(void)
{
1495 1496
	int tmp;

Daniel Vetter's avatar
Daniel Vetter committed
1497 1498
	igt_exit_called = true;

1499 1500 1501
	if (igt_key_file)
		g_key_file_free(igt_key_file);

1502 1503
	if (run_single_subtest && !run_single_subtest_found) {
		igt_warn("Unknown subtest: %s\n", run_single_subtest);
1504
		exit(IGT_EXIT_INVALID);
1505 1506
	}

Daniel Vetter's avatar
Daniel Vetter committed
1507
	if (igt_only_list_subtests())
1508
		exit(IGT_EXIT_SUCCESS);
Daniel Vetter's avatar
Daniel Vetter committed
1509

1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
	/* Calling this without calling one of the above is a failure */
	assert(!test_with_subtests ||
	       skipped_one ||
	       succeeded_one ||
	       failed_one);

	if (test_with_subtests && !failed_one) {
		if (succeeded_one)
			igt_exitcode = IGT_EXIT_SUCCESS;
		else
			igt_exitcode = IGT_EXIT_SKIP;
	}

1523
	if (command_str)
Chris Wilson's avatar
Chris Wilson committed
1524 1525
		igt_kmsg(KMSG_INFO "%s: exiting, ret=%d\n",
			 command_str, igt_exitcode);
1526
	igt_debug("Exiting with status code %d\n", igt_exitcode);
1527

1528 1529
	for (int c = 0; c < num_test_children; c++)
		kill(test_children[c], SIGKILL);
1530
	assert(!num_test_children);
1531

1532 1533
	assert(waitpid(-1, &tmp, WNOHANG) == -1 && errno == ECHILD);

1534 1535 1536 1537
	if (!test_with_subtests) {
		struct timespec now;
		const char *result;

1538
		igt_gettime(&now);
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550

		switch (igt_exitcode) {
			case IGT_EXIT_SUCCESS:
				result = "SUCCESS";
				break;
			case IGT_EXIT_SKIP:
				result = "SKIP";
				break;
			default:
				result = "FAIL";
		}

1551
		printf("%s (%.3fs)\n",
1552
		       result, igt_time_elapsed(&subtest_time, &now));
1553
	}
Daniel Vetter's avatar
Daniel Vetter committed
1554

1555
	exit(igt_exitcode);
Daniel Vetter's avatar
Daniel Vetter committed
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569
}

/* fork support code */
static int helper_process_count;
static pid_t helper_process_pids[] =
{ -1, -1, -1, -1};

static void reset_helper_process_list(void)
{
	for (int i = 0; i < ARRAY_SIZE(helper_process_pids); i++)
		helper_process_pids[i] = -1;
	helper_process_count = 0;
}

1570
static int __waitpid(pid_t pid)
Daniel Vetter's avatar
Daniel Vetter committed
1571
{
1572 1573 1574 1575
	int status = -1;
	while (waitpid(pid, &status, 0) == -1 &&
	       errno == EINTR)
		;
1576

1577 1578 1579 1580 1581
	return status;
}

static void fork_helper_exit_handler(int sig)
{
1582
	/* Inside a signal handler, play safe */
Daniel Vetter's avatar
Daniel Vetter committed
1583 1584 1585
	for (int i = 0; i < ARRAY_SIZE(helper_process_pids); i++) {
		pid_t pid = helper_process_pids[i];
		if (pid != -1) {
1586
			kill(pid, SIGTERM);
1587
			__waitpid(pid);
Daniel Vetter's avatar
Daniel Vetter committed
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
			helper_process_count--;
		}
	}

	assert(helper_process_count == 0);
}

bool __igt_fork_helper(struct igt_helper_process *proc)
{
	pid_t pid;
	int id;
1599
	int tmp_count;
Daniel Vetter's avatar
Daniel Vetter committed
1600 1601 1602 1603 1604 1605 1606 1607 1608

	assert(!proc->running);
	assert(helper_process_count < ARRAY_SIZE(helper_process_pids));

	for (id = 0; helper_process_pids[id] != -1; id++)
		;

	igt_install_exit_handler(fork_helper_exit_handler);

1609 1610 1611 1612 1613 1614 1615
	/*
	 * Avoid races when the parent stops the child before the setup code
	 * had a chance to run. This happens e.g. when skipping tests wrapped in
	 * the signal helper.
	 */
	tmp_count = exit_handler_count;
	exit_handler_count = 0;
1616 1617 1618 1619

	/* ensure any buffers are flushed before fork */
	fflush(NULL);

Daniel Vetter's avatar
Daniel Vetter committed
1620 1621
	switch (pid = fork()) {
	case -1:
1622
		exit_handler_count = tmp_count;
Daniel Vetter's avatar
Daniel Vetter committed
1623 1624 1625 1626 1627 1628 1629
		igt_assert(0);
	case 0:
		reset_helper_process_list();
		oom_adjust_for_doom();

		return true;
	default:
1630
		exit_handler_count = tmp_count;
Daniel Vetter's avatar
Daniel Vetter committed
1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641
		proc->running = true;
		proc->pid = pid;
		proc->id = id;
		helper_process_pids[id] = pid;
		helper_process_count++;

		return false;
	}

}

1642
/**
1643
 * igt_wait_helper:
1644 1645
 * @proc: #igt_helper_process structure
 *
1646 1647
 * Joins a helper process. It is an error to call this on a helper process which
 * hasn't been spawned yet.
1648
 */