1 /*
2  * Copyright © 2007,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 
29 
30 #ifndef IGT_CORE_H
31 #define IGT_CORE_H
32 
33 #include <assert.h>
34 #include <setjmp.h>
35 #include <stdbool.h>
36 #include <stdint.h>
37 #include <stdlib.h>
38 #include <stdio.h>
39 #include <string.h>
40 #include <sys/types.h>
41 #include <stdarg.h>
42 #include <getopt.h>
43 #include <unistd.h>
44 
45 #ifndef IGT_LOG_DOMAIN
46 #define IGT_LOG_DOMAIN (NULL)
47 #endif
48 
49 
50 #ifndef STATIC_ANALYSIS_BUILD
51 #if defined(__clang_analyzer__) || defined(__COVERITY__) || defined(__KLOCWORK__)
52 #define STATIC_ANALYSIS_BUILD 1
53 #else
54 #define STATIC_ANALYSIS_BUILD 0
55 #endif
56 #endif
57 
58 /**
59  * BUILD_BUG_ON_INVALID:
60  * @expr: Expression
61  *
62  * A macro that takes an expression and generates no code. Used for
63  * checking at build-time that an expression is valid code.
64  */
65 #define BUILD_BUG_ON_INVALID(e) ((void)(sizeof((long)(e))))
66 
67 /**
68  * igt_assume:
69  * @expr: Condition to test
70  *
71  * An assert-like macro to be used for tautologies to give hints to
72  * static analysis of code. No-op if STATIC_ANALYSIS_BUILD is not
73  * defined, expands to an assert() if it is.
74  */
75 #if STATIC_ANALYSIS_BUILD
76 #define igt_assume(e) assert(e)
77 #else
78 /* Make sure the expression is still parsed even though it generates no code */
79 #define igt_assume(e) BUILD_BUG_ON_INVALID(e)
80 #endif
81 
82 extern const char* __igt_test_description __attribute__((weak));
83 extern bool __igt_plain_output;
84 extern char *igt_frame_dump_path;
85 
86 /**
87  * IGT_TEST_DESCRIPTION:
88  * @str: description string
89  *
90  * Defines a description for a test. This is used as the output for the
91  * "--help-description" option and is also included in the generated
92  * documentation.
93  */
94 #define IGT_TEST_DESCRIPTION(str) const char* __igt_test_description = str
95 
96 /**
97  * IGT_EXIT_SKIP:
98  *
99  * Exit status indicating the test was skipped.
100  */
101 #define IGT_EXIT_SKIP    77
102 
103 /**
104  * IGT_EXIT_SUCCESS
105  *
106  * Exit status indicating the test executed successfully.
107  */
108 #define IGT_EXIT_SUCCESS 0
109 
110 /**
111  * IGT_EXIT_INVALID
112  *
113  * Exit status indicating an invalid option or subtest was specified
114  */
115 #define IGT_EXIT_INVALID 79
116 
117 /**
118  * IGT_EXIT_FAILURE
119  *
120  * Exit status indicating a test failure
121  */
122 #define IGT_EXIT_FAILURE 98
123 
124 bool __igt_fixture(void);
125 void __igt_fixture_complete(void);
126 void __igt_fixture_end(void) __attribute__((noreturn));
127 /**
128  * igt_fixture:
129  *
130  * Annotate global test fixture code
131  *
132  * Testcase with subtests often need to set up a bunch of global state as the
133  * common test fixture. To avoid such code interfering with the subtest
134  * enumeration (e.g. when enumerating on systems without an intel gpu) such
135  * blocks should be annotated with igt_fixture.
136  */
137 #define igt_fixture for (volatile int igt_tokencat(__tmpint,__LINE__) = 0; \
138 			 igt_tokencat(__tmpint,__LINE__) < 1 && \
139 			 (STATIC_ANALYSIS_BUILD || \
140 			 (__igt_fixture() && \
141 			 (sigsetjmp(igt_subtest_jmpbuf, 1) == 0))); \
142 			 igt_tokencat(__tmpint,__LINE__) ++, \
143 			 __igt_fixture_complete())
144 
145 /* subtest infrastructure */
146 jmp_buf igt_subtest_jmpbuf;
147 typedef int (*igt_opt_handler_t)(int opt, int opt_index, void *data);
148 #define IGT_OPT_HANDLER_SUCCESS 0
149 #define IGT_OPT_HANDLER_ERROR -2
150 #ifndef __GTK_DOC_IGNORE__ /* gtkdoc wants to document this forward decl */
151 struct option;
152 #endif
153 int igt_subtest_init_parse_opts(int *argc, char **argv,
154 				const char *extra_short_opts,
155 				const struct option *extra_long_opts,
156 				const char *help_str,
157 				igt_opt_handler_t extra_opt_handler,
158 				void *handler_data);
159 
160 
161 /**
162  * igt_subtest_init:
163  * @argc: argc from the test's main()
164  * @argv: argv from the test's main()
165  *
166  * This initializes the for tests with subtests without the need for additional
167  * command line options. It is just a simplified version of
168  * igt_subtest_init_parse_opts().
169  *
170  * If there's not a reason to the contrary it's less error prone to just use an
171  * #igt_main block instead of stitching the test's main() function together
172  * manually.
173  */
174 #define igt_subtest_init(argc, argv) \
175 	igt_subtest_init_parse_opts(&argc, argv, NULL, NULL, NULL, NULL, NULL);
176 
177 bool __igt_run_subtest(const char *subtest_name, const char *file, const int line);
178 #define __igt_tokencat2(x, y) x ## y
179 
180 /**
181  * igt_tokencat:
182  * @x: first variable
183  * @y: second variable
184  *
185  * C preprocessor helper to concatenate two variables while properly expanding
186  * them.
187  */
188 #define igt_tokencat(x, y) __igt_tokencat2(x, y)
189 
190 /**
191  * igt_subtest:
192  * @name: name of the subtest
193  *
194  * This is a magic control flow block which denotes a subtest code block. Within
195  * that code block igt_skip|success will only bail out of the subtest. The _f
196  * variant accepts a printf format string, which is useful for constructing
197  * combinatorial tests.
198  *
199  * This is a simpler version of igt_subtest_f()
200  */
201 #define igt_subtest(name) for (; __igt_run_subtest((name), __FILE__, __LINE__) && \
202 				   (sigsetjmp(igt_subtest_jmpbuf, 1) == 0); \
203 				   igt_success())
204 #define __igt_subtest_f(tmp, format...) \
205 	for (char tmp [256]; \
206 	     snprintf( tmp , sizeof( tmp ), \
207 		      format), \
208 	     __igt_run_subtest(tmp, __FILE__, __LINE__) && \
209 	     (sigsetjmp(igt_subtest_jmpbuf, 1) == 0); \
210 	     igt_success())
211 
212 /**
213  * igt_subtest_f:
214  * @...: format string and optional arguments
215  *
216  * This is a magic control flow block which denotes a subtest code block. Within
217  * that code block igt_skip|success will only bail out of the subtest. The _f
218  * variant accepts a printf format string, which is useful for constructing
219  * combinatorial tests.
220  *
221  * Like igt_subtest(), but also accepts a printf format string instead of a
222  * static string.
223  */
224 #define igt_subtest_f(f...) \
225 	__igt_subtest_f(igt_tokencat(__tmpchar, __LINE__), f)
226 
227 const char *igt_subtest_name(void);
228 bool igt_only_list_subtests(void);
229 
230 void __igt_subtest_group_save(int *, int *);
231 void __igt_subtest_group_restore(int, int);
232 /**
233  * igt_subtest_group:
234  *
235  * Group a set of subtests together with their common setup code
236  *
237  * Testcase with subtests often need to set up a bunch of shared state as the
238  * common test fixture. But if there are multiple with different requirements
239  * the commont setup code can't be extracted, since a test condition failure in
240  * e.g. igt_require() would result in all subsequent tests skipping. Even those
241  * from a different group.
242  *
243  * This macro allows to group together a set of #igt_fixture and #igt_subtest
244  * clauses. If any common setup in a fixture fails, only the subtests in this
245  * group will fail or skip. Subtest groups can be arbitrarily nested.
246  */
247 #define igt_subtest_group for (int igt_tokencat(__tmpint,__LINE__) = 0, \
248 			       igt_tokencat(__save,__LINE__) = 0, \
249 			       igt_tokencat(__desc,__LINE__) = 0; \
250 			       igt_tokencat(__tmpint,__LINE__) < 1 && \
251 			       (__igt_subtest_group_save(& igt_tokencat(__save,__LINE__), \
252 							 & igt_tokencat(__desc,__LINE__) ), true); \
253 			       igt_tokencat(__tmpint,__LINE__) ++, \
254 			       __igt_subtest_group_restore(igt_tokencat(__save,__LINE__), \
255 							   igt_tokencat(__desc,__LINE__)))
256 
257 /**
258  * igt_main_args:
259  * @extra_short_opts: getopt_long() compliant list with additional short options
260  * @extra_long_opts: getopt_long() compliant list with additional long options
261  * @help_str: help string for the additional options
262  * @extra_opt_handler: handler for the additional options
263  * @handler_data: user data given to @extra_opt_handler when invoked
264  *
265  * This is a magic control flow block used instead of a main()
266  * function for tests with subtests, along with custom command line
267  * arguments. The macro parameters are passed directly to
268  * #igt_subtest_init_parse_opts.
269  */
270 #define igt_main_args(short_opts, long_opts, help_str, opt_handler, handler_data) \
271 	static void igt_tokencat(__real_main, __LINE__)(void); \
272 	int main(int argc, char **argv) { \
273 		igt_subtest_init_parse_opts(&argc, argv, \
274 					    short_opts, long_opts, help_str, \
275 					    opt_handler, handler_data); \
276 		igt_tokencat(__real_main, __LINE__)(); \
277 		igt_exit(); \
278 	} \
279 	static void igt_tokencat(__real_main, __LINE__)(void) \
280 
281 
282 /**
283  * igt_main:
284  *
285  * This is a magic control flow block used instead of a main() function for
286  * tests with subtests. Open-coding the main() function is not recommended.
287  */
288 #define igt_main igt_main_args(NULL, NULL, NULL, NULL, NULL)
289 
290 const char *igt_test_name(void);
291 void igt_simple_init_parse_opts(int *argc, char **argv,
292 				const char *extra_short_opts,
293 				const struct option *extra_long_opts,
294 				const char *help_str,
295 				igt_opt_handler_t extra_opt_handler,
296 				void *handler_data);
297 
298 /**
299  * igt_simple_init:
300  * @argc: argc from the test's main()
301  * @argv: argv from the test's main()
302  *
303  * This initializes a simple test without any support for subtests.
304  *
305  * If there's not a reason to the contrary it's less error prone to just use an
306  * #igt_simple_main block instead of stitching the test's main() function together
307  * manually.
308  */
309 #define igt_simple_init(argc, argv) \
310 	igt_simple_init_parse_opts(&argc, argv, NULL, NULL, NULL, NULL, NULL);
311 
312 
313 /**
314  * igt_simple_main_args:
315  * @extra_short_opts: getopt_long() compliant list with additional short options
316  * @extra_long_opts: getopt_long() compliant list with additional long options
317  * @help_str: help string for the additional options
318  * @extra_opt_handler: handler for the additional options
319  * @handler_data: user data given to @extra_opt_handler when invoked
320  *
321  * This is a magic control flow block used instead of a main()
322  * function for simple tests with custom command line arguments. The
323  * macro parameters are passed directly to
324  * #igt_simple_init_parse_opts.
325  */
326 #define igt_simple_main_args(short_opts, long_opts, help_str, opt_handler, handler_data) \
327 	static void igt_tokencat(__real_main, __LINE__)(void); \
328 	int main(int argc, char **argv) { \
329 		igt_simple_init_parse_opts(&argc, argv, \
330 					   short_opts, long_opts, help_str, \
331 					   opt_handler, handler_data);	\
332 		igt_tokencat(__real_main, __LINE__)(); \
333 		igt_exit(); \
334 	} \
335 	static void igt_tokencat(__real_main, __LINE__)(void) \
336 
337 
338 /**
339  * igt_simple_main:
340  *
341  * This is a magic control flow block used instead of a main() function for
342  * simple tests. Open-coding the main() function is not recommended.
343  */
344 #define igt_simple_main igt_simple_main_args(NULL, NULL, NULL, NULL, NULL)
345 
346 /**
347  * igt_constructor:
348  *
349  * Convenience macro to run the provided code block when igt first starts,
350  * before any tests have been run. This should be used for parts of the igt
351  * library that require initialization of objects with global context.
352  *
353  * This code block will be executed exactly once.
354  */
355 #define igt_constructor \
356 	__attribute__((constructor)) \
357 	static void igt_tokencat(__igt_constructor_l, __LINE__)(void)
358 
359 __attribute__((format(printf, 1, 2)))
360 void igt_skip(const char *f, ...) __attribute__((noreturn));
361 __attribute__((format(printf, 5, 6)))
362 void __igt_skip_check(const char *file, const int line,
363 		      const char *func, const char *check,
364 		      const char *format, ...) __attribute__((noreturn));
365 #define igt_skip_check(E, F...) \
366 	__igt_skip_check(__FILE__, __LINE__, __func__, E, F)
367 void igt_success(void);
368 
369 bool igt_can_fail(void);
370 
371 void igt_fail(int exitcode) __attribute__((noreturn));
372 __attribute__((format(printf, 6, 7)))
373 void __igt_fail_assert(const char *domain, const char *file,
374 		       const int line, const char *func, const char *assertion,
375 		       const char *format, ...)
376 	__attribute__((noreturn));
377 void igt_exit(void) __attribute__((noreturn));
378 void igt_fatal_error(void) __attribute__((noreturn));
379 
380 /**
381  * igt_ignore_warn:
382  * @expr: condition to ignore
383  *
384  *
385  * Stops the compiler warning about an unused return value.
386  */
igt_ignore_warn(bool value)387 static inline void igt_ignore_warn(bool value)
388 {
389 }
390 
391 __attribute__((format(printf, 1, 2)))
392 void igt_describe_f(const char *fmt, ...);
393 
394 /**
395  * igt_describe:
396  * @dsc: string containing description
397  *
398  * Attach a description to the following #igt_subtest or #igt_subtest_group
399  * block.
400  *
401  * The description should complement the test/subtest name and provide more
402  * context on what is being tested. It should explain the idea of the test and
403  * do not mention implementation details, so that it never goes out of date.
404  *
405  * DO:
406  *  * focus on the userspace's perspective
407  *  * try to capture the reason for the test's existence
408  *  * be brief
409  *
410  * DON'T:
411  *  * try to translate the code into English
412  *  * explain all the checks the test does
413  *  * delve on the implementation
414  *
415  * Good examples:
416  *  * "make sure that legacy cursor updates do not stall atomic commits"
417  *  * "check that atomic updates of many planes are indeed atomic and take
418  *     effect immediately after the commit"
419  *  * "make sure that the meta-data exposed by the kernel to the userspace
420  *     is correct and matches the used EDID"
421  *
422  * Bad examples:
423  *  * "spawn 10 threads, each pinning cpu core with a busy loop..."
424  *  * "randomly generate holes in a primary plane then try to cover each hole
425  *    with a plane and make sure that CRC matches, do 25 gazillion rounds of
426  *    that..."
427  *
428  *
429  * Resulting #igt_subtest documentation is a concatenation of its own
430  * description and all the parenting #igt_subtest_group descriptions, starting
431  * from the outermost one. Example:
432  *
433  * |[<!-- language="C" -->
434  * #include "igt.h"
435  *
436  * IGT_TEST_DESCRIPTION("Global description of the whole binary");
437  * igt_main
438  * {
439  * 	igt_describe("Desc of the subgroup with A and B");
440  * 	igt_subtest_group {
441  * 		igt_describe("Desc of the subtest A");
442  * 		igt_subtest("subtest-a") {
443  * 			...
444  * 		}
445  *
446  * 		igt_describe("Desc of the subtest B");
447  * 		igt_subtest("subtest-b") {
448  * 			...
449  * 		}
450  * 	}
451  *
452  * 	igt_describe("Desc of the subtest C");
453  * 	igt_subtest("subtest-c") {
454  * 		...
455  * 	}
456  * }
457  * ]|
458  *
459  * It's will accessible via --describe command line switch:
460  *
461  * |[
462  * $ test --describe
463  * Global description of the whole binary
464  *
465  * SUB subtest-a test.c:5:
466  *   Desc of the subgroup with A and B
467  *
468  *   Desc of the subtest A
469  *
470  * SUB subtest-b test.c:10:
471  *   Desc of the subgroup with A and B
472  *
473  *   Desc of the subtest B
474  *
475  * SUB subtest-c test.c:15:
476  *   Desc of the subtest C
477  * ]|
478  *
479  * Every single #igt_subtest does not have to be preceded with a #igt_describe
480  * as long as it has good-enough explanation provided on the #igt_subtest_group
481  * level.
482  *
483  * Example:
484  *
485  * |[<!-- language="C" -->
486  * #include "igt.h"
487  *
488  * igt_main
489  * {
490  * 	igt_describe("check xyz with different tilings");
491  * 	igt_subtest_group {
492  * 		// no need for extra description, group is enough and tiling is
493  * 		// obvious from the test name
494  * 		igt_subtest("foo-tiling-x") {
495  * 			...
496  * 		}
497  *
498  * 		igt_subtest("foo-tiling-y") {
499  * 			...
500  * 		}
501  * 	}
502  * }
503  * ]|
504  *
505  */
506 #define igt_describe(dsc) \
507 	igt_describe_f("%s", dsc)
508 
509 /**
510  * igt_assert:
511  * @expr: condition to test
512  *
513  * Fails (sub-)test if the condition is not met.
514  *
515  * Should be used everywhere where a test checks results.
516  */
517 #define igt_assert(expr) \
518 	do { if (!(expr)) \
519 		__igt_fail_assert(IGT_LOG_DOMAIN, __FILE__, __LINE__, __func__, #expr , NULL); \
520 	} while (0)
521 
522 /**
523  * igt_assert_f:
524  * @expr: condition to test
525  * @...: format string and optional arguments
526  *
527  * Fails (sub-)test if the condition is not met.
528  *
529  * Should be used everywhere where a test checks results.
530  *
531  * In addition to the plain igt_assert() helper this allows to print additional
532  * information to help debugging test failures.
533  */
534 #define igt_assert_f(expr, f...) \
535 	do { if (!(expr)) \
536 		__igt_fail_assert(IGT_LOG_DOMAIN, __FILE__, __LINE__, __func__, #expr , f); \
537 	} while (0)
538 
539 /**
540  * igt_fail_on:
541  * @expr: condition to test
542  *
543  * Fails (sub-)test if the condition is met.
544  *
545  * Should be used everywhere where a test checks results.
546  */
547 #define igt_fail_on(expr) igt_assert(!(expr))
548 
549 /**
550  * igt_fail_on_f:
551  * @expr: condition to test
552  * @...: format string and optional arguments
553  *
554  * Fails (sub-)test if the condition is met.
555  *
556  * Should be used everywhere where a test checks results.
557  *
558  * In addition to the plain igt_assert() helper this allows to print additional
559  * information to help debugging test failures.
560  */
561 #define igt_fail_on_f(expr, f...) igt_assert_f(!(expr), f)
562 
563 /**
564  * igt_assert_cmpint:
565  * @n1: first value
566  * @cmp: compare operator
567  * @ncmp: negated version of @cmp
568  * @n2: second value
569  *
570  * Fails (sub-)test if the condition is not met
571  *
572  * Should be used everywhere where a test compares two integer values.
573  *
574  * Like igt_assert(), but displays the values being compared on failure instead
575  * of simply printing the stringified expression.
576  */
577 #define igt_assert_cmpint(n1, cmp, ncmp, n2) \
578 	do { \
579 		int __n1 = (n1), __n2 = (n2); \
580 		if (__n1 cmp __n2) ; else \
581 		__igt_fail_assert(IGT_LOG_DOMAIN, __FILE__, __LINE__, __func__, \
582 				  #n1 " " #cmp " " #n2, \
583 				  "error: %d " #ncmp " %d\n", __n1, __n2); \
584 	} while (0)
585 
586 /**
587  * igt_assert_cmpuint:
588  * @n1: first value
589  * @cmp: compare operator
590  * @ncmp: negated version of @cmp
591  * @n2: second value
592  *
593  * Like igt_assert_cmpint(), but for unsigned ints.
594  */
595 #define igt_assert_cmpuint(n1, cmp, ncmp, n2) \
596 	do { \
597 		uint32_t __n1 = (n1), __n2 = (n2); \
598 		if (__n1 cmp __n2) ; else \
599 		__igt_fail_assert(IGT_LOG_DOMAIN, __FILE__, __LINE__, __func__, \
600 				  #n1 " " #cmp " " #n2, \
601 				  "error: %#x " #ncmp " %#x\n", __n1, __n2); \
602 	} while (0)
603 
604 /**
605  * igt_assert_cmps64:
606  * @n1: first value
607  * @cmp: compare operator
608  * @ncmp: negated version of @cmp
609  * @n2: second value
610  *
611  * Like igt_assert_cmpuint(), but for larger signed ints.
612  */
613 #define igt_assert_cmps64(n1, cmp, ncmp, n2) \
614 	do { \
615 		int64_t __n1 = (n1), __n2 = (n2); \
616 		if (__n1 cmp __n2) ; else \
617 		__igt_fail_assert(IGT_LOG_DOMAIN, __FILE__, __LINE__, __func__, \
618 				  #n1 " " #cmp " " #n2, \
619 				  "error: %lld " #ncmp " %lld\n", (long long)__n1, (long long)__n2); \
620 	} while (0)
621 
622 /**
623  * igt_assert_cmpu64:
624  * @n1: first value
625  * @cmp: compare operator
626  * @ncmp: negated version of @cmp
627  * @n2: second value
628  *
629  * Like igt_assert_cmpuint(), but for larger ints.
630  */
631 #define igt_assert_cmpu64(n1, cmp, ncmp, n2) \
632 	do { \
633 		uint64_t __n1 = (n1), __n2 = (n2); \
634 		if (__n1 cmp __n2) ; else \
635 		__igt_fail_assert(IGT_LOG_DOMAIN, __FILE__, __LINE__, __func__, \
636 				  #n1 " " #cmp " " #n2, \
637 				  "error: %#llx " #ncmp " %#llx\n", (long long)__n1, (long long)__n2); \
638 	} while (0)
639 
640 /**
641  * igt_assert_cmpdouble:
642  * @n1: first value
643  * @cmp: compare operator
644  * @ncmp: negated version of @cmp
645  * @n2: second value
646  *
647  * Like igt_assert_cmpint(), but for doubles.
648  */
649 #define igt_assert_cmpdouble(n1, cmp, ncmp, n2) \
650 	do { \
651 		double __n1 = (n1), __n2 = (n2); \
652 		if (__n1 cmp __n2) ; else \
653 		__igt_fail_assert(IGT_LOG_DOMAIN, __FILE__, __LINE__, __func__, \
654 				  #n1 " " #cmp " " #n2, \
655 				  "error: %#lf " #ncmp " %#lf\n", __n1, __n2); \
656 	} while (0)
657 
658 /**
659  * igt_assert_eq:
660  * @n1: first integer
661  * @n2: second integer
662  *
663  * Fails (sub-)test if the two integers are not equal. Beware that for now this
664  * only works on integers.
665  *
666  * Like igt_assert(), but displays the values being compared on failure instead
667  * of simply printing the stringified expression.
668  */
669 #define igt_assert_eq(n1, n2) igt_assert_cmpint(n1, ==, !=, n2)
670 
671 /**
672  * igt_assert_eq_u32:
673  * @n1: first integer
674  * @n2: second integer
675  *
676  * Like igt_assert_eq(), but for uint32_t.
677  */
678 #define igt_assert_eq_u32(n1, n2) igt_assert_cmpuint(n1, ==, !=, n2)
679 
680 /**
681  * igt_assert_eq_s64:
682  * @n1: first integer
683  * @n2: second integer
684  *
685  * Like igt_assert_eq_u32(), but for int64_t.
686  */
687 #define igt_assert_eq_s64(n1, n2) igt_assert_cmps64(n1, ==, !=, n2)
688 
689 /**
690  * igt_assert_eq_u64:
691  * @n1: first integer
692  * @n2: second integer
693  *
694  * Like igt_assert_eq_u32(), but for uint64_t.
695  */
696 #define igt_assert_eq_u64(n1, n2) igt_assert_cmpu64(n1, ==, !=, n2)
697 
698 /**
699  * igt_assert_eq_double:
700  * @n1: first double
701  * @n2: second double
702  *
703  * Like igt_assert_eq(), but for doubles.
704  */
705 #define igt_assert_eq_double(n1, n2) igt_assert_cmpdouble(n1, ==, !=, n2)
706 
707 /**
708  * igt_assert_neq:
709  * @n1: first integer
710  * @n2: second integer
711  *
712  * Fails (sub-)test if the two integers are equal. Beware that for now this
713  * only works on integers.
714  *
715  * Like igt_assert(), but displays the values being compared on failure instead
716  * of simply printing the stringified expression.
717  */
718 #define igt_assert_neq(n1, n2) igt_assert_cmpint(n1, !=, ==, n2)
719 
720 /**
721  * igt_assert_neq_u32:
722  * @n1: first integer
723  * @n2: second integer
724  *
725  * Like igt_assert_neq(), but for uint32_t.
726  */
727 #define igt_assert_neq_u32(n1, n2) igt_assert_cmpuint(n1, !=, ==, n2)
728 
729 /**
730  * igt_assert_neq_u64:
731  * @n1: first integer
732  * @n2: second integer
733  *
734  * Like igt_assert_neq_u32(), but for uint64_t.
735  */
736 #define igt_assert_neq_u64(n1, n2) igt_assert_cmpu64(n1, !=, ==, n2)
737 
738 /**
739  * igt_assert_neq_double:
740  * @n1: first double
741  * @n2: second double
742  *
743  * Like igt_assert_neq(), but for doubles.
744  */
745 #define igt_assert_neq_double(n1, n2) igt_assert_cmpdouble(n1, !=, ==, n2)
746 
747 /**
748  * igt_assert_lte:
749  * @n1: first integer
750  * @n2: second integer
751  *
752  * Fails (sub-)test if the second integer is strictly smaller than the first.
753  * Beware that for now this only works on integers.
754  *
755  * Like igt_assert(), but displays the values being compared on failure instead
756  * of simply printing the stringified expression.
757  */
758 #define igt_assert_lte(n1, n2) igt_assert_cmpint(n1, <=, >, n2)
759 
760 /**
761  * igt_assert_lte_u64:
762  * @n1: first integer
763  * @n2: second integer
764  *
765  * Fails (sub-)test if the second integer is strictly smaller than the first.
766  * Beware that for now this only works on integers.
767  *
768  * Like igt_assert(), but displays the values being compared on failure instead
769  * of simply printing the stringified expression.
770  */
771 #define igt_assert_lte_u64(n1, n2) igt_assert_cmpu64(n1, <=, >, n2)
772 
773 /**
774  * igt_assert_lte_s64:
775  * @n1: first integer
776  * @n2: second integer
777  *
778  * Fails (sub-)test if the second integer is strictly smaller than the first.
779  * Beware that for now this only works on integers.
780  *
781  * Like igt_assert(), but displays the values being compared on failure instead
782  * of simply printing the stringified expression.
783  */
784 #define igt_assert_lte_s64(n1, n2) igt_assert_cmps64(n1, <=, >, n2)
785 
786 /**
787  * igt_assert_lt:
788  * @n1: first integer
789  * @n2: second integer
790  *
791  * Fails (sub-)test if the second integer is smaller than or equal to the first.
792  * Beware that for now this only works on integers.
793  *
794  * Like igt_assert(), but displays the values being compared on failure instead
795  * of simply printing the stringified expression.
796  */
797 #define igt_assert_lt(n1, n2) igt_assert_cmpint(n1, <, >=, n2)
798 
799 /**
800  * igt_assert_lt_u64:
801  * @n1: first integer
802  * @n2: second integer
803  *
804  * Fails (sub-)test if the second integer is smaller than or equal to the first.
805  * Beware that for now this only works on integers.
806  *
807  * Like igt_assert(), but displays the values being compared on failure instead
808  * of simply printing the stringified expression.
809  */
810 #define igt_assert_lt_u64(n1, n2) igt_assert_cmpu64(n1, <, >=, n2)
811 
812 /**
813  * igt_assert_lt_s64:
814  * @n1: first integer
815  * @n2: second integer
816  *
817  * Fails (sub-)test if the second integer is smaller than or equal to the first.
818  * Beware that for now this only works on integers.
819  *
820  * Like igt_assert(), but displays the values being compared on failure instead
821  * of simply printing the stringified expression.
822  */
823 #define igt_assert_lt_s64(n1, n2) igt_assert_cmps64(n1, <, >=, n2)
824 
825 /**
826  * igt_assert_fd:
827  * @fd: file descriptor
828  *
829  * Fails (sub-) test if the given file descriptor is invalid.
830  *
831  * Like igt_assert(), but displays the values being compared on failure instead
832  * of simply printing the stringified expression.
833  */
834 #define igt_assert_fd(fd) \
835 	igt_assert_f(fd >= 0, "file descriptor " #fd " failed\n");
836 
837 /**
838  * igt_require:
839  * @expr: condition to test
840  *
841  * Skip a (sub-)test if a condition is not met.
842  *
843  * Should be used everywhere where a test checks results to decide about
844  * skipping. This is useful to streamline the skip logic since it allows for a more flat
845  * code control flow, similar to igt_assert()
846  */
847 #define igt_require(expr) do { \
848 	if (!(expr)) igt_skip_check(#expr , NULL); \
849 	else igt_debug("Test requirement passed: %s\n", #expr); \
850 } while (0)
851 
852 /**
853  * igt_skip_on:
854  * @expr: condition to test
855  *
856  * Skip a (sub-)test if a condition is met.
857  *
858  * Should be used everywhere where a test checks results to decide about
859  * skipping. This is useful to streamline the skip logic since it allows for a more flat
860  * code control flow, similar to igt_assert()
861  */
862 #define igt_skip_on(expr) do { \
863 	if ((expr)) igt_skip_check("!(" #expr ")" , NULL); \
864 	else igt_debug("Test requirement passed: !(%s)\n", #expr); \
865 } while (0)
866 
867 /**
868  * igt_require_f:
869  * @expr: condition to test
870  * @...: format string and optional arguments
871  *
872  * Skip a (sub-)test if a condition is not met.
873  *
874  * Should be used everywhere where a test checks results to decide about
875  * skipping. This is useful to streamline the skip logic since it allows for a more flat
876  * code control flow, similar to igt_assert()
877  *
878  * In addition to the plain igt_require() helper this allows to print additional
879  * information to help debugging test failures.
880  */
881 #define igt_require_f(expr, f...) do { \
882 	if (!(expr)) igt_skip_check(#expr , f); \
883 	else igt_debug("Test requirement passed: %s\n", #expr); \
884 } while (0)
885 
886 /**
887  * igt_skip_on_f:
888  * @expr: condition to test
889  * @...: format string and optional arguments
890  *
891  * Skip a (sub-)test if a condition is met.
892  *
893  * Should be used everywhere where a test checks results to decide about
894  * skipping. This is useful to streamline the skip logic since it allows for a more flat
895  * code control flow, similar to igt_assert()
896  *
897  * In addition to the plain igt_skip_on() helper this allows to print additional
898  * information to help debugging test failures.
899  */
900 #define igt_skip_on_f(expr, f...) do { \
901 	if ((expr)) igt_skip_check("!("#expr")", f); \
902 	else igt_debug("Test requirement passed: !(%s)\n", #expr); \
903 } while (0)
904 
905 /* fork support code */
906 bool __igt_fork(void);
907 
908 /**
909  * igt_fork:
910  * @child: name of the int variable with the child number
911  * @num_children: number of children to fork
912  *
913  * This is a magic control flow block which spawns parallel test threads with
914  * fork().
915  *
916  * The test children execute in parallel to the main test thread. Joining all
917  * test threads should be done with igt_waitchildren to ensure that the exit
918  * codes of all children are properly reflected in the test status.
919  *
920  * Note that igt_skip() will not be forwarded, feature tests need to be done
921  * before spawning threads with igt_fork().
922  */
923 #define igt_fork(child, num_children) \
924 	for (int child = 0; child < (num_children); child++) \
925 		for (; __igt_fork(); exit(0))
926 int __igt_waitchildren(void);
927 void igt_waitchildren(void);
928 void igt_waitchildren_timeout(int seconds, const char *reason);
929 
930 /**
931  * igt_helper_process:
932  * @running: indicates whether the process is currently running
933  * @use_SIGKILL: whether the helper should be terminated with SIGKILL or SIGTERM
934  * @pid: pid of the helper if @running is true
935  * @id: internal id
936  *
937  * Tracking structure for helper processes. Users of the i-g-t library should
938  * only set @use_SIGKILL directly.
939  */
940 struct igt_helper_process {
941 	bool running;
942 	bool use_SIGKILL;
943 	pid_t pid;
944 	int id;
945 };
946 bool __igt_fork_helper(struct igt_helper_process *proc);
947 
948 /**
949  * igt_fork_helper:
950  * @proc: #igt_helper_process structure
951  *
952  * This is a magic control flow block which denotes an asynchronous helper
953  * process block. The difference compared to igt_fork() is that failures from
954  * the child process will not be forwarded, making this construct more suitable
955  * for background processes. Common use cases are regular interference of the
956  * main test thread through e.g. sending signals or evicting objects through
957  * debugfs. Through the explicit #igt_helper_process they can also be controlled
958  * in a more fine-grained way than test children spawned through igt_fork().
959  *
960  * For tests with subtest helper process can be started outside of a
961  * #igt_subtest block.
962  *
963  * Calling igt_wait_helper() joins a helper process and igt_stop_helper()
964  * forcefully terminates it.
965  */
966 #define igt_fork_helper(proc) \
967 	for (; __igt_fork_helper(proc); exit(0))
968 int igt_wait_helper(struct igt_helper_process *proc);
969 void igt_stop_helper(struct igt_helper_process *proc);
970 
971 /* exit handler code */
972 
973 /**
974  * igt_exit_handler_t:
975  * @sig: Signal number which caused the exit or 0.
976  *
977  * Exit handler type used by igt_install_exit_handler(). Note that exit handlers
978  * can potentially be run from signal handling contexts, the @sig parameter can
979  * be used to figure this out and act accordingly.
980  */
981 typedef void (*igt_exit_handler_t)(int sig);
982 
983 /* reliable atexit helpers, also work when killed by a signal (if possible) */
984 void igt_install_exit_handler(igt_exit_handler_t fn);
985 
986 /* helpers to automatically reduce test runtime in simulation */
987 bool igt_run_in_simulation(void);
988 /**
989  * SLOW_QUICK:
990  * @slow: value in simulation mode
991  * @quick: value in normal mode
992  *
993  * Simple macro to select between two values (e.g. number of test rounds or test
994  * buffer size) depending upon whether i-g-t is run in simulation mode or not.
995  */
996 #define SLOW_QUICK(slow,quick) (igt_run_in_simulation() ? (quick) : (slow))
997 
998 void igt_skip_on_simulation(void);
999 
1000 extern const char *igt_interactive_debug;
1001 extern bool igt_skip_crc_compare;
1002 
1003 /**
1004  * igt_log_level:
1005  * @IGT_LOG_DEBUG: debug information, not printed by default
1006  * @IGT_LOG_INFO: informational message, printed by default
1007  * @IGT_LOG_WARN: non-fatal warnings which should be treated as test failures
1008  * @IGT_LOG_CRITICAL: critical errors which lead to immediate termination of tests
1009  * @IGT_LOG_NONE: unused
1010  *
1011  * Log levels used by functions like igt_log().
1012  */
1013 enum igt_log_level {
1014 	IGT_LOG_DEBUG,
1015 	IGT_LOG_INFO,
1016 	IGT_LOG_WARN,
1017 	IGT_LOG_CRITICAL,
1018 	IGT_LOG_NONE,
1019 };
1020 __attribute__((format(printf, 3, 4)))
1021 void igt_log(const char *domain, enum igt_log_level level, const char *format, ...);
1022 __attribute__((format(printf, 3, 0)))
1023 void igt_vlog(const char *domain, enum igt_log_level level, const char *format, va_list args);
1024 
1025 /**
1026  * igt_debug:
1027  * @...: format string and optional arguments
1028  *
1029  * Wrapper for igt_log() for message at the IGT_LOG_DEBUG level.
1030  */
1031 #define igt_debug(f...) igt_log(IGT_LOG_DOMAIN, IGT_LOG_DEBUG, f)
1032 
1033 /**
1034  * igt_info:
1035  * @...: format string and optional arguments
1036  *
1037  * Wrapper for igt_log() for message at the IGT_LOG_INFO level.
1038  */
1039 #define igt_info(f...) igt_log(IGT_LOG_DOMAIN, IGT_LOG_INFO, f)
1040 
1041 /**
1042  * igt_warn:
1043  * @...: format string and optional arguments
1044  *
1045  * Wrapper for igt_log() for message at the IGT_LOG_WARN level.
1046  */
1047 #define igt_warn(f...) igt_log(IGT_LOG_DOMAIN, IGT_LOG_WARN, f)
1048 
1049 /**
1050  * igt_critical:
1051  * @...: format string and optional arguments
1052  *
1053  * Wrapper for igt_log() for message at the IGT_LOG_CRITICAL level.
1054  */
1055 #define igt_critical(f...) igt_log(IGT_LOG_DOMAIN, IGT_LOG_CRITICAL, f)
1056 
1057 typedef bool (*igt_buffer_log_handler_t)(const char *line, void *data);
1058 void igt_log_buffer_inspect(igt_buffer_log_handler_t check, void *data);
1059 
1060 extern enum igt_log_level igt_log_level;
1061 
1062 /**
1063  * igt_warn_on:
1064  * @condition: condition to test
1065  *
1066  * Print a IGT_LOG_WARN level message if a condition is not met.
1067  *
1068  * Should be used everywhere where a test checks results to decide about
1069  * printing warnings. This is useful to streamline the test logic since it
1070  * allows for a more flat code control flow, similar to igt_assert()
1071  *
1072  * This macro also returns the value of @condition.
1073  */
1074 #define igt_warn_on(condition) ({ \
1075 		typeof(condition) ret__ = (condition); \
1076 		if (ret__) \
1077 			igt_warn("Warning on condition %s in function %s, file %s:%i\n", \
1078 				 #condition, __func__, __FILE__, __LINE__); \
1079 		ret__; \
1080 	})
1081 
1082 /**
1083  * igt_warn_on_f:
1084  * @condition: condition to test
1085  * @...: format string and optional arguments
1086  *
1087  * Skip a (sub-)test if a condition is not met.
1088  *
1089  * Print a IGT_LOG_WARN level message if a condition is not met.
1090  *
1091  * Should be used everywhere where a test checks results to decide about
1092  * printing warnings. This is useful to streamline the test logic since it
1093  * allows for a more flat code control flow, similar to igt_assert()
1094  *
1095  * In addition to the plain igt_warn_on_f() helper this allows to print
1096  * additional information (again as warnings) to help debugging test failures.
1097  *
1098  * It also returns the value of @condition.
1099  */
1100 #define igt_warn_on_f(condition, f...) ({ \
1101 		typeof(condition) ret__ = (condition); \
1102 		if (ret__) {\
1103 			igt_warn("Warning on condition %s in function %s, file %s:%i\n", \
1104 				 #condition, __func__, __FILE__, __LINE__); \
1105 			igt_warn(f); \
1106 		} \
1107 		ret__; \
1108 	})
1109 
1110 void igt_set_timeout(unsigned int seconds,
1111 		     const char *op);
1112 
1113 /**
1114  * igt_gettime:
1115  * @ts: current monotonic clock reading
1116  *
1117  * Reports the current time in the monotonic clock.
1118  * Returns: 0 on success, -errno on failure.
1119  */
1120 int igt_gettime(struct timespec *ts);
1121 
1122 /**
1123  * igt_time_elapsed:
1124  * @then: Earlier timestamp
1125  * @now: Later timestamp
1126  *
1127  * Returns: Time between two timestamps in seconds, as a floating
1128  * point number.
1129  */
1130 double igt_time_elapsed(struct timespec *then,
1131 			struct timespec *now);
1132 
1133 /**
1134  * igt_nsec_elapsed:
1135  * @start: measure from this point in time
1136  *
1137  * Reports the difference in the monotonic clock from the start time
1138  * in nanoseconds. On the first invocation, start should be zeroed and will
1139  * be set by the call.
1140  *
1141  * Typical use would be:
1142  *
1143  * igt_subtest("test") {
1144  * 	struct timespec start = {};
1145  * 	while (igt_nsec_elapsed(&start) < test_timeout_ns)
1146  *	 	do_test();
1147  * }
1148  *
1149  * A handy approximation is to use nsec >> 30 to convert to seconds,
1150  * nsec >> 20 to convert to milliseconds - the error is about 8%, acceptable
1151  * for test run times.
1152  */
1153 uint64_t igt_nsec_elapsed(struct timespec *start);
1154 
1155 /**
1156  * igt_seconds_elapsed:
1157  * @start: measure from this point in time
1158  *
1159  * A wrapper around igt_nsec_elapsed that reports the approximate (8% error)
1160  * number of seconds since the start point.
1161  */
igt_seconds_elapsed(struct timespec * start)1162 static inline uint32_t igt_seconds_elapsed(struct timespec *start)
1163 {
1164 	return igt_nsec_elapsed(start) >> 30;
1165 }
1166 
1167 void igt_reset_timeout(void);
1168 
1169 FILE *__igt_fopen_data(const char* igt_srcdir, const char* igt_datadir,
1170 		       const char* filename);
1171 /**
1172  * igt_fopen_data:
1173  * @filename: filename to open.
1174  *
1175  * Open a datafile for test, first try from installation directory,
1176  * then from build directory, and finally from current directory.
1177  */
1178 #define igt_fopen_data(filename) \
1179 	__igt_fopen_data(IGT_SRCDIR, IGT_DATADIR, filename)
1180 
1181 int igt_system(const char *command);
1182 int igt_system_quiet(const char *command);
1183 #define igt_system_cmd(status, format...) \
1184 	do { \
1185 		char *buf = 0; \
1186 		igt_assert(asprintf(&buf, format) != -1); \
1187 	        status = igt_system(buf); \
1188 		free(buf); \
1189 	} while (0)
1190 
1191 /**
1192  * igt_kmsg:
1193  * @format: printf-style format string with optional args
1194  *
1195  * Writes a message into the kernel log file (/dev/kmsg).
1196  */
1197 __attribute__((format(printf, 1, 2)))
1198 void igt_kmsg(const char *format, ...);
1199 #define KMSG_EMER	"<0>[IGT] "
1200 #define KMSG_ALERT	"<1>[IGT] "
1201 #define KMSG_CRIT	"<2>[IGT] "
1202 #define KMSG_ERR	"<3>[IGT] "
1203 #define KMSG_WARNING	"<4>[IGT] "
1204 #define KMSG_NOTICE	"<5>[IGT] "
1205 #define KMSG_INFO	"<6>[IGT] "
1206 #define KMSG_DEBUG	"<7>[IGT] "
1207 
1208 #define READ_ONCE(x) (*(volatile typeof(x) *)(&(x)))
1209 
1210 #define MSEC_PER_SEC (1000)
1211 #define USEC_PER_SEC (1000*MSEC_PER_SEC)
1212 #define NSEC_PER_SEC (1000*USEC_PER_SEC)
1213 
1214 #endif /* IGT_CORE_H */
1215