1 /*
2  * Copyright © 2007, 2011, 2013, 2014, 2015 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 #ifdef HAVE_LIBGEN_H
30 #include <libgen.h>
31 #endif
32 #include <stdio.h>
33 #include <fcntl.h>
34 #include <sys/stat.h>
35 #include <sys/ioctl.h>
36 #include <string.h>
37 #include <sys/mman.h>
38 #include <signal.h>
39 #include <pciaccess.h>
40 #include <stdlib.h>
41 #include <time.h>
42 #include <unistd.h>
43 #include <sys/poll.h>
44 #include <sys/wait.h>
45 #include <sys/resource.h>
46 #include <sys/time.h>
47 #include <sys/types.h>
48 #include <sys/syscall.h>
49 #include <sys/utsname.h>
50 #include <termios.h>
51 #include <assert.h>
52 #include <grp.h>
53 
54 #ifndef ANDROID
55 #include <proc/readproc.h>
56 #include <libudev.h>
57 #endif
58 
59 #include "drmtest.h"
60 #include "i915_drm.h"
61 #include "intel_chipset.h"
62 #include "igt_aux.h"
63 #include "igt_debugfs.h"
64 #include "igt_gt.h"
65 #include "igt_rand.h"
66 #include "igt_sysfs.h"
67 #include "config.h"
68 #include "intel_reg.h"
69 #include "ioctl_wrappers.h"
70 #include "igt_kms.h"
71 #include "igt_stats.h"
72 #include "igt_sysfs.h"
73 
74 #ifdef HAVE_LIBGEN_H
75 #include <libgen.h>   /* for dirname() */
76 #endif
77 
78 /**
79  * SECTION:igt_aux
80  * @short_description: Auxiliary libraries and support functions
81  * @title: aux
82  * @include: igt.h
83  *
84  * This library provides various auxiliary helper functions that don't really
85  * fit into any other topic.
86  */
87 
88 static struct __igt_sigiter_global {
89 	pid_t tid;
90 	timer_t timer;
91 	struct timespec offset;
92 	struct {
93 		long hit, miss;
94 		long ioctls, signals;
95 	} stat;
96 } __igt_sigiter;
97 
sigiter(int sig,siginfo_t * info,void * arg)98 static void sigiter(int sig, siginfo_t *info, void *arg)
99 {
100 	__igt_sigiter.stat.signals++;
101 }
102 
103 #if 0
104 #define SIG_ASSERT(expr) igt_assert(expr)
105 #else
106 #define SIG_ASSERT(expr)
107 #endif
108 
109 static int
sig_ioctl(int fd,unsigned long request,void * arg)110 sig_ioctl(int fd, unsigned long request, void *arg)
111 {
112 	struct itimerspec its;
113 	int ret;
114 
115 	SIG_ASSERT(__igt_sigiter.timer);
116 	SIG_ASSERT(__igt_sigiter.tid == gettid());
117 
118 	memset(&its, 0, sizeof(its));
119 	if (timer_settime(__igt_sigiter.timer, 0, &its, NULL)) {
120 		/* oops, we didn't undo the interrupter (i.e. !unwound abort) */
121 		igt_ioctl = drmIoctl;
122 		return drmIoctl(fd, request, arg);
123 	}
124 
125 	its.it_value = __igt_sigiter.offset;
126 	do {
127 		long serial;
128 
129 		__igt_sigiter.stat.ioctls++;
130 
131 		ret = 0;
132 		serial = __igt_sigiter.stat.signals;
133 		igt_assert(timer_settime(__igt_sigiter.timer, 0, &its, NULL) == 0);
134 		if (ioctl(fd, request, arg))
135 			ret = errno;
136 		if (__igt_sigiter.stat.signals == serial)
137 			__igt_sigiter.stat.miss++;
138 		if (ret == 0)
139 			break;
140 
141 		if (ret == EINTR) {
142 			__igt_sigiter.stat.hit++;
143 
144 			its.it_value.tv_sec *= 2;
145 			its.it_value.tv_nsec *= 2;
146 			while (its.it_value.tv_nsec >= NSEC_PER_SEC) {
147 				its.it_value.tv_nsec -= NSEC_PER_SEC;
148 				its.it_value.tv_sec += 1;
149 			}
150 
151 			SIG_ASSERT(its.it_value.tv_nsec >= 0);
152 			SIG_ASSERT(its.it_value.tv_sec >= 0);
153 		}
154 	} while (ret == EAGAIN || ret == EINTR);
155 
156 	memset(&its, 0, sizeof(its));
157 	timer_settime(__igt_sigiter.timer, 0, &its, NULL);
158 
159 	errno = ret;
160 	return ret ? -1 : 0;
161 }
162 
igt_sigiter_start(struct __igt_sigiter * iter,bool enable)163 static bool igt_sigiter_start(struct __igt_sigiter *iter, bool enable)
164 {
165 	/* Note that until we can automatically clean up on failed/skipped
166 	 * tests, we cannot assume the state of the igt_ioctl indirection.
167 	 */
168 	SIG_ASSERT(igt_ioctl == drmIoctl);
169 	igt_ioctl = drmIoctl;
170 
171 	if (enable) {
172 		struct timespec start, end;
173 		struct sigevent sev;
174 		struct sigaction act;
175 		struct itimerspec its;
176 
177 		igt_ioctl = sig_ioctl;
178 		__igt_sigiter.tid = gettid();
179 
180 		memset(&sev, 0, sizeof(sev));
181 		sev.sigev_notify = SIGEV_SIGNAL | SIGEV_THREAD_ID;
182 		sev.sigev_notify_thread_id = __igt_sigiter.tid;
183 		sev.sigev_signo = SIGRTMIN;
184 		igt_assert(timer_create(CLOCK_MONOTONIC, &sev, &__igt_sigiter.timer) == 0);
185 
186 		memset(&its, 0, sizeof(its));
187 		igt_assert(timer_settime(__igt_sigiter.timer, 0, &its, NULL) == 0);
188 
189 		memset(&act, 0, sizeof(act));
190 		act.sa_sigaction = sigiter;
191 		act.sa_flags = SA_SIGINFO;
192 		igt_assert(sigaction(SIGRTMIN, &act, NULL) == 0);
193 
194 		/* Try to find the approximate delay required to skip over
195 		 * the timer_setttime and into the following ioctl() to try
196 		 * and avoid the timer firing before we enter the drmIoctl.
197 		 */
198 		igt_assert(clock_gettime(CLOCK_MONOTONIC, &start) == 0);
199 		igt_assert(timer_settime(__igt_sigiter.timer, 0, &its, NULL) == 0);
200 		igt_assert(clock_gettime(CLOCK_MONOTONIC, &end) == 0);
201 
202 		__igt_sigiter.offset.tv_sec = end.tv_sec - start.tv_sec;
203 		__igt_sigiter.offset.tv_nsec = end.tv_nsec - start.tv_nsec;
204 		if (__igt_sigiter.offset.tv_nsec < 0) {
205 			__igt_sigiter.offset.tv_nsec += NSEC_PER_SEC;
206 			__igt_sigiter.offset.tv_sec -= 1;
207 		}
208 		if (__igt_sigiter.offset.tv_sec < 0) {
209 			__igt_sigiter.offset.tv_nsec = 0;
210 			__igt_sigiter.offset.tv_sec = 0;
211 		}
212 		igt_assert(__igt_sigiter.offset.tv_sec == 0);
213 
214 		igt_debug("Initial delay for interruption: %ld.%09lds\n",
215 			  __igt_sigiter.offset.tv_sec,
216 			  __igt_sigiter.offset.tv_nsec);
217 	}
218 
219 	return true;
220 }
221 
igt_sigiter_stop(struct __igt_sigiter * iter,bool enable)222 static bool igt_sigiter_stop(struct __igt_sigiter *iter, bool enable)
223 {
224 	if (enable) {
225 		struct sigaction act;
226 
227 		SIG_ASSERT(igt_ioctl == sig_ioctl);
228 		SIG_ASSERT(__igt_sigiter.tid == gettid());
229 		igt_ioctl = drmIoctl;
230 
231 		timer_delete(__igt_sigiter.timer);
232 
233 		memset(&act, 0, sizeof(act));
234 		act.sa_handler = SIG_IGN;
235 		sigaction(SIGRTMIN, &act, NULL);
236 
237 		memset(&__igt_sigiter, 0, sizeof(__igt_sigiter));
238 	}
239 
240 	memset(iter, 0, sizeof(*iter));
241 	return false;
242 }
243 
__igt_sigiter_continue(struct __igt_sigiter * iter,bool enable)244 bool __igt_sigiter_continue(struct __igt_sigiter *iter, bool enable)
245 {
246 	if (iter->pass++ == 0)
247 		return igt_sigiter_start(iter, enable);
248 
249 	/* If nothing reported SIGINT, nothing will on the next pass, so
250 	 * give up! Also give up if everything is now executing faster
251 	 * than current sigtimer.
252 	 */
253 	if (__igt_sigiter.stat.hit == 0 ||
254 	    __igt_sigiter.stat.miss == __igt_sigiter.stat.ioctls)
255 		return igt_sigiter_stop(iter, enable);
256 
257 	igt_debug("%s: pass %d, missed %ld/%ld\n",
258 		  __func__, iter->pass - 1,
259 		  __igt_sigiter.stat.miss,
260 		  __igt_sigiter.stat.ioctls);
261 
262 	SIG_ASSERT(igt_ioctl == sig_ioctl);
263 	SIG_ASSERT(__igt_sigiter.timer);
264 
265 	__igt_sigiter.offset.tv_sec *= 2;
266 	__igt_sigiter.offset.tv_nsec *= 2;
267 	while (__igt_sigiter.offset.tv_nsec >= NSEC_PER_SEC) {
268 		__igt_sigiter.offset.tv_nsec -= NSEC_PER_SEC;
269 		__igt_sigiter.offset.tv_sec += 1;
270 	}
271 	SIG_ASSERT(__igt_sigiter.offset.tv_nsec >= 0);
272 	SIG_ASSERT(__igt_sigiter.offset.tv_sec >= 0);
273 
274 	memset(&__igt_sigiter.stat, 0, sizeof(__igt_sigiter.stat));
275 	return true;
276 }
277 
278 static struct igt_helper_process signal_helper;
279 long long int sig_stat;
signal_helper_process(pid_t pid)280 static void __attribute__((noreturn)) signal_helper_process(pid_t pid)
281 {
282 	/* Interrupt the parent process at 500Hz, just to be annoying */
283 	while (1) {
284 		usleep(1000 * 1000 / 500);
285 		if (kill(pid, SIGCONT)) /* Parent has died, so must we. */
286 			exit(0);
287 	}
288 }
289 
sig_handler(int i)290 static void sig_handler(int i)
291 {
292 	sig_stat++;
293 }
294 
295 /**
296  * igt_fork_signal_helper:
297  *
298  * Fork a child process using #igt_fork_helper to interrupt the parent process
299  * with a SIGCONT signal at regular quick intervals. The corresponding dummy
300  * signal handler is installed in the parent process.
301  *
302  * This is useful to exercise ioctl error paths, at least where those can be
303  * exercises by interrupting blocking waits, like stalling for the gpu. This
304  * helper can also be used from children spawned with #igt_fork.
305  *
306  * In tests with subtests this function can be called outside of failure
307  * catching code blocks like #igt_fixture or #igt_subtest.
308  *
309  * Note that this just spews signals at the current process unconditionally and
310  * hence incurs quite a bit of overhead. For a more focused approach, with less
311  * overhead, look at the #igt_while_interruptible code block macro.
312  */
igt_fork_signal_helper(void)313 void igt_fork_signal_helper(void)
314 {
315 	if (igt_only_list_subtests())
316 		return;
317 
318 	/* We pick SIGCONT as it is a "safe" signal - if we send SIGCONT to
319 	 * an unexpecting process it spuriously wakes up and does nothing.
320 	 * Most other signals (e.g. SIGUSR1) cause the process to die if they
321 	 * are not handled. This is an issue in case the sighandler is not
322 	 * inherited correctly (or if there is a race in the inheritance
323 	 * and we send the signal at exactly the wrong time).
324 	 */
325 	signal(SIGCONT, sig_handler);
326 	setpgrp(); /* define a new process group for the tests */
327 
328 	igt_fork_helper(&signal_helper) {
329 		setpgrp(); /* Escape from the test process group */
330 
331 		/* Pass along the test process group identifier,
332 		 * negative pid => send signal to everyone in the group.
333 		 */
334 		signal_helper_process(-getppid());
335 	}
336 }
337 
338 /**
339  * igt_stop_signal_helper:
340  *
341  * Stops the child process spawned with igt_fork_signal_helper() again.
342  *
343  * In tests with subtests this function can be called outside of failure
344  * catching code blocks like #igt_fixture or #igt_subtest.
345  */
igt_stop_signal_helper(void)346 void igt_stop_signal_helper(void)
347 {
348 	if (igt_only_list_subtests())
349 		return;
350 
351 	igt_stop_helper(&signal_helper);
352 
353 	sig_stat = 0;
354 }
355 
356 /**
357  * igt_suspend_signal_helper:
358  *
359  * Suspends the child process spawned with igt_fork_signal_helper(). This
360  * should be called before a critical section of code that has difficulty to
361  * make progress if interrupted frequently, like the clone() syscall called
362  * from a largish executable. igt_resume_signal_helper() must be called after
363  * the critical section to restart interruptions for the test.
364  */
igt_suspend_signal_helper(void)365 void igt_suspend_signal_helper(void)
366 {
367 	int status;
368 
369 	if (!signal_helper.running)
370 		return;
371 
372 	kill(signal_helper.pid, SIGSTOP);
373 	while (waitpid(signal_helper.pid, &status, WUNTRACED) == -1 &&
374 	       errno == EINTR)
375 		;
376 }
377 
378 /**
379  * igt_resume_signal_helper:
380  *
381  * Resumes the child process spawned with igt_fork_signal_helper().
382  *
383  * This should be paired with igt_suspend_signal_helper() and called after the
384  * problematic code sensitive to signals.
385  */
igt_resume_signal_helper(void)386 void igt_resume_signal_helper(void)
387 {
388 	if (!signal_helper.running)
389 		return;
390 
391 	kill(signal_helper.pid, SIGCONT);
392 }
393 
394 static struct igt_helper_process shrink_helper;
shrink_helper_process(int fd,pid_t pid)395 static void __attribute__((noreturn)) shrink_helper_process(int fd, pid_t pid)
396 {
397 	while (1) {
398 		igt_drop_caches_set(fd, DROP_SHRINK_ALL);
399 		usleep(1000 * 1000 / 50);
400 		if (kill(pid, 0)) /* Parent has died, so must we. */
401 			exit(0);
402 	}
403 }
404 
405 /**
406  * igt_fork_shrink_helper:
407  *
408  * Fork a child process using #igt_fork_helper to force all available objects
409  * to be paged out (via i915_gem_shrink()).
410  *
411  * This is useful to exercise swapping paths, without requiring us to hit swap.
412  *
413  * This should only be used from an igt_fixture.
414  */
igt_fork_shrink_helper(int drm_fd)415 void igt_fork_shrink_helper(int drm_fd)
416 {
417 	assert(!igt_only_list_subtests());
418 	igt_require(igt_drop_caches_has(drm_fd, DROP_SHRINK_ALL));
419 	igt_fork_helper(&shrink_helper)
420 		shrink_helper_process(drm_fd, getppid());
421 }
422 
423 /**
424  * igt_stop_shrink_helper:
425  *
426  * Stops the child process spawned with igt_fork_shrink_helper().
427  */
igt_stop_shrink_helper(void)428 void igt_stop_shrink_helper(void)
429 {
430 	igt_stop_helper(&shrink_helper);
431 }
432 
433 #ifndef ANDROID
434 
show_kernel_stack(pid_t pid)435 static void show_kernel_stack(pid_t pid)
436 {
437 	char buf[80], *str;
438 	int dir;
439 
440 	snprintf(buf, sizeof(buf), "/proc/%d", pid);
441 	dir = open(buf, O_RDONLY);
442 	if (dir < 0)
443 		return;
444 
445 	str = igt_sysfs_get(dir, "stack");
446 	if (str) {
447 		igt_debug("Kernel stack for pid %d:\n%s\n", pid, str);
448 		free(str);
449 	}
450 
451 	close(dir);
452 }
453 
454 static struct igt_helper_process hang_detector;
455 static void __attribute__((noreturn))
hang_detector_process(int fd,pid_t pid,dev_t rdev)456 hang_detector_process(int fd, pid_t pid, dev_t rdev)
457 {
458 	struct udev_monitor *mon =
459 		udev_monitor_new_from_netlink(udev_new(), "kernel");
460 	struct pollfd pfd;
461 	int ret;
462 
463 	udev_monitor_filter_add_match_subsystem_devtype(mon, "drm", NULL);
464 	udev_monitor_enable_receiving(mon);
465 
466 	pfd.fd = udev_monitor_get_fd(mon);
467 	pfd.events = POLLIN;
468 
469 	while ((ret = poll(&pfd, 1, 2000)) >= 0) {
470 		struct udev_device *dev;
471 		dev_t devnum;
472 
473 		if (kill(pid, 0)) { /* Parent has died, so must we. */
474 			igt_warn("Parent died without killing its children (%s)\n",
475 				 __func__);
476 			break;
477 		}
478 
479 		dev = NULL;
480 		if (ret > 0)
481 			dev = udev_monitor_receive_device(mon);
482 		if (dev == NULL)
483 			continue;
484 
485 		devnum = udev_device_get_devnum(dev);
486 		if (memcmp(&rdev, &devnum, sizeof(dev_t)) == 0) {
487 			const char *str;
488 
489 			str = udev_device_get_property_value(dev, "ERROR");
490 			if (str && atoi(str) == 1) {
491 				igt_debugfs_dump(fd, "i915_error_state");
492 				show_kernel_stack(pid);
493 				kill(pid, SIGIO);
494 			}
495 		}
496 
497 		udev_device_unref(dev);
498 	}
499 
500 	exit(0);
501 }
502 
sig_abort(int sig)503 static void sig_abort(int sig)
504 {
505 	errno = 0; /* inside a signal, last errno reporting is confusing */
506 	igt_assert(!"GPU hung");
507 }
508 
igt_fork_hang_detector(int fd)509 void igt_fork_hang_detector(int fd)
510 {
511 	struct stat st;
512 
513 	igt_assert(fstat(fd, &st) == 0);
514 
515 	/*
516 	 * Disable per-engine reset to force an error uevent. We don't
517 	 * expect to get any hangs whilst the detector is enabled (if we do
518 	 * they are a test failure!) and so the loss of per-engine reset
519 	 * functionality is not an issue.
520 	 */
521 	igt_assert(igt_sysfs_set_parameter
522 		   (fd, "reset", "%d", 1 /* only global reset */));
523 
524 	signal(SIGIO, sig_abort);
525 	igt_fork_helper(&hang_detector)
526 		hang_detector_process(fd, getppid(), st.st_rdev);
527 }
528 
igt_stop_hang_detector(void)529 void igt_stop_hang_detector(void)
530 {
531 	igt_stop_helper(&hang_detector);
532 }
533 #endif
534 
535 /**
536  * igt_check_boolean_env_var:
537  * @env_var: environment variable name
538  * @default_value: default value for the environment variable
539  *
540  * This function should be used to parse boolean environment variable options.
541  *
542  * Returns:
543  * The boolean value of the environment variable @env_var as decoded by atoi()
544  * if it is set and @default_value if the variable is not set.
545  */
igt_check_boolean_env_var(const char * env_var,bool default_value)546 bool igt_check_boolean_env_var(const char *env_var, bool default_value)
547 {
548 	char *val;
549 
550 	val = getenv(env_var);
551 	if (!val)
552 		return default_value;
553 
554 	return atoi(val) != 0;
555 }
556 
557 /**
558  * igt_aub_dump_enabled:
559  *
560  * Returns:
561  * True if AUB dumping is enabled with IGT_DUMP_AUB=1 in the environment, false
562  * otherwise.
563  */
igt_aub_dump_enabled(void)564 bool igt_aub_dump_enabled(void)
565 {
566 	static int dump_aub = -1;
567 
568 	if (dump_aub == -1)
569 		dump_aub = igt_check_boolean_env_var("IGT_DUMP_AUB", false);
570 
571 	return dump_aub;
572 }
573 
574 /* other helpers */
575 /**
576  * igt_exchange_int:
577  * @array: pointer to the array of integers
578  * @i: first position
579  * @j: second position
580  *
581  * Exchanges the two values at array indices @i and @j. Useful as an exchange
582  * function for igt_permute_array().
583  */
igt_exchange_int(void * array,unsigned i,unsigned j)584 void igt_exchange_int(void *array, unsigned i, unsigned j)
585 {
586 	int *int_arr, tmp;
587 	int_arr = array;
588 
589 	tmp = int_arr[i];
590 	int_arr[i] = int_arr[j];
591 	int_arr[j] = tmp;
592 }
593 
594 /**
595  * igt_exchange_int64:
596  * @array: pointer to the array of int64_t
597  * @i: first position
598  * @j: second position
599  *
600  * Exchanges the two values at array indices @i and @j. Useful as an exchange
601  * function for igt_permute_array().
602  */
igt_exchange_int64(void * array,unsigned i,unsigned j)603 void igt_exchange_int64(void *array, unsigned i, unsigned j)
604 {
605 	int64_t *a = array;
606 
607 	igt_swap(a[i], a[j]);
608 }
609 
610 /**
611  * igt_permute_array:
612  * @array: pointer to array
613  * @size: size of the array
614  * @exchange_func: function to exchange array elements
615  *
616  * This function randomly permutes the array using random() as the PRNG source.
617  * The @exchange_func function is called to exchange two elements in the array
618  * when needed.
619  */
igt_permute_array(void * array,unsigned size,void (* exchange_func)(void * array,unsigned i,unsigned j))620 void igt_permute_array(void *array, unsigned size,
621                        void (*exchange_func)(void *array,
622                                              unsigned i,
623                                              unsigned j))
624 {
625 	int i;
626 
627 	for (i = size - 1; i > 0; i--) {
628 		/* yes, not perfectly uniform, who cares */
629 		long l = hars_petruska_f54_1_random_unsafe() % (i +1);
630 		if (i != l)
631 			exchange_func(array, i, l);
632 	}
633 }
634 
635 __attribute__((format(printf, 1, 2)))
igt_interactive_info(const char * format,...)636 static void igt_interactive_info(const char *format, ...)
637 {
638 	va_list args;
639 
640 	if (!isatty(STDERR_FILENO) || __igt_plain_output) {
641 		errno = 0; /* otherwise would be either ENOTTY or EBADF */
642 		return;
643 	}
644 
645 	if (igt_log_level > IGT_LOG_INFO)
646 		return;
647 
648 	va_start(args, format);
649 	vfprintf(stderr, format, args);
650 	va_end(args);
651 }
652 
653 
654 /**
655  * igt_progress:
656  * @header: header string to prepend to the progress indicator
657  * @i: work processed thus far
658  * @total: total amount of work
659  *
660  * This function draws a progress indicator, which is useful for running
661  * long-winded tests manually on the console. To avoid spamming log files in
662  * automated runs the progress indicator is suppressed when not running on a
663  * terminal.
664  */
igt_progress(const char * header,uint64_t i,uint64_t total)665 void igt_progress(const char *header, uint64_t i, uint64_t total)
666 {
667 	int divider = 200;
668 
669 	if (i+1 >= total) {
670 		igt_interactive_info("\r%s100%%\n", header);
671 		return;
672 	}
673 
674 	if (total / 200 == 0)
675 		divider = 1;
676 
677 	/* only bother updating about every 0.5% */
678 	if (i % (total / divider) == 0)
679 		igt_interactive_info("\r%s%3llu%%", header,
680 				     (long long unsigned)i * 100 / total);
681 }
682 
683 /**
684  * igt_print_activity:
685  *
686  * Print a '.' to indicate activity. This is printed without a newline and
687  * only if output is to a terminal.
688  */
igt_print_activity(void)689 void igt_print_activity(void)
690 {
691 	igt_interactive_info(".");
692 }
693 
694 static int autoresume_delay;
695 
696 static const char *suspend_state_name[] = {
697 	[SUSPEND_STATE_FREEZE] = "freeze",
698 	[SUSPEND_STATE_STANDBY] = "standby",
699 	[SUSPEND_STATE_MEM] = "mem",
700 	[SUSPEND_STATE_DISK] = "disk",
701 };
702 
703 static const char *suspend_test_name[] = {
704 	[SUSPEND_TEST_NONE] = "none",
705 	[SUSPEND_TEST_FREEZER] = "freezer",
706 	[SUSPEND_TEST_DEVICES] = "devices",
707 	[SUSPEND_TEST_PLATFORM] = "platform",
708 	[SUSPEND_TEST_PROCESSORS] = "processors",
709 	[SUSPEND_TEST_CORE] = "core",
710 };
711 
get_suspend_test(int power_dir)712 static enum igt_suspend_test get_suspend_test(int power_dir)
713 {
714 	char *test_line;
715 	char *test_name;
716 	enum igt_suspend_test test;
717 
718 	if (faccessat(power_dir, "pm_test", R_OK, 0))
719 		return SUSPEND_TEST_NONE;
720 
721 	igt_assert((test_line = igt_sysfs_get(power_dir, "pm_test")));
722 	for (test_name = strtok(test_line, " "); test_name;
723 	     test_name = strtok(NULL, " "))
724 		if (test_name[0] == '[') {
725 			test_name[strlen(test_name) - 1] = '\0';
726 			test_name++;
727 			break;
728 		}
729 
730 	if (!test_name) {
731 	  	free(test_line);
732 		return SUSPEND_TEST_NONE;
733 	}
734 
735 	for (test = SUSPEND_TEST_NONE; test < SUSPEND_TEST_NUM; test++)
736 		if (strcmp(suspend_test_name[test], test_name) == 0)
737 			break;
738 
739 	igt_assert(test < SUSPEND_TEST_NUM);
740 
741 	free(test_line);
742 	return test;
743 }
744 
set_suspend_test(int power_dir,enum igt_suspend_test test)745 static void set_suspend_test(int power_dir, enum igt_suspend_test test)
746 {
747 	igt_assert(test < SUSPEND_TEST_NUM);
748 
749 	if (faccessat(power_dir, "pm_test", W_OK, 0)) {
750 		igt_require(test == SUSPEND_TEST_NONE);
751 		return;
752 	}
753 
754 	igt_assert(igt_sysfs_set(power_dir, "pm_test", suspend_test_name[test]));
755 }
756 
757 #define SQUELCH ">/dev/null 2>&1"
758 
suspend_via_rtcwake(enum igt_suspend_state state)759 static void suspend_via_rtcwake(enum igt_suspend_state state)
760 {
761 	char cmd[128];
762 	int delay, ret;
763 
764 	igt_assert(state < SUSPEND_STATE_NUM);
765 
766 	delay = igt_get_autoresume_delay(state);
767 
768 	/*
769 	 * Skip if rtcwake would fail for a reason not related to the kernel's
770 	 * suspend functionality.
771 	 */
772 	snprintf(cmd, sizeof(cmd), "rtcwake -n -s %d -m %s " SQUELCH,
773 		 delay, suspend_state_name[state]);
774 	ret = igt_system(cmd);
775 	igt_require_f(ret == 0, "rtcwake test failed with %i\n"
776 		     "This failure could mean that something is wrong with "
777 		     "the rtcwake tool or how your distro is set up.\n",
778 		      ret);
779 
780 	snprintf(cmd, sizeof(cmd), "rtcwake -s %d -m %s ",
781 		 delay, suspend_state_name[state]);
782 	ret = igt_system(cmd);
783 	if (ret) {
784 		const char *path = "suspend_stats";
785 		char *info;
786 		int dir;
787 
788 		igt_warn("rtcwake failed with %i\n"
789 			 "Check dmesg for further details.\n",
790 			 ret);
791 
792 		dir = open(igt_debugfs_mount(), O_RDONLY);
793 		info = igt_sysfs_get(dir, path);
794 		close(dir);
795 		if (info) {
796 			igt_debug("%s:\n%s\n", path, info);
797 			free(info);
798 		}
799 	}
800 	igt_assert_eq(ret, 0);
801 }
802 
suspend_via_sysfs(int power_dir,enum igt_suspend_state state)803 static void suspend_via_sysfs(int power_dir, enum igt_suspend_state state)
804 {
805 	igt_assert(state < SUSPEND_STATE_NUM);
806 	igt_assert(igt_sysfs_set(power_dir, "state",
807 				 suspend_state_name[state]));
808 }
809 
get_supported_suspend_states(int power_dir)810 static uint32_t get_supported_suspend_states(int power_dir)
811 {
812 	char *states;
813 	char *state_name;
814 	uint32_t state_mask;
815 
816 	igt_assert((states = igt_sysfs_get(power_dir, "state")));
817 	state_mask = 0;
818 	for (state_name = strtok(states, " "); state_name;
819 	     state_name = strtok(NULL, " ")) {
820 		enum igt_suspend_state state;
821 
822 		for (state = SUSPEND_STATE_FREEZE; state < SUSPEND_STATE_NUM;
823 		     state++)
824 			if (strcmp(state_name, suspend_state_name[state]) == 0)
825 				break;
826 		igt_assert(state < SUSPEND_STATE_NUM);
827 		state_mask |= 1 << state;
828 	}
829 
830 	free(states);
831 
832 	return state_mask;
833 }
834 
835 /**
836  * igt_system_suspend_autoresume:
837  * @state: an #igt_suspend_state, the target suspend state
838  * @test: an #igt_suspend_test, test point at which to complete the suspend
839  *	  cycle
840  *
841  * Execute a system suspend cycle targeting the given @state optionally
842  * completing the cycle at the given @test point and automaically wake up
843  * again. Waking up is either achieved using the RTC wake-up alarm for a full
844  * suspend cycle or a kernel timer for a suspend test cycle. The kernel timer
845  * delay for a test cycle can be configured by the suspend.pm_test_delay
846  * kernel parameter (5 sec by default).
847  *
848  * #SUSPEND_TEST_NONE specifies a full suspend cycle.
849  * The #SUSPEND_TEST_FREEZER..#SUSPEND_TEST_CORE test points can make it
850  * possible to collect error logs in case a full suspend cycle would prevent
851  * this by hanging the machine, or they can provide an idea of the faulty
852  * component by comparing fail/no-fail results at different test points.
853  *
854  * This is very handy for implementing any kind of suspend/resume test.
855  */
igt_system_suspend_autoresume(enum igt_suspend_state state,enum igt_suspend_test test)856 void igt_system_suspend_autoresume(enum igt_suspend_state state,
857 				   enum igt_suspend_test test)
858 {
859 	int power_dir;
860 	enum igt_suspend_test orig_test;
861 
862 	/* FIXME: Simulation doesn't like suspend/resume, and not even a lighter
863 	 * approach using /sys/power/pm_test to just test our driver's callbacks
864 	 * seems to fare better. We need to investigate what's going on. */
865 	igt_skip_on_simulation();
866 
867 	igt_require((power_dir = open("/sys/power", O_RDONLY)) >= 0);
868 	igt_require(get_supported_suspend_states(power_dir) & (1 << state));
869 	igt_require(test == SUSPEND_TEST_NONE ||
870 		    faccessat(power_dir, "pm_test", R_OK | W_OK, 0) == 0);
871 
872 	orig_test = get_suspend_test(power_dir);
873 	set_suspend_test(power_dir, test);
874 
875 	if (test == SUSPEND_TEST_NONE)
876 		suspend_via_rtcwake(state);
877 	else
878 		suspend_via_sysfs(power_dir, state);
879 
880 	set_suspend_test(power_dir, orig_test);
881 	close(power_dir);
882 }
883 
884 static int original_autoresume_delay;
885 
igt_restore_autoresume_delay(int sig)886 static void igt_restore_autoresume_delay(int sig)
887 {
888 	int delay_fd;
889 	char delay_str[10];
890 
891 	igt_require((delay_fd = open("/sys/module/suspend/parameters/pm_test_delay",
892 				    O_WRONLY)) >= 0);
893 
894 	snprintf(delay_str, sizeof(delay_str), "%d", original_autoresume_delay);
895 	igt_require(write(delay_fd, delay_str, strlen(delay_str)));
896 
897 	close(delay_fd);
898 }
899 
900 /**
901  * igt_set_autoresume_delay:
902  * @delay_secs: The delay in seconds before resuming the system
903  *
904  * Sets how long we wait to resume the system after suspending it, using the
905  * suspend.pm_test_delay variable. On exit, the original delay value is
906  * restored.
907  */
igt_set_autoresume_delay(int delay_secs)908 void igt_set_autoresume_delay(int delay_secs)
909 {
910 	int delay_fd;
911 	char delay_str[10];
912 
913 	igt_skip_on_simulation();
914 
915 	delay_fd = open("/sys/module/suspend/parameters/pm_test_delay", O_RDWR);
916 
917 	if (delay_fd >= 0) {
918 		if (!original_autoresume_delay) {
919 			igt_require(read(delay_fd, delay_str,
920 					 sizeof(delay_str)));
921 			original_autoresume_delay = atoi(delay_str);
922 			igt_install_exit_handler(igt_restore_autoresume_delay);
923 		}
924 
925 		snprintf(delay_str, sizeof(delay_str), "%d", delay_secs);
926 		igt_require(write(delay_fd, delay_str, strlen(delay_str)));
927 
928 		close(delay_fd);
929 	}
930 
931 	autoresume_delay = delay_secs;
932 }
933 
934 /**
935  * igt_get_autoresume_delay:
936  * @state: an #igt_suspend_state, the target suspend state
937  *
938  * Retrieves how long we wait to resume the system after suspending it.
939  * This can either be set through igt_set_autoresume_delay or be a default
940  * value that depends on the suspend state.
941  *
942  * Returns: The autoresume delay, in seconds.
943  */
igt_get_autoresume_delay(enum igt_suspend_state state)944 int igt_get_autoresume_delay(enum igt_suspend_state state)
945 {
946 	int delay;
947 
948 	if (autoresume_delay)
949 		delay = autoresume_delay;
950 	else
951 		delay = state == SUSPEND_STATE_DISK ? 30 : 15;
952 
953 	return delay;
954 }
955 
956 /**
957  * igt_drop_root:
958  *
959  * Drop root privileges and make sure it actually worked. Useful for tests
960  * which need to check security constraints. Note that this should only be
961  * called from manually forked processes, since the lack of root privileges
962  * will wreak havoc with the automatic cleanup handlers.
963  */
igt_drop_root(void)964 void igt_drop_root(void)
965 {
966 	igt_assert_eq(getuid(), 0);
967 
968 	igt_assert_eq(setgroups(0, NULL), 0);
969 	igt_assert_eq(setgid(2), 0);
970 	igt_assert_eq(setuid(2), 0);
971 
972 	igt_assert_eq(getgroups(0, NULL), 0);
973 	igt_assert_eq(getgid(), 2);
974 	igt_assert_eq(getuid(), 2);
975 }
976 
977 /**
978  * igt_debug_wait_for_keypress:
979  * @var: var lookup to to enable this wait
980  *
981  * Waits for a key press when run interactively and when the corresponding debug
982  * var is set in the --interactive-debug=$var variable. Multiple keys
983  * can be specified as a comma-separated list or alternatively "all" if a wait
984  * should happen for all cases.
985  *
986  * When not connected to a terminal interactive_debug is ignored
987  * and execution immediately continues.
988  *
989  * This is useful for display tests where under certain situation manual
990  * inspection of the display is useful. Or when running a testcase in the
991  * background.
992  */
igt_debug_wait_for_keypress(const char * var)993 void igt_debug_wait_for_keypress(const char *var)
994 {
995 	struct termios oldt, newt;
996 
997 	if (!isatty(STDIN_FILENO)) {
998 		errno = 0; /* otherwise would be either ENOTTY or EBADF */
999 		return;
1000 	}
1001 
1002 	if (!igt_interactive_debug)
1003 		return;
1004 
1005 	if (!strstr(igt_interactive_debug, var) &&
1006 	    !strstr(igt_interactive_debug, "all"))
1007 		return;
1008 
1009 	igt_info("Press any key to continue ...\n");
1010 
1011 	tcgetattr ( STDIN_FILENO, &oldt );
1012 	newt = oldt;
1013 	newt.c_lflag &= ~( ICANON | ECHO );
1014 	tcsetattr ( STDIN_FILENO, TCSANOW, &newt );
1015 	getchar();
1016 	tcsetattr ( STDIN_FILENO, TCSANOW, &oldt );
1017 }
1018 
1019 /**
1020  * igt_debug_manual_check:
1021  * @var: var lookup to to enable this wait
1022  * @expected: message to be printed as expected behaviour before wait for keys Y/n
1023  *
1024  * Waits for a key press when run interactively and when the corresponding debug
1025  * var is set in the --interactive-debug=$var variable. Multiple vars
1026  * can be specified as a comma-separated list or alternatively "all" if a wait
1027  * should happen for all cases.
1028  *
1029  * This is useful for display tests where under certain situation manual
1030  * inspection of the display is useful. Or when running a testcase in the
1031  * background.
1032  *
1033  * When not connected to a terminal interactive_debug is ignored
1034  * and execution immediately continues. For this reason by default this function
1035  * returns true. It returns false only when N/n is pressed indicating the
1036  * user isn't seeing what was expected.
1037  *
1038  * Force test fail when N/n is pressed.
1039  */
igt_debug_manual_check(const char * var,const char * expected)1040 void igt_debug_manual_check(const char *var, const char *expected)
1041 {
1042 	struct termios oldt, newt;
1043 	char key;
1044 
1045 	if (!isatty(STDIN_FILENO)) {
1046 		errno = 0; /* otherwise would be either ENOTTY or EBADF */
1047 		return;
1048 	}
1049 
1050 	if (!igt_interactive_debug)
1051 		return;
1052 
1053 	if (!strstr(igt_interactive_debug, var) &&
1054 	    !strstr(igt_interactive_debug, "all"))
1055 		return;
1056 
1057 	igt_info("Is %s [Y/n]", expected);
1058 
1059 	tcgetattr ( STDIN_FILENO, &oldt );
1060 	newt = oldt;
1061 	newt.c_lflag &= ~ICANON;
1062 	tcsetattr ( STDIN_FILENO, TCSANOW, &newt );
1063 	key = getchar();
1064 	tcsetattr ( STDIN_FILENO, TCSANOW, &oldt );
1065 
1066 	igt_info("\n");
1067 
1068 	igt_assert(key != 'n' && key != 'N');
1069 }
1070 
1071 /**
1072  * igt_lock_mem:
1073  * @size: the amount of memory to lock into RAM, in MB
1074  *
1075  * Allocate @size MB of memory and lock it into RAM. This releases any
1076  * previously locked memory.
1077  *
1078  * Use #igt_unlock_mem to release the currently locked memory.
1079  */
1080 static char *locked_mem;
1081 static size_t locked_size;
1082 
igt_lock_mem(size_t size)1083 void igt_lock_mem(size_t size)
1084 {
1085 	long pagesize = sysconf(_SC_PAGESIZE);
1086 	size_t i;
1087 	int ret;
1088 
1089 	if (size == 0) {
1090 		return;
1091 	}
1092 
1093 	if (locked_mem) {
1094 		igt_unlock_mem();
1095 		igt_warn("Unlocking previously locked memory.\n");
1096 	}
1097 
1098 	locked_size = size * 1024 * 1024;
1099 
1100 	locked_mem = malloc(locked_size);
1101 	igt_require_f(locked_mem,
1102 		      "Could not malloc %zdMiB for locking.\n", size);
1103 
1104 	/* write into each page to ensure it is allocated */
1105 	for (i = 0; i < locked_size; i += pagesize)
1106 		locked_mem[i] = i;
1107 
1108 	ret = mlock(locked_mem, locked_size);
1109 	igt_assert_f(ret == 0, "Could not mlock %zdMiB.\n", size);
1110 }
1111 
1112 /**
1113  * igt_unlock_mem:
1114  *
1115  * Release and free the RAM used by #igt_lock_mem.
1116  */
igt_unlock_mem(void)1117 void igt_unlock_mem(void)
1118 {
1119 	if (!locked_mem)
1120 		return;
1121 
1122 	munlock(locked_mem, locked_size);
1123 
1124 	free(locked_mem);
1125 	locked_mem = NULL;
1126 }
1127 
1128 
1129 #define MODULE_PARAM_DIR "/sys/module/i915/parameters/"
1130 #define PARAM_NAME_MAX_SZ 32
1131 #define PARAM_VALUE_MAX_SZ 16
1132 #define PARAM_FILE_PATH_MAX_SZ (strlen(MODULE_PARAM_DIR) + PARAM_NAME_MAX_SZ)
1133 
1134 struct module_param_data {
1135 	char name[PARAM_NAME_MAX_SZ];
1136 	char original_value[PARAM_VALUE_MAX_SZ];
1137 
1138 	struct module_param_data *next;
1139 };
1140 struct module_param_data *module_params = NULL;
1141 
igt_module_param_exit_handler(int sig)1142 static void igt_module_param_exit_handler(int sig)
1143 {
1144 	const size_t dir_len = strlen(MODULE_PARAM_DIR);
1145 	char file_path[PARAM_FILE_PATH_MAX_SZ];
1146 	struct module_param_data *data;
1147 	int fd;
1148 
1149 	/* We don't need to assert string sizes on this function since they were
1150 	 * already checked before being stored on the lists. Besides,
1151 	 * igt_assert() is not AS-Safe. */
1152 	strcpy(file_path, MODULE_PARAM_DIR);
1153 
1154 	for (data = module_params; data != NULL; data = data->next) {
1155 		strcpy(file_path + dir_len, data->name);
1156 
1157 		fd = open(file_path, O_RDWR);
1158 		if (fd >= 0) {
1159 			int size = strlen (data->original_value);
1160 
1161 			if (size != write(fd, data->original_value, size)) {
1162 				const char msg[] = "WARNING: Module parameters "
1163 					"may not have been reset to their "
1164 					"original values\n";
1165 				assert(write(STDERR_FILENO, msg, sizeof(msg))
1166 				       == sizeof(msg));
1167 			}
1168 
1169 			close(fd);
1170 		}
1171 	}
1172 	/* free() is not AS-Safe, so we can't call it here. */
1173 }
1174 
1175 /**
1176  * igt_save_module_param:
1177  * @name: name of the i915.ko module parameter
1178  * @file_path: full sysfs file path for the parameter
1179  *
1180  * Reads the current value of an i915.ko module parameter, saves it on an array,
1181  * then installs an exit handler to restore it when the program exits.
1182  *
1183  * It is safe to call this function multiple times for the same parameter.
1184  *
1185  * Notice that this function is called by igt_set_module_param(), so that one -
1186  * or one of its wrappers - is the only function the test programs need to call.
1187  */
igt_save_module_param(const char * name,const char * file_path)1188 static void igt_save_module_param(const char *name, const char *file_path)
1189 {
1190 	struct module_param_data *data;
1191 	size_t n;
1192 	int fd;
1193 
1194 	/* Check if this parameter is already saved. */
1195 	for (data = module_params; data != NULL; data = data->next)
1196 		if (strncmp(data->name, name, PARAM_NAME_MAX_SZ) == 0)
1197 			return;
1198 
1199 	if (!module_params)
1200 		igt_install_exit_handler(igt_module_param_exit_handler);
1201 
1202 	data = calloc(1, sizeof (*data));
1203 	igt_assert(data);
1204 
1205 	strncpy(data->name, name, PARAM_NAME_MAX_SZ - 1);
1206 
1207 	fd = open(file_path, O_RDONLY);
1208 	igt_assert(fd >= 0);
1209 
1210 	n = read(fd, data->original_value, PARAM_VALUE_MAX_SZ);
1211 	igt_assert_f(n > 0 && n < PARAM_VALUE_MAX_SZ,
1212 		     "Need to increase PARAM_VALUE_MAX_SZ\n");
1213 
1214 	igt_assert(close(fd) == 0);
1215 
1216 	data->next = module_params;
1217 	module_params = data;
1218 }
1219 
1220 /**
1221  * igt_set_module_param:
1222  * @name: i915.ko parameter name
1223  * @val: i915.ko parameter value
1224  *
1225  * This function sets the desired value for the given i915.ko parameter. It also
1226  * takes care of saving and restoring the values that were already set before
1227  * the test was run.
1228  *
1229  * Please consider using igt_set_module_param_int() for the integer and bool
1230  * parameters.
1231  */
igt_set_module_param(const char * name,const char * val)1232 void igt_set_module_param(const char *name, const char *val)
1233 {
1234 	char file_path[PARAM_FILE_PATH_MAX_SZ];
1235 	size_t len = strlen(val);
1236 	int fd;
1237 
1238 	igt_assert_f(strlen(name) < PARAM_NAME_MAX_SZ,
1239 		     "Need to increase PARAM_NAME_MAX_SZ\n");
1240 	strcpy(file_path, MODULE_PARAM_DIR);
1241 	strcpy(file_path + strlen(MODULE_PARAM_DIR), name);
1242 
1243 	igt_save_module_param(name, file_path);
1244 
1245 	fd = open(file_path, O_RDWR);
1246 	igt_assert(write(fd, val, len) == len);
1247 	igt_assert(close(fd) == 0);
1248 }
1249 
1250 /**
1251  * igt_set_module_param_int:
1252  * @name: i915.ko parameter name
1253  * @val: i915.ko parameter value
1254  *
1255  * This is a wrapper for igt_set_module_param() that takes an integer instead of
1256  * a string. Please see igt_set_module_param().
1257  */
igt_set_module_param_int(const char * name,int val)1258 void igt_set_module_param_int(const char *name, int val)
1259 {
1260 	char str[PARAM_VALUE_MAX_SZ];
1261 	int n;
1262 
1263 	n = snprintf(str, PARAM_VALUE_MAX_SZ, "%d\n", val);
1264 	igt_assert_f(n < PARAM_VALUE_MAX_SZ,
1265 		     "Need to increase PARAM_VALUE_MAX_SZ\n");
1266 
1267 	igt_set_module_param(name, str);
1268 }
1269 
1270 #ifndef ANDROID
1271 
1272 /**
1273  * igt_is_process_running:
1274  * @comm: Name of process in the form found in /proc/pid/comm (limited to 15
1275  * chars)
1276  *
1277  * Returns: true in case the process has been found, false otherwise.
1278  *
1279  * This function checks in the process table for an entry with the name @comm.
1280  */
igt_is_process_running(const char * comm)1281 int igt_is_process_running(const char *comm)
1282 {
1283 	PROCTAB *proc;
1284 	proc_t *proc_info;
1285 	bool found = false;
1286 
1287 	proc = openproc(PROC_FILLCOM | PROC_FILLSTAT);
1288 	igt_assert(proc != NULL);
1289 
1290 	while ((proc_info = readproc(proc, NULL))) {
1291 		if (!strncasecmp(proc_info->cmd, comm, sizeof(proc_info->cmd))) {
1292 			freeproc(proc_info);
1293 			found = true;
1294 			break;
1295 		}
1296 		freeproc(proc_info);
1297 	}
1298 
1299 	closeproc(proc);
1300 	return found;
1301 }
1302 
1303 /**
1304  * igt_terminate_process:
1305  * @sig: Signal to send
1306  * @comm: Name of process in the form found in /proc/pid/comm (limited to 15
1307  * chars)
1308  *
1309  * Returns: 0 in case the process is not found running or the signal has been
1310  * sent successfully or -errno otherwise.
1311  *
1312  * This function sends the signal @sig for a process found in process table
1313  * with name @comm.
1314  */
igt_terminate_process(int sig,const char * comm)1315 int igt_terminate_process(int sig, const char *comm)
1316 {
1317 	PROCTAB *proc;
1318 	proc_t *proc_info;
1319 	int err = 0;
1320 
1321 	proc = openproc(PROC_FILLCOM | PROC_FILLSTAT | PROC_FILLARG);
1322 	igt_assert(proc != NULL);
1323 
1324 	while ((proc_info = readproc(proc, NULL))) {
1325 		if (!strncasecmp(proc_info->cmd, comm, sizeof(proc_info->cmd))) {
1326 
1327 			if (kill(proc_info->tid, sig) < 0)
1328 				err = -errno;
1329 
1330 			freeproc(proc_info);
1331 			break;
1332 		}
1333 		freeproc(proc_info);
1334 	}
1335 
1336 	closeproc(proc);
1337 	return err;
1338 }
1339 
1340 struct pinfo {
1341 	pid_t pid;
1342 	const char *comm;
1343 	const char *fn;
1344 };
1345 
1346 static void
__igt_show_stat(struct pinfo * info)1347 __igt_show_stat(struct pinfo *info)
1348 {
1349 	const char *comm, *fn;
1350 	const char *type = "";
1351 	struct stat st;
1352 
1353 	pid_t pid = info->pid;
1354 	igt_assert((comm = info->comm));
1355 	igt_assert((fn = info->fn));
1356 
1357 	if (lstat(fn, &st) == -1)
1358 		return;
1359 
1360 	igt_info("%20.20s ", comm);
1361 	igt_info("%10d ", pid);
1362 
1363 	switch (st.st_mode & S_IFMT) {
1364 	case S_IFBLK:
1365 		type = "block";
1366 		break;
1367 	case S_IFCHR:
1368 		type = "character";
1369 		break;
1370 	case S_IFDIR:
1371 		type = "directory";
1372 		break;
1373 	case S_IFIFO:
1374 		type = "FIFO/pipe";
1375 		break;
1376 	case S_IFLNK:
1377 		type = "symlink";
1378 		break;
1379 	case S_IFREG:
1380 		type = "file";
1381 		break;
1382 	case S_IFSOCK:
1383 		type = "socket";
1384 		break;
1385 	default:
1386 		type = "unknown?";
1387 		break;
1388 	}
1389 	igt_info("%20.20s ", type);
1390 
1391 	igt_info("%10ld%10ld ", (long) st.st_uid, (long) st.st_gid);
1392 
1393 	igt_info("%15lld bytes ", (long long) st.st_size);
1394 	igt_info("%30.30s", fn);
1395 	igt_info("\n");
1396 }
1397 
1398 static void
igt_show_stat_header(void)1399 igt_show_stat_header(void)
1400 {
1401 	igt_info("%20.20s%11.11s%21.21s%11.11s%10.10s%22.22s%31.31s\n",
1402 		"COMM", "PID", "Type", "UID", "GID", "Size", "Filename");
1403 }
1404 
1405 static void
igt_show_stat(proc_t * info,int * state,const char * fn)1406 igt_show_stat(proc_t *info, int *state, const char *fn)
1407 {
1408 	struct pinfo p = { .pid = info->tid, .comm = info->cmd, .fn = fn };
1409 
1410 	if (!*state)
1411 		igt_show_stat_header();
1412 
1413 	__igt_show_stat(&p);
1414 	++*state;
1415 }
1416 
1417 static void
__igt_lsof_fds(proc_t * proc_info,int * state,char * proc_path,const char * dir)1418 __igt_lsof_fds(proc_t *proc_info, int *state, char *proc_path, const char *dir)
1419 {
1420 	struct dirent *d;
1421 	struct stat st;
1422 	char path[PATH_MAX];
1423 	char *fd_lnk;
1424 
1425 	/* default fds or kernel threads */
1426 	const char *default_fds[] = { "/dev/pts", "/dev/null" };
1427 
1428 	DIR *dp = opendir(proc_path);
1429 	igt_assert(dp);
1430 again:
1431 	while ((d = readdir(dp))) {
1432 		char *copy_fd_lnk;
1433 		char *dirn;
1434 
1435 		unsigned int i;
1436 		ssize_t read;
1437 
1438 		if (*d->d_name == '.')
1439 			continue;
1440 
1441 		memset(path, 0, sizeof(path));
1442 		snprintf(path, sizeof(path), "%s/%s", proc_path, d->d_name);
1443 
1444 		if (lstat(path, &st) == -1)
1445 			continue;
1446 
1447 		fd_lnk = malloc(st.st_size + 1);
1448 
1449 		igt_assert((read = readlink(path, fd_lnk, st.st_size + 1)));
1450 		fd_lnk[read] = '\0';
1451 
1452 		for (i = 0; i < ARRAY_SIZE(default_fds); ++i) {
1453 			if (!strncmp(default_fds[i],
1454 				     fd_lnk,
1455 				     strlen(default_fds[i]))) {
1456 				free(fd_lnk);
1457 				goto again;
1458 			}
1459 		}
1460 
1461 		copy_fd_lnk = strdup(fd_lnk);
1462 		dirn = dirname(copy_fd_lnk);
1463 
1464 		if (!strncmp(dir, dirn, strlen(dir)))
1465 			igt_show_stat(proc_info, state, fd_lnk);
1466 
1467 		free(copy_fd_lnk);
1468 		free(fd_lnk);
1469 	}
1470 
1471 	closedir(dp);
1472 }
1473 
1474 /*
1475  * This functions verifies, for each process running on the machine, if the
1476  * current working directory or the fds matches the one supplied in dir.
1477  */
1478 static void
__igt_lsof(const char * dir)1479 __igt_lsof(const char *dir)
1480 {
1481 	PROCTAB *proc;
1482 	proc_t *proc_info;
1483 
1484 	char path[30];
1485 	char *name_lnk;
1486 	struct stat st;
1487 	int state = 0;
1488 
1489 	proc = openproc(PROC_FILLCOM | PROC_FILLSTAT | PROC_FILLARG);
1490 	igt_assert(proc != NULL);
1491 
1492 	while ((proc_info = readproc(proc, NULL))) {
1493 		ssize_t read;
1494 
1495 		/* check current working directory */
1496 		memset(path, 0, sizeof(path));
1497 		snprintf(path, sizeof(path), "/proc/%d/cwd", proc_info->tid);
1498 
1499 		if (stat(path, &st) == -1)
1500 			continue;
1501 
1502 		name_lnk = malloc(st.st_size + 1);
1503 
1504 		igt_assert((read = readlink(path, name_lnk, st.st_size + 1)));
1505 		name_lnk[read] = '\0';
1506 
1507 		if (!strncmp(dir, name_lnk, strlen(dir)))
1508 			igt_show_stat(proc_info, &state, name_lnk);
1509 
1510 		/* check also fd, seems that lsof(8) doesn't look here */
1511 		memset(path, 0, sizeof(path));
1512 		snprintf(path, sizeof(path), "/proc/%d/fd", proc_info->tid);
1513 
1514 		__igt_lsof_fds(proc_info, &state, path, dir);
1515 
1516 		free(name_lnk);
1517 		freeproc(proc_info);
1518 	}
1519 
1520 	closeproc(proc);
1521 }
1522 
1523 /**
1524  * igt_lsof: Lists information about files opened by processes.
1525  * @dpath: Path to look under. A valid directory is required.
1526  *
1527  * This function mimics (a restrictive form of) lsof(8), but also shows
1528  * information about opened fds.
1529  */
1530 void
igt_lsof(const char * dpath)1531 igt_lsof(const char *dpath)
1532 {
1533 	struct stat st;
1534 	size_t len = strlen(dpath);
1535 	char *sanitized;
1536 
1537 	if (stat(dpath, &st) == -1)
1538 		return;
1539 
1540 	if (!S_ISDIR(st.st_mode)) {
1541 		igt_warn("%s not a directory!\n", dpath);
1542 		return;
1543 	}
1544 
1545 	sanitized = strdup(dpath);
1546 	/* remove last '/' so matching is easier */
1547 	if (len > 1 && dpath[len - 1] == '/')
1548 		sanitized[len - 1] = '\0';
1549 
1550 	__igt_lsof(sanitized);
1551 
1552 	free(sanitized);
1553 }
1554 #endif
1555 
1556 static struct igt_siglatency {
1557 	timer_t timer;
1558 	struct timespec target;
1559 	struct sigaction oldact;
1560 	struct igt_mean mean;
1561 
1562 	int sig;
1563 } igt_siglatency;
1564 
delay(void)1565 static long delay(void)
1566 {
1567 	return hars_petruska_f54_1_random_unsafe() % (NSEC_PER_SEC / 1000);
1568 }
1569 
elapsed(const struct timespec * now,const struct timespec * last)1570 static double elapsed(const struct timespec *now, const struct timespec *last)
1571 {
1572 	double nsecs;
1573 
1574 	nsecs = now->tv_nsec - last ->tv_nsec;
1575 	nsecs += 1e9*(now->tv_sec - last->tv_sec);
1576 
1577 	return nsecs;
1578 }
1579 
siglatency(int sig,siginfo_t * info,void * arg)1580 static void siglatency(int sig, siginfo_t *info, void *arg)
1581 {
1582 	struct itimerspec its;
1583 
1584 	clock_gettime(CLOCK_MONOTONIC, &its.it_value);
1585 	if (info)
1586 		igt_mean_add(&igt_siglatency.mean,
1587 			     elapsed(&its.it_value, &igt_siglatency.target));
1588 	igt_siglatency.target = its.it_value;
1589 
1590 	its.it_value.tv_nsec += 100 * 1000;
1591 	its.it_value.tv_nsec += delay();
1592 	if (its.it_value.tv_nsec >= NSEC_PER_SEC) {
1593 		its.it_value.tv_nsec -= NSEC_PER_SEC;
1594 		its.it_value.tv_sec += 1;
1595 	}
1596 	its.it_interval.tv_sec = its.it_interval.tv_nsec = 0;
1597 	timer_settime(igt_siglatency.timer, TIMER_ABSTIME, &its, NULL);
1598 }
1599 
igt_start_siglatency(int sig)1600 void igt_start_siglatency(int sig)
1601 {
1602 	struct sigevent sev;
1603 	struct sigaction act;
1604 
1605 	if (sig <= 0)
1606 		sig = SIGRTMIN;
1607 
1608 	if (igt_siglatency.sig)
1609 		(void)igt_stop_siglatency(NULL);
1610 	igt_assert(igt_siglatency.sig == 0);
1611 	igt_siglatency.sig = sig;
1612 
1613 	memset(&sev, 0, sizeof(sev));
1614 	sev.sigev_notify = SIGEV_SIGNAL | SIGEV_THREAD_ID;
1615 	sev.sigev_notify_thread_id = gettid();
1616 	sev.sigev_signo = sig;
1617 	timer_create(CLOCK_MONOTONIC, &sev, &igt_siglatency.timer);
1618 
1619 	memset(&act, 0, sizeof(act));
1620 	act.sa_sigaction = siglatency;
1621 	sigaction(sig, &act, &igt_siglatency.oldact);
1622 
1623 	siglatency(sig, NULL, NULL);
1624 }
1625 
igt_stop_siglatency(struct igt_mean * result)1626 double igt_stop_siglatency(struct igt_mean *result)
1627 {
1628 	double mean = igt_mean_get(&igt_siglatency.mean);
1629 
1630 	if (result)
1631 		*result = igt_siglatency.mean;
1632 
1633 	sigaction(igt_siglatency.sig, &igt_siglatency.oldact, NULL);
1634 	timer_delete(igt_siglatency.timer);
1635 	memset(&igt_siglatency, 0, sizeof(igt_siglatency));
1636 
1637 	return mean;
1638 }
1639 
igt_allow_unlimited_files(void)1640 bool igt_allow_unlimited_files(void)
1641 {
1642 	struct rlimit rlim;
1643 	unsigned nofile_rlim = 1024*1024;
1644 
1645 	FILE *file = fopen("/proc/sys/fs/nr_open", "r");
1646 	if (file) {
1647 		igt_assert(fscanf(file, "%u", &nofile_rlim) == 1);
1648 		igt_info("System limit for open files is %u\n", nofile_rlim);
1649 		fclose(file);
1650 	}
1651 
1652 	if (getrlimit(RLIMIT_NOFILE, &rlim))
1653 		return false;
1654 
1655 	rlim.rlim_cur = nofile_rlim;
1656 	rlim.rlim_max = nofile_rlim;
1657 	return setrlimit(RLIMIT_NOFILE, &rlim) == 0;
1658 }
1659 
1660 /**
1661  * vfs_file_max: report maximum number of files
1662  *
1663  * Get the global system-wide maximum of open files the kernel allows,
1664  * by reading /proc/sys/fs/file-max. Fails the current subtest if
1665  * reading the file fails, and returns a suitable best guess if it
1666  * cannot be opened.
1667  *
1668  * Returns: System-wide maximum of open files, or a best effort guess.
1669  */
vfs_file_max(void)1670 uint64_t vfs_file_max(void)
1671 {
1672 	static long long unsigned max;
1673 	if (max == 0) {
1674 		FILE *file = fopen("/proc/sys/fs/file-max", "r");
1675 		max = 80000;
1676 		if (file) {
1677 			igt_assert(fscanf(file, "%llu", &max) == 1);
1678 			fclose(file);
1679 		}
1680 	}
1681 	return max;
1682 }
1683