ad91c657dd06018044a32f56336e6f49ba442c3f
[platform/upstream/intel-gpu-tools.git] / lib / drmtest.c
1 /*
2  * Copyright © 2007, 2011, 2013 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 #define _GNU_SOURCE
30 #include <stdio.h>
31 #include <fcntl.h>
32 #include <sys/stat.h>
33 #include <sys/ioctl.h>
34 #include <string.h>
35 #include <sys/mman.h>
36 #include <signal.h>
37 #include <pciaccess.h>
38 #include <math.h>
39 #include <getopt.h>
40 #include <stdlib.h>
41 #include <linux/kd.h>
42 #include <unistd.h>
43 #include <sys/wait.h>
44 #include "drm_fourcc.h"
45
46 #include "drmtest.h"
47 #include "i915_drm.h"
48 #include "intel_chipset.h"
49 #include "intel_gpu_tools.h"
50
51 /* This file contains a bunch of wrapper functions to directly use gem ioctls.
52  * Mostly useful to write kernel tests. */
53
54 drm_intel_bo *
55 gem_handle_to_libdrm_bo(drm_intel_bufmgr *bufmgr, int fd, const char *name, uint32_t handle)
56 {
57         struct drm_gem_flink flink;
58         int ret;
59         drm_intel_bo *bo;
60
61         flink.handle = handle;
62         ret = ioctl(fd, DRM_IOCTL_GEM_FLINK, &flink);
63         igt_assert(ret == 0);
64
65         bo = drm_intel_bo_gem_create_from_name(bufmgr, name, flink.name);
66         igt_assert(bo);
67
68         return bo;
69 }
70
71 static int
72 is_intel(int fd)
73 {
74         struct drm_i915_getparam gp;
75         int devid;
76
77         gp.param = I915_PARAM_CHIPSET_ID;
78         gp.value = &devid;
79
80         if (ioctl(fd, DRM_IOCTL_I915_GETPARAM, &gp, sizeof(gp)))
81                 return 0;
82
83         return IS_INTEL(devid);
84 }
85
86 bool gem_uses_aliasing_ppgtt(int fd)
87 {
88         struct drm_i915_getparam gp;
89         int val;
90
91         gp.param = 18; /* HAS_ALIASING_PPGTT */
92         gp.value = &val;
93
94         if (ioctl(fd, DRM_IOCTL_I915_GETPARAM, &gp, sizeof(gp)))
95                 return 0;
96
97         return val;
98 }
99
100 int gem_available_fences(int fd)
101 {
102         struct drm_i915_getparam gp;
103         int val;
104
105         gp.param = I915_PARAM_NUM_FENCES_AVAIL;
106         gp.value = &val;
107
108         if (ioctl(fd, DRM_IOCTL_I915_GETPARAM, &gp, sizeof(gp)))
109                 return 0;
110
111         return val;
112 }
113
114
115 #define LOCAL_I915_EXEC_VEBOX   (4 << 0)
116 /* Ensure the gpu is idle by launching a nop execbuf and stalling for it. */
117 void gem_quiescent_gpu(int fd)
118 {
119         uint32_t batch[2] = {MI_BATCH_BUFFER_END, 0};
120         uint32_t handle;
121         struct drm_i915_gem_execbuffer2 execbuf;
122         struct drm_i915_gem_exec_object2 gem_exec[1];
123
124         handle = gem_create(fd, 4096);
125         gem_write(fd, handle, 0, batch, sizeof(batch));
126
127         gem_exec[0].handle = handle;
128         gem_exec[0].relocation_count = 0;
129         gem_exec[0].relocs_ptr = 0;
130         gem_exec[0].alignment = 0;
131         gem_exec[0].offset = 0;
132         gem_exec[0].flags = 0;
133         gem_exec[0].rsvd1 = 0;
134         gem_exec[0].rsvd2 = 0;
135
136         execbuf.buffers_ptr = (uintptr_t)gem_exec;
137         execbuf.buffer_count = 1;
138         execbuf.batch_start_offset = 0;
139         execbuf.batch_len = 8;
140         execbuf.cliprects_ptr = 0;
141         execbuf.num_cliprects = 0;
142         execbuf.DR1 = 0;
143         execbuf.DR4 = 0;
144         execbuf.flags = 0;
145         i915_execbuffer2_set_context_id(execbuf, 0);
146         execbuf.rsvd2 = 0;
147
148         do_ioctl(fd, DRM_IOCTL_I915_GEM_EXECBUFFER2, &execbuf);
149
150         if (gem_has_blt(fd)) {
151                 execbuf.flags = I915_EXEC_BLT;
152                 do_ioctl(fd, DRM_IOCTL_I915_GEM_EXECBUFFER2, &execbuf);
153         }
154
155         if (gem_has_bsd(fd)) {
156                 execbuf.flags = I915_EXEC_BSD;
157                 do_ioctl(fd, DRM_IOCTL_I915_GEM_EXECBUFFER2, &execbuf);
158         }
159
160         if (gem_has_vebox(fd)) {
161                 execbuf.flags = LOCAL_I915_EXEC_VEBOX;
162                 do_ioctl(fd, DRM_IOCTL_I915_GEM_EXECBUFFER2, &execbuf);
163         }
164
165         gem_sync(fd, handle);
166 }
167
168 /**
169  * drm_get_card() - get an intel card number for use in /dev or /sys
170  *
171  * @master: -1 not a master, 0 don't care, 1 is the master
172  *
173  * returns -1 on error
174  */
175 int drm_get_card(void)
176 {
177         char *name;
178         int i, fd;
179
180         for (i = 0; i < 16; i++) {
181                 int ret;
182
183                 ret = asprintf(&name, "/dev/dri/card%u", i);
184                 igt_assert(ret != -1);
185
186                 fd = open(name, O_RDWR);
187                 free(name);
188
189                 if (fd == -1)
190                         continue;
191
192                 if (!is_intel(fd))
193                         continue;
194
195                 close(fd);
196                 return i;
197         }
198
199         igt_skip("No intel gpu found\n");
200
201         return -1;
202 }
203
204 /** Open the first DRM device we can find, searching up to 16 device nodes */
205 static int __drm_open_any(void)
206 {
207         char *name;
208         int ret, fd;
209
210         ret = asprintf(&name, "/dev/dri/card%d", drm_get_card());
211         if (ret == -1)
212                 return -1;
213
214         fd = open(name, O_RDWR);
215         free(name);
216
217         if (!is_intel(fd)) {
218                 close(fd);
219                 fd = -1;
220         }
221
222         return fd;
223 }
224
225 static void quiescent_gpu_at_exit(int sig)
226 {
227         int fd;
228
229         fd = __drm_open_any();
230         if (fd >= 0) {
231                 gem_quiescent_gpu(fd);
232                 close(fd);
233         }
234 }
235
236 int drm_open_any(void)
237 {
238         static int open_count;
239         int fd = __drm_open_any();
240
241         igt_require(fd >= 0);
242
243         if (__sync_fetch_and_add(&open_count, 1))
244                 return fd;
245
246         gem_quiescent_gpu(fd);
247         igt_install_exit_handler(quiescent_gpu_at_exit);
248
249         return fd;
250 }
251
252 void gem_set_tiling(int fd, uint32_t handle, int tiling, int stride)
253 {
254         struct drm_i915_gem_set_tiling st;
255         int ret;
256
257         memset(&st, 0, sizeof(st));
258         do {
259                 st.handle = handle;
260                 st.tiling_mode = tiling;
261                 st.stride = tiling ? stride : 0;
262
263                 ret = ioctl(fd, DRM_IOCTL_I915_GEM_SET_TILING, &st);
264         } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
265         igt_assert(ret == 0);
266         igt_assert(st.tiling_mode == tiling);
267 }
268
269 bool gem_has_enable_ring(int fd,int param)
270 {
271         drm_i915_getparam_t gp;
272         int ret, tmp;
273         memset(&gp, 0, sizeof(gp));
274
275         gp.value = &tmp;
276         gp.param = param;
277
278         ret = drmIoctl(fd, DRM_IOCTL_I915_GETPARAM, &gp);
279
280         if ((ret == 0) && (*gp.value > 0))
281                 return true;
282         else
283                 return false;
284 }
285
286 bool gem_has_bsd(int fd)
287 {
288
289         return gem_has_enable_ring(fd,I915_PARAM_HAS_BSD);
290 }
291
292 bool gem_has_blt(int fd)
293 {
294
295         return gem_has_enable_ring(fd,I915_PARAM_HAS_BLT);
296 }
297
298 #define LOCAL_I915_PARAM_HAS_VEBOX 22
299 bool gem_has_vebox(int fd)
300 {
301
302         return gem_has_enable_ring(fd,LOCAL_I915_PARAM_HAS_VEBOX);
303 }
304
305 int gem_get_num_rings(int fd)
306 {
307         int num_rings = 1;      /* render ring is always available */
308
309         if (gem_has_bsd(fd))
310                 num_rings++;
311         else
312                 goto skip;
313
314         if (gem_has_blt(fd))
315                 num_rings++;
316         else
317                 goto skip;
318
319         if (gem_has_vebox(fd))
320                 num_rings++;
321         else
322                 goto skip;
323
324
325 skip:
326         return num_rings;
327 }
328
329 struct local_drm_i915_gem_caching {
330         uint32_t handle;
331         uint32_t caching;
332 };
333
334 #define LOCAL_DRM_I915_GEM_SET_CACHEING    0x2f
335 #define LOCAL_DRM_I915_GEM_GET_CACHEING    0x30
336 #define LOCAL_DRM_IOCTL_I915_GEM_SET_CACHEING \
337         DRM_IOW(DRM_COMMAND_BASE + LOCAL_DRM_I915_GEM_SET_CACHEING, struct local_drm_i915_gem_caching)
338 #define LOCAL_DRM_IOCTL_I915_GEM_GET_CACHEING \
339         DRM_IOWR(DRM_COMMAND_BASE + LOCAL_DRM_I915_GEM_GET_CACHEING, struct local_drm_i915_gem_caching)
340
341 void gem_require_caching(int fd)
342 {
343         struct local_drm_i915_gem_caching arg;
344         int ret;
345
346         arg.handle = gem_create(fd, 4096);
347         igt_assert(arg.handle != 0);
348
349         arg.caching = 0;
350         ret = ioctl(fd, LOCAL_DRM_IOCTL_I915_GEM_SET_CACHEING, &arg);
351         gem_close(fd, arg.handle);
352
353         igt_require(ret == 0);
354 }
355
356 void gem_set_caching(int fd, uint32_t handle, int caching)
357 {
358         struct local_drm_i915_gem_caching arg;
359         int ret;
360
361         arg.handle = handle;
362         arg.caching = caching;
363         ret = ioctl(fd, LOCAL_DRM_IOCTL_I915_GEM_SET_CACHEING, &arg);
364
365         igt_assert(ret == 0 || (errno == ENOTTY || errno == EINVAL));
366         igt_require(ret == 0);
367 }
368
369 uint32_t gem_get_caching(int fd, uint32_t handle)
370 {
371         struct local_drm_i915_gem_caching arg;
372         int ret;
373
374         arg.handle = handle;
375         arg.caching = 0;
376         ret = ioctl(fd, LOCAL_DRM_IOCTL_I915_GEM_GET_CACHEING, &arg);
377         igt_assert(ret == 0);
378
379         return arg.caching;
380 }
381
382 uint32_t gem_open(int fd, uint32_t name)
383 {
384         struct drm_gem_open open_struct;
385         int ret;
386
387         open_struct.name = name;
388         ret = ioctl(fd, DRM_IOCTL_GEM_OPEN, &open_struct);
389         igt_assert(ret == 0);
390         igt_assert(open_struct.handle != 0);
391
392         return open_struct.handle;
393 }
394
395 uint32_t gem_flink(int fd, uint32_t handle)
396 {
397         struct drm_gem_flink flink;
398         int ret;
399
400         flink.handle = handle;
401         ret = ioctl(fd, DRM_IOCTL_GEM_FLINK, &flink);
402         igt_assert(ret == 0);
403
404         return flink.name;
405 }
406
407 void gem_close(int fd, uint32_t handle)
408 {
409         struct drm_gem_close close_bo;
410
411         close_bo.handle = handle;
412         do_ioctl(fd, DRM_IOCTL_GEM_CLOSE, &close_bo);
413 }
414
415 void gem_write(int fd, uint32_t handle, uint32_t offset, const void *buf, uint32_t size)
416 {
417         struct drm_i915_gem_pwrite gem_pwrite;
418
419         gem_pwrite.handle = handle;
420         gem_pwrite.offset = offset;
421         gem_pwrite.size = size;
422         gem_pwrite.data_ptr = (uintptr_t)buf;
423         do_ioctl(fd, DRM_IOCTL_I915_GEM_PWRITE, &gem_pwrite);
424 }
425
426 void gem_read(int fd, uint32_t handle, uint32_t offset, void *buf, uint32_t length)
427 {
428         struct drm_i915_gem_pread gem_pread;
429
430         gem_pread.handle = handle;
431         gem_pread.offset = offset;
432         gem_pread.size = length;
433         gem_pread.data_ptr = (uintptr_t)buf;
434         do_ioctl(fd, DRM_IOCTL_I915_GEM_PREAD, &gem_pread);
435 }
436
437 void gem_set_domain(int fd, uint32_t handle,
438                     uint32_t read_domains, uint32_t write_domain)
439 {
440         struct drm_i915_gem_set_domain set_domain;
441
442         set_domain.handle = handle;
443         set_domain.read_domains = read_domains;
444         set_domain.write_domain = write_domain;
445
446         do_ioctl(fd, DRM_IOCTL_I915_GEM_SET_DOMAIN, &set_domain);
447 }
448
449 void gem_sync(int fd, uint32_t handle)
450 {
451         gem_set_domain(fd, handle, I915_GEM_DOMAIN_GTT, I915_GEM_DOMAIN_GTT);
452 }
453
454 uint32_t gem_create(int fd, int size)
455 {
456         struct drm_i915_gem_create create;
457
458         create.handle = 0;
459         create.size = size;
460         do_ioctl(fd, DRM_IOCTL_I915_GEM_CREATE, &create);
461         igt_assert(create.handle);
462
463         return create.handle;
464 }
465
466 void *gem_mmap__gtt(int fd, uint32_t handle, int size, int prot)
467 {
468         struct drm_i915_gem_mmap_gtt mmap_arg;
469         void *ptr;
470
471         mmap_arg.handle = handle;
472         if (drmIoctl(fd, DRM_IOCTL_I915_GEM_MMAP_GTT, &mmap_arg))
473                 return NULL;
474
475         ptr = mmap64(0, size, prot, MAP_SHARED, fd, mmap_arg.offset);
476         if (ptr == MAP_FAILED)
477                 ptr = NULL;
478
479         return ptr;
480 }
481
482 void *gem_mmap__cpu(int fd, uint32_t handle, int size, int prot)
483 {
484         struct drm_i915_gem_mmap mmap_arg;
485
486         mmap_arg.handle = handle;
487         mmap_arg.offset = 0;
488         mmap_arg.size = size;
489         if (drmIoctl(fd, DRM_IOCTL_I915_GEM_MMAP, &mmap_arg))
490                 return NULL;
491
492         return (void *)(uintptr_t)mmap_arg.addr_ptr;
493 }
494
495 uint64_t gem_aperture_size(int fd)
496 {
497         struct drm_i915_gem_get_aperture aperture;
498
499         aperture.aper_size = 256*1024*1024;
500         do_ioctl(fd, DRM_IOCTL_I915_GEM_GET_APERTURE, &aperture);
501         return aperture.aper_size;
502 }
503
504 uint64_t gem_mappable_aperture_size(void)
505 {
506         struct pci_device *pci_dev;
507         int bar;
508         pci_dev = intel_get_pci_device();
509
510         if (intel_gen(pci_dev->device_id) < 3)
511                 bar = 0;
512         else
513                 bar = 2;
514
515         return pci_dev->regions[bar].size;
516 }
517
518 int gem_madvise(int fd, uint32_t handle, int state)
519 {
520         struct drm_i915_gem_madvise madv;
521
522         madv.handle = handle;
523         madv.madv = state;
524         madv.retained = 1;
525         do_ioctl(fd, DRM_IOCTL_I915_GEM_MADVISE, &madv);
526
527         return madv.retained;
528 }
529
530 uint32_t gem_context_create(int fd)
531 {
532         struct drm_i915_gem_context_create create;
533         int ret;
534
535         ret = drmIoctl(fd, DRM_IOCTL_I915_GEM_CONTEXT_CREATE, &create);
536         igt_require(ret == 0 || (errno != ENODEV && errno != EINVAL));
537         igt_assert(ret == 0);
538
539         return create.ctx_id;
540 }
541
542 /* prime */
543 int prime_handle_to_fd(int fd, uint32_t handle)
544 {
545         struct drm_prime_handle args;
546
547         args.handle = handle;
548         args.flags = DRM_CLOEXEC;
549         args.fd = -1;
550
551         do_ioctl(fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &args);
552
553         return args.fd;
554 }
555
556 uint32_t prime_fd_to_handle(int fd, int dma_buf_fd)
557 {
558         struct drm_prime_handle args;
559
560         args.fd = dma_buf_fd;
561         args.flags = 0;
562         args.handle = 0;
563
564         do_ioctl(fd, DRM_IOCTL_PRIME_FD_TO_HANDLE, &args);
565
566         return args.handle;
567 }
568
569 off_t prime_get_size(int dma_buf_fd)
570 {
571         off_t ret;
572         ret = lseek(dma_buf_fd, 0, SEEK_END);
573         igt_assert(ret >= 0 || errno == ESPIPE);
574         igt_require(ret >= 0);
575
576         return ret;
577 }
578
579 /* signal interrupt helpers */
580 static bool igt_only_list_subtests(void);
581
582 static pid_t signal_helper = -1;
583 long long int sig_stat;
584 static void __attribute__((noreturn)) signal_helper_process(pid_t pid)
585 {
586         /* Interrupt the parent process at 500Hz, just to be annoying */
587         while (1) {
588                 usleep(1000 * 1000 / 500);
589                 if (kill(pid, SIGUSR1)) /* Parent has died, so must we. */
590                         exit(0);
591         }
592 }
593
594 static void sig_handler(int i)
595 {
596         sig_stat++;
597 }
598
599 static void signal_helper_exit_handler(int sig)
600 {
601         igt_stop_signal_helper();
602 }
603
604 void igt_fork_signal_helper(void)
605 {
606         pid_t pid;
607         sighandler_t oldsig;
608
609         if (igt_only_list_subtests())
610                 return;
611
612         igt_install_exit_handler(signal_helper_exit_handler);
613
614         signal(SIGUSR1, sig_handler);
615         oldsig = signal(SIGQUIT, SIG_DFL);
616         pid = fork();
617         signal(SIGQUIT, oldsig);
618         if (pid == 0) {
619                 signal_helper_process(getppid());
620                 return;
621         }
622
623         signal_helper = pid;
624 }
625
626 void igt_stop_signal_helper(void)
627 {
628         int exitcode;
629
630         if (signal_helper != -1) {
631                 kill(signal_helper, SIGQUIT);
632                 wait(&exitcode);
633         } else
634                 return;
635
636 #if 0
637         if (sig_stat)
638                 fprintf(stdout, "signal handler called %llu times\n", sig_stat);
639 #endif
640
641         sig_stat = 0;
642         signal_helper = -1;
643 }
644
645 /* subtests helpers */
646 static bool list_subtests = false;
647 static char *run_single_subtest = NULL;
648 static const char *in_subtest = NULL;
649 static bool in_fixture = false;
650 static bool test_with_subtests = false;
651 static enum {
652         CONT = 0, SKIP, FAIL
653 } skip_subtests_henceforth = CONT;
654
655 bool __igt_fixture(void)
656 {
657         assert(!in_fixture);
658
659         if (igt_only_list_subtests())
660                 return false;
661
662         if (skip_subtests_henceforth)
663                 return false;
664
665         in_fixture = true;
666         return true;
667 }
668
669 void __igt_fixture_end(void)
670 {
671         assert(in_fixture);
672
673         in_fixture = false;
674         longjmp(igt_subtest_jmpbuf, 1);
675 }
676
677 static void print_usage(const char *command_str, const char *help_str,
678                         bool output_on_stderr)
679 {
680         FILE *f = output_on_stderr ? stderr : stdout;
681
682         fprintf(f, "Usage: %s [OPTIONS]\n"
683                    "  --list-subtests\n"
684                    "  --run-subtest <pattern>\n", command_str);
685         if (help_str)
686                 fprintf(f, "%s\n", help_str);
687 }
688
689 int igt_subtest_init_parse_opts(int argc, char **argv,
690                                 const char *extra_short_opts,
691                                 struct option *extra_long_opts,
692                                 const char *help_str,
693                                 igt_opt_handler_t extra_opt_handler)
694 {
695         int c, option_index = 0;
696         static struct option long_options[] = {
697                 {"list-subtests", 0, 0, 'l'},
698                 {"run-subtest", 1, 0, 'r'},
699                 {"help", 0, 0, 'h'},
700         };
701         const char *command_str;
702         char *short_opts;
703         struct option *combined_opts;
704         int extra_opt_count;
705         int all_opt_count;
706         int ret = 0;
707
708         test_with_subtests = true;
709
710         command_str = argv[0];
711         if (strrchr(command_str, '/'))
712                 command_str = strrchr(command_str, '/') + 1;
713
714         /* First calculate space for all passed-in extra long options */
715         all_opt_count = 0;
716         while (extra_long_opts && extra_long_opts[all_opt_count].name)
717                 all_opt_count++;
718         extra_opt_count = all_opt_count;
719
720         all_opt_count += ARRAY_SIZE(long_options);
721
722         combined_opts = malloc(all_opt_count * sizeof(*combined_opts));
723         memcpy(combined_opts, extra_long_opts,
724                extra_opt_count * sizeof(*combined_opts));
725
726         /* Copy the subtest long options (and the final NULL entry) */
727         memcpy(&combined_opts[extra_opt_count], long_options,
728                 ARRAY_SIZE(long_options) * sizeof(*combined_opts));
729
730         ret = asprintf(&short_opts, "%sh",
731                        extra_short_opts ? extra_short_opts : "");
732         assert(ret >= 0);
733
734         while ((c = getopt_long(argc, argv, short_opts, combined_opts,
735                                &option_index)) != -1) {
736                 switch(c) {
737                 case 'l':
738                         if (!run_single_subtest)
739                                 list_subtests = true;
740                         break;
741                 case 'r':
742                         if (!list_subtests)
743                                 run_single_subtest = strdup(optarg);
744                         break;
745                 case 'h':
746                         print_usage(command_str, help_str, false);
747                         ret = -2;
748                         goto out;
749                 case '?':
750                         if (opterr) {
751                                 print_usage(command_str, help_str, true);
752                                 ret = -1;
753                                 goto out;
754                         }
755                         /*
756                          * Just ignore the error, since the unknown argument
757                          * can be something the caller understands and will
758                          * parse by doing a second getopt scanning.
759                          */
760                         break;
761                 default:
762                         ret = extra_opt_handler(c, option_index);
763                         if (ret)
764                                 goto out;
765                 }
766         }
767
768 out:
769         return ret;
770 }
771
772 void igt_subtest_init(int argc, char **argv)
773 {
774         int ret;
775
776         /* supress getopt errors about unknown options */
777         opterr = 0;
778
779         ret = igt_subtest_init_parse_opts(argc, argv, NULL, NULL, NULL, NULL);
780         if (ret < 0)
781                 /* exit with no error for -h/--help */
782                 exit(ret == -2 ? 0 : ret);
783
784         /* reset opt parsing */
785         optind = 1;
786 }
787
788 /*
789  * Note: Testcases which use these helpers MUST NOT output anything to stdout
790  * outside of places protected by igt_run_subtest checks - the piglit
791  * runner adds every line to the subtest list.
792  */
793 bool __igt_run_subtest(const char *subtest_name)
794 {
795         assert(!in_subtest);
796         assert(!in_fixture);
797
798         if (list_subtests) {
799                 printf("%s\n", subtest_name);
800                 return false;
801         }
802
803         if (skip_subtests_henceforth) {
804                 printf("Subtest %s: %s\n", subtest_name,
805                        skip_subtests_henceforth == SKIP ?
806                        "SKIP" : "FAIL");
807                 return false;
808         }
809
810         if (!run_single_subtest) {
811                 return (in_subtest = subtest_name);
812         } else {
813                 if (strcmp(subtest_name, run_single_subtest) == 0)
814                         return (in_subtest = subtest_name);
815
816                 return false;
817         }
818 }
819
820 const char *igt_subtest_name(void)
821 {
822         return in_subtest;
823 }
824
825 static bool igt_only_list_subtests(void)
826 {
827         return list_subtests;
828 }
829
830 static bool skipped_one = false;
831 static bool succeeded_one = false;
832 static bool failed_one = false;
833 static int igt_exitcode;
834
835 static void exit_subtest(const char *) __attribute__((noreturn));
836 static void exit_subtest(const char *result)
837 {
838         printf("Subtest %s: %s\n", in_subtest, result);
839         in_subtest = NULL;
840         longjmp(igt_subtest_jmpbuf, 1);
841 }
842
843 void igt_skip(const char *f, ...)
844 {
845         va_list args;
846         skipped_one = true;
847
848         if (!igt_only_list_subtests()) {
849                 va_start(args, f);
850                 vprintf(f, args);
851                 va_end(args);
852         }
853
854         if (in_subtest) {
855                 exit_subtest("SKIP");
856         } else if (test_with_subtests) {
857                 skip_subtests_henceforth = SKIP;
858                 if (in_fixture)
859                         __igt_fixture_end();
860         } else {
861                 exit(77);
862         }
863 }
864
865 void __igt_skip_check(const char *file, const int line,
866                       const char *func, const char *check)
867 {
868         igt_skip("Test requirement not met in function %s, file %s:%i:\n"
869                  "Test requirement: (%s)\n",
870                  func, file, line, check);
871 }
872
873 void igt_success(void)
874 {
875         succeeded_one = true;
876         if (in_subtest)
877                 exit_subtest("SUCCESS");
878 }
879
880 void igt_fail(int exitcode)
881 {
882         assert(exitcode != 0 && exitcode != 77);
883
884         if (!failed_one)
885                 igt_exitcode = exitcode;
886
887         failed_one = true;
888
889         if (in_subtest)
890                 exit_subtest("FAIL");
891         else {
892                 assert(!test_with_subtests || in_fixture);
893
894                 if (in_fixture) {
895                         skip_subtests_henceforth = FAIL;
896                         __igt_fixture_end();
897                 }
898
899                 exit(exitcode);
900         }
901 }
902
903 static bool run_under_gdb(void)
904 {
905         char buf[1024];
906
907         sprintf(buf, "/proc/%d/exe", getppid());
908         return (readlink (buf, buf, sizeof (buf)) != -1 &&
909                 strncmp (basename (buf), "gdb", 3) == 0);
910 }
911
912 void __igt_fail_assert(int exitcode, const char *file,
913                        const int line, const char *func, const char *assertion)
914 {
915         printf("Test assertion failure function %s, file %s:%i:\n"
916                "Failed assertion: %s\n",
917                func, file, line, assertion);
918         if (run_under_gdb())
919                 abort();
920         igt_fail(exitcode);
921 }
922
923 void igt_exit(void)
924 {
925         if (igt_only_list_subtests())
926                 exit(0);
927
928         if (!test_with_subtests)
929                 exit(0);
930
931         /* Calling this without calling one of the above is a failure */
932         assert(skipped_one || succeeded_one || failed_one);
933
934         if (failed_one)
935                 exit(igt_exitcode);
936         else if (succeeded_one)
937                 exit(0);
938         else
939                 exit(77);
940 }
941
942 static bool env_set(const char *env_var, bool default_value)
943 {
944         char *val;
945
946         val = getenv(env_var);
947         if (!val)
948                 return default_value;
949
950         return atoi(val) != 0;
951 }
952
953 bool igt_run_in_simulation(void)
954 {
955         static int simulation = -1;
956
957         if (simulation == -1)
958                 simulation = env_set("INTEL_SIMULATION", false);
959
960         return simulation;
961 }
962
963 /**
964  * igt_skip_on_simulation - skip tests when INTEL_SIMULATION env war is set
965  *
966  * Skip the test when running on simulation (and that's relevant only when
967  * we're not in the mode where we list the subtests).
968  *
969  * This function is subtest aware (since it uses igt_skip) and so can be used to
970  * skip specific subtests or all subsequent subtests.
971  */
972 void igt_skip_on_simulation(void)
973 {
974         if (igt_only_list_subtests())
975                 return;
976
977         igt_require(!igt_run_in_simulation());
978 }
979
980 /* other helpers */
981 void igt_exchange_int(void *array, unsigned i, unsigned j)
982 {
983         int *int_arr, tmp;
984         int_arr = array;
985
986         tmp = int_arr[i];
987         int_arr[i] = int_arr[j];
988         int_arr[j] = tmp;
989 }
990
991 void igt_permute_array(void *array, unsigned size,
992                            void (*exchange_func)(void *array,
993                                                  unsigned i,
994                                                  unsigned j))
995 {
996         int i;
997
998         for (i = size - 1; i > 1; i--) {
999                 /* yes, not perfectly uniform, who cares */
1000                 long l = random() % (i +1);
1001                 if (i != l)
1002                         exchange_func(array, i, l);
1003         }
1004 }
1005
1006 void igt_progress(const char *header, uint64_t i, uint64_t total)
1007 {
1008         int divider = 200;
1009
1010         if (!isatty(fileno(stderr)))
1011                 return;
1012
1013         if (i+1 >= total) {
1014                 fprintf(stderr, "\r%s100%%\n", header);
1015                 return;
1016         }
1017
1018         if (total / 200 == 0)
1019                 divider = 1;
1020
1021         /* only bother updating about every 0.5% */
1022         if (i % (total / divider) == 0 || i+1 >= total) {
1023                 fprintf(stderr, "\r%s%3llu%%", header,
1024                         (long long unsigned) i * 100 / total);
1025         }
1026 }
1027
1028 /* mappable aperture trasher helper */
1029 drm_intel_bo **trash_bos;
1030 int num_trash_bos;
1031
1032 void igt_init_aperture_trashers(drm_intel_bufmgr *bufmgr)
1033 {
1034         int i;
1035
1036         num_trash_bos = gem_mappable_aperture_size() / (1024*1024);
1037
1038         trash_bos = malloc(num_trash_bos * sizeof(drm_intel_bo *));
1039         assert(trash_bos);
1040
1041         for (i = 0; i < num_trash_bos; i++)
1042                 trash_bos[i] = drm_intel_bo_alloc(bufmgr, "trash bo", 1024*1024, 4096);
1043 }
1044
1045 void igt_trash_aperture(void)
1046 {
1047         int i;
1048         uint8_t *gtt_ptr;
1049
1050         for (i = 0; i < num_trash_bos; i++) {
1051                 drm_intel_gem_bo_map_gtt(trash_bos[i]);
1052                 gtt_ptr = trash_bos[i]->virtual;
1053                 *gtt_ptr = 0;
1054                 drm_intel_gem_bo_unmap_gtt(trash_bos[i]);
1055         }
1056 }
1057
1058 void igt_cleanup_aperture_trashers(void)
1059 {
1060         int i;
1061
1062         for (i = 0; i < num_trash_bos; i++)
1063                 drm_intel_bo_unreference(trash_bos[i]);
1064
1065         free(trash_bos);
1066 }
1067
1068 /* helpers to create nice-looking framebuffers */
1069 static int create_bo_for_fb(int fd, int width, int height, int bpp,
1070                             bool tiled, uint32_t *gem_handle_ret,
1071                             unsigned *size_ret, unsigned *stride_ret)
1072 {
1073         struct drm_i915_gem_set_tiling set_tiling;
1074         uint32_t gem_handle;
1075         int size;
1076         unsigned stride;
1077
1078         if (tiled) {
1079                 int v;
1080
1081                 /* Round the tiling up to the next power-of-two and the
1082                  * region up to the next pot fence size so that this works
1083                  * on all generations.
1084                  *
1085                  * This can still fail if the framebuffer is too large to
1086                  * be tiled. But then that failure is expected.
1087                  */
1088
1089                 v = width * bpp / 8;
1090                 for (stride = 512; stride < v; stride *= 2)
1091                         ;
1092
1093                 v = stride * height;
1094                 for (size = 1024*1024; size < v; size *= 2)
1095                         ;
1096         } else {
1097                 /* Scan-out has a 64 byte alignment restriction */
1098                 stride = (width * (bpp / 8) + 63) & ~63;
1099                 size = stride * height;
1100         }
1101
1102         gem_handle = gem_create(fd, size);
1103
1104         if (tiled) {
1105                 set_tiling.handle = gem_handle;
1106                 set_tiling.tiling_mode = I915_TILING_X;
1107                 set_tiling.stride = stride;
1108                 if (ioctl(fd, DRM_IOCTL_I915_GEM_SET_TILING, &set_tiling)) {
1109                         fprintf(stderr, "set tiling failed: %s (stride=%d, size=%d)\n",
1110                                 strerror(errno), stride, size);
1111                         return -1;
1112                 }
1113         }
1114
1115         *stride_ret = stride;
1116         *size_ret = size;
1117         *gem_handle_ret = gem_handle;
1118
1119         return 0;
1120 }
1121
1122 void
1123 kmstest_paint_color_gradient(cairo_t *cr, int x, int y, int w, int h,
1124                      int r, int g, int b)
1125 {
1126         cairo_pattern_t *pat;
1127
1128         pat = cairo_pattern_create_linear(x, y, x + w, y + h);
1129         cairo_pattern_add_color_stop_rgba(pat, 1, 0, 0, 0, 1);
1130         cairo_pattern_add_color_stop_rgba(pat, 0, r, g, b, 1);
1131
1132         cairo_rectangle(cr, x, y, w, h);
1133         cairo_set_source(cr, pat);
1134         cairo_fill(cr);
1135         cairo_pattern_destroy(pat);
1136 }
1137
1138 static void
1139 paint_test_patterns(cairo_t *cr, int width, int height)
1140 {
1141         double gr_height, gr_width;
1142         int x, y;
1143
1144         y = height * 0.10;
1145         gr_width = width * 0.75;
1146         gr_height = height * 0.08;
1147         x = (width / 2) - (gr_width / 2);
1148
1149         kmstest_paint_color_gradient(cr, x, y, gr_width, gr_height, 1, 0, 0);
1150
1151         y += gr_height;
1152         kmstest_paint_color_gradient(cr, x, y, gr_width, gr_height, 0, 1, 0);
1153
1154         y += gr_height;
1155         kmstest_paint_color_gradient(cr, x, y, gr_width, gr_height, 0, 0, 1);
1156
1157         y += gr_height;
1158         kmstest_paint_color_gradient(cr, x, y, gr_width, gr_height, 1, 1, 1);
1159 }
1160
1161 int kmstest_cairo_printf_line(cairo_t *cr, enum kmstest_text_align align,
1162                                 double yspacing, const char *fmt, ...)
1163 {
1164         double x, y, xofs, yofs;
1165         cairo_text_extents_t extents;
1166         char *text;
1167         va_list ap;
1168         int ret;
1169
1170         va_start(ap, fmt);
1171         ret = vasprintf(&text, fmt, ap);
1172         assert(ret >= 0);
1173         va_end(ap);
1174
1175         cairo_text_extents(cr, text, &extents);
1176
1177         xofs = yofs = 0;
1178         if (align & align_right)
1179                 xofs = -extents.width;
1180         else if (align & align_hcenter)
1181                 xofs = -extents.width / 2;
1182
1183         if (align & align_top)
1184                 yofs = extents.height;
1185         else if (align & align_vcenter)
1186                 yofs = extents.height / 2;
1187
1188         cairo_get_current_point(cr, &x, &y);
1189         if (xofs || yofs)
1190                 cairo_rel_move_to(cr, xofs, yofs);
1191
1192         cairo_text_path(cr, text);
1193         cairo_set_source_rgb(cr, 0, 0, 0);
1194         cairo_stroke_preserve(cr);
1195         cairo_set_source_rgb(cr, 1, 1, 1);
1196         cairo_fill(cr);
1197
1198         cairo_move_to(cr, x, y + extents.height + yspacing);
1199
1200         free(text);
1201
1202         return extents.width;
1203 }
1204
1205 static void
1206 paint_marker(cairo_t *cr, int x, int y)
1207 {
1208         enum kmstest_text_align align;
1209         int xoff, yoff;
1210
1211         cairo_move_to(cr, x, y - 20);
1212         cairo_line_to(cr, x, y + 20);
1213         cairo_move_to(cr, x - 20, y);
1214         cairo_line_to(cr, x + 20, y);
1215         cairo_new_sub_path(cr);
1216         cairo_arc(cr, x, y, 10, 0, M_PI * 2);
1217         cairo_set_line_width(cr, 4);
1218         cairo_set_source_rgb(cr, 0, 0, 0);
1219         cairo_stroke_preserve(cr);
1220         cairo_set_source_rgb(cr, 1, 1, 1);
1221         cairo_set_line_width(cr, 2);
1222         cairo_stroke(cr);
1223
1224         xoff = x ? -20 : 20;
1225         align = x ? align_right : align_left;
1226
1227         yoff = y ? -20 : 20;
1228         align |= y ? align_bottom : align_top;
1229
1230         cairo_move_to(cr, x + xoff, y + yoff);
1231         cairo_set_font_size(cr, 18);
1232         kmstest_cairo_printf_line(cr, align, 0, "(%d, %d)", x, y);
1233 }
1234
1235 void kmstest_paint_test_pattern(cairo_t *cr, int width, int height)
1236 {
1237         paint_test_patterns(cr, width, height);
1238
1239         cairo_set_line_cap(cr, CAIRO_LINE_CAP_SQUARE);
1240
1241         /* Paint corner markers */
1242         paint_marker(cr, 0, 0);
1243         paint_marker(cr, width, 0);
1244         paint_marker(cr, 0, height);
1245         paint_marker(cr, width, height);
1246
1247         assert(!cairo_status(cr));
1248 }
1249
1250 #define DF(did, cid, _bpp, _depth)      \
1251         { DRM_FORMAT_##did, CAIRO_FORMAT_##cid, # did, _bpp, _depth }
1252 static struct format_desc_struct {
1253         uint32_t drm_id;
1254         cairo_format_t cairo_id;
1255         const char *name;
1256         int bpp;
1257         int depth;
1258 } format_desc[] = {
1259         DF(RGB565,      RGB16_565,      16, 16),
1260         DF(RGB888,      INVALID,        24, 24),
1261         DF(XRGB8888,    RGB24,          32, 24),
1262         DF(XRGB2101010, RGB30,          32, 30),
1263         DF(ARGB8888,    ARGB32,         32, 32),
1264 };
1265 #undef DF
1266
1267 #define for_each_format(f)      \
1268         for (f = format_desc; f - format_desc < ARRAY_SIZE(format_desc); f++)
1269
1270 static uint32_t bpp_depth_to_drm_format(int bpp, int depth)
1271 {
1272         struct format_desc_struct *f;
1273
1274         for_each_format(f)
1275                 if (f->bpp == bpp && f->depth == depth)
1276                         return f->drm_id;
1277
1278         abort();
1279 }
1280
1281 /* Return fb_id on success, 0 on error */
1282 unsigned int kmstest_create_fb(int fd, int width, int height, int bpp,
1283                                int depth, bool tiled, struct kmstest_fb *fb)
1284 {
1285         memset(fb, 0, sizeof(*fb));
1286
1287         if (create_bo_for_fb(fd, width, height, bpp, tiled, &fb->gem_handle,
1288                                &fb->size, &fb->stride) < 0)
1289                 return 0;
1290
1291         if (drmModeAddFB(fd, width, height, depth, bpp, fb->stride,
1292                                fb->gem_handle, &fb->fb_id) < 0) {
1293                 gem_close(fd, fb->gem_handle);
1294
1295                 return 0;
1296         }
1297
1298         fb->width = width;
1299         fb->height = height;
1300         fb->drm_format = bpp_depth_to_drm_format(bpp, depth);
1301
1302         return fb->fb_id;
1303 }
1304
1305 uint32_t drm_format_to_bpp(uint32_t drm_format)
1306 {
1307         struct format_desc_struct *f;
1308
1309         for_each_format(f)
1310                 if (f->drm_id == drm_format)
1311                         return f->bpp;
1312
1313         abort();
1314 }
1315
1316 unsigned int kmstest_create_fb2(int fd, int width, int height, uint32_t format,
1317                                 bool tiled, struct kmstest_fb *fb)
1318 {
1319         uint32_t handles[4];
1320         uint32_t pitches[4];
1321         uint32_t offsets[4];
1322         uint32_t fb_id;
1323         int bpp;
1324         int ret;
1325
1326         memset(fb, 0, sizeof(*fb));
1327
1328         bpp = drm_format_to_bpp(format);
1329         ret = create_bo_for_fb(fd, width, height, bpp, tiled, &fb->gem_handle,
1330                               &fb->size, &fb->stride);
1331         if (ret < 0)
1332                 return ret;
1333
1334         memset(handles, 0, sizeof(handles));
1335         handles[0] = fb->gem_handle;
1336         memset(pitches, 0, sizeof(pitches));
1337         pitches[0] = fb->stride;
1338         memset(offsets, 0, sizeof(offsets));
1339         if (drmModeAddFB2(fd, width, height, format, handles, pitches,
1340                           offsets, &fb_id, 0) < 0) {
1341                 gem_close(fd, fb->gem_handle);
1342
1343                 return 0;
1344         }
1345
1346         fb->width = width;
1347         fb->height = height;
1348         fb->drm_format = format;
1349         fb->fb_id = fb_id;
1350
1351         return fb_id;
1352 }
1353
1354 static cairo_format_t drm_format_to_cairo(uint32_t drm_format)
1355 {
1356         struct format_desc_struct *f;
1357
1358         for_each_format(f)
1359                 if (f->drm_id == drm_format)
1360                         return f->cairo_id;
1361
1362         abort();
1363 }
1364
1365 static cairo_t *create_cairo_ctx(int fd, struct kmstest_fb *fb)
1366 {
1367         cairo_t *cr;
1368         cairo_surface_t *surface;
1369         cairo_format_t cformat;
1370         void *fb_ptr;
1371
1372         cformat = drm_format_to_cairo(fb->drm_format);
1373         fb_ptr = gem_mmap(fd, fb->gem_handle, fb->size, PROT_READ | PROT_WRITE);
1374         surface = cairo_image_surface_create_for_data((unsigned char *)fb_ptr,
1375                                                    cformat, fb->width,
1376                                                    fb->height, fb->stride);
1377         assert(surface);
1378         cr = cairo_create(surface);
1379         cairo_surface_destroy(surface);
1380
1381         return cr;
1382 }
1383
1384 cairo_t *kmstest_get_cairo_ctx(int fd, struct kmstest_fb *fb)
1385 {
1386
1387         if (!fb->cairo_ctx)
1388                 fb->cairo_ctx = create_cairo_ctx(fd, fb);
1389
1390         gem_set_domain(fd, fb->gem_handle, I915_GEM_DOMAIN_CPU,
1391                        I915_GEM_DOMAIN_CPU);
1392
1393         return fb->cairo_ctx;
1394 }
1395
1396 void kmstest_remove_fb(int fd, struct kmstest_fb *fb)
1397 {
1398         if (fb->cairo_ctx)
1399                 cairo_destroy(fb->cairo_ctx);
1400         do_or_die(drmModeRmFB(fd, fb->fb_id));
1401         gem_close(fd, fb->gem_handle);
1402 }
1403
1404 const char *kmstest_format_str(uint32_t drm_format)
1405 {
1406         struct format_desc_struct *f;
1407
1408         for_each_format(f)
1409                 if (f->drm_id == drm_format)
1410                         return f->name;
1411
1412         return "invalid";
1413 }
1414
1415 const char *kmstest_pipe_str(int pipe)
1416 {
1417         const char *str[] = { "A", "B", "C" };
1418
1419         if (pipe > 2)
1420                 return "invalid";
1421
1422         return str[pipe];
1423 }
1424
1425 void kmstest_get_all_formats(const uint32_t **formats, int *format_count)
1426 {
1427         static uint32_t *drm_formats;
1428
1429         if (!drm_formats) {
1430                 struct format_desc_struct *f;
1431                 uint32_t *format;
1432
1433                 drm_formats = calloc(ARRAY_SIZE(format_desc),
1434                                      sizeof(*drm_formats));
1435                 format = &drm_formats[0];
1436                 for_each_format(f)
1437                         *format++ = f->drm_id;
1438         }
1439
1440         *formats = drm_formats;
1441         *format_count = ARRAY_SIZE(format_desc);
1442 }
1443
1444 struct type_name {
1445         int type;
1446         const char *name;
1447 };
1448
1449 #define type_name_fn(res) \
1450 const char * kmstest_##res##_str(int type) {            \
1451         unsigned int i;                                 \
1452         for (i = 0; i < ARRAY_SIZE(res##_names); i++) { \
1453                 if (res##_names[i].type == type)        \
1454                         return res##_names[i].name;     \
1455         }                                               \
1456         return "(invalid)";                             \
1457 }
1458
1459 struct type_name encoder_type_names[] = {
1460         { DRM_MODE_ENCODER_NONE, "none" },
1461         { DRM_MODE_ENCODER_DAC, "DAC" },
1462         { DRM_MODE_ENCODER_TMDS, "TMDS" },
1463         { DRM_MODE_ENCODER_LVDS, "LVDS" },
1464         { DRM_MODE_ENCODER_TVDAC, "TVDAC" },
1465 };
1466
1467 type_name_fn(encoder_type)
1468
1469 struct type_name connector_status_names[] = {
1470         { DRM_MODE_CONNECTED, "connected" },
1471         { DRM_MODE_DISCONNECTED, "disconnected" },
1472         { DRM_MODE_UNKNOWNCONNECTION, "unknown" },
1473 };
1474
1475 type_name_fn(connector_status)
1476
1477 struct type_name connector_type_names[] = {
1478         { DRM_MODE_CONNECTOR_Unknown, "unknown" },
1479         { DRM_MODE_CONNECTOR_VGA, "VGA" },
1480         { DRM_MODE_CONNECTOR_DVII, "DVI-I" },
1481         { DRM_MODE_CONNECTOR_DVID, "DVI-D" },
1482         { DRM_MODE_CONNECTOR_DVIA, "DVI-A" },
1483         { DRM_MODE_CONNECTOR_Composite, "composite" },
1484         { DRM_MODE_CONNECTOR_SVIDEO, "s-video" },
1485         { DRM_MODE_CONNECTOR_LVDS, "LVDS" },
1486         { DRM_MODE_CONNECTOR_Component, "component" },
1487         { DRM_MODE_CONNECTOR_9PinDIN, "9-pin DIN" },
1488         { DRM_MODE_CONNECTOR_DisplayPort, "DP" },
1489         { DRM_MODE_CONNECTOR_HDMIA, "HDMI-A" },
1490         { DRM_MODE_CONNECTOR_HDMIB, "HDMI-B" },
1491         { DRM_MODE_CONNECTOR_TV, "TV" },
1492         { DRM_MODE_CONNECTOR_eDP, "eDP" },
1493 };
1494
1495 type_name_fn(connector_type)
1496
1497
1498 void kmstest_dump_mode(drmModeModeInfo *mode)
1499 {
1500         printf("  %s %d %d %d %d %d %d %d %d %d 0x%x 0x%x %d\n",
1501                mode->name,
1502                mode->vrefresh,
1503                mode->hdisplay,
1504                mode->hsync_start,
1505                mode->hsync_end,
1506                mode->htotal,
1507                mode->vdisplay,
1508                mode->vsync_start,
1509                mode->vsync_end,
1510                mode->vtotal,
1511                mode->flags,
1512                mode->type,
1513                mode->clock);
1514         fflush(stdout);
1515 }
1516
1517 int kmstest_get_pipe_from_crtc_id(int fd, int crtc_id)
1518 {
1519         struct drm_i915_get_pipe_from_crtc_id pfci;
1520         int ret;
1521
1522         memset(&pfci, 0, sizeof(pfci));
1523         pfci.crtc_id = crtc_id;
1524         ret = drmIoctl(fd, DRM_IOCTL_I915_GET_PIPE_FROM_CRTC_ID, &pfci);
1525         igt_assert(ret == 0);
1526
1527         return pfci.pipe;
1528 }
1529
1530 #define MAX_SIGNALS             32
1531 #define MAX_EXIT_HANDLERS       5
1532
1533 static struct {
1534         sighandler_t handler;
1535         bool installed;
1536 } orig_sig[MAX_SIGNALS];
1537
1538 static igt_exit_handler_t exit_handler_fn[MAX_EXIT_HANDLERS];
1539 static int exit_handler_count;
1540 static bool exit_handler_disabled;
1541 static sigset_t saved_sig_mask;
1542 static const int handled_signals[] =
1543         { SIGINT, SIGHUP, SIGTERM, SIGQUIT, SIGPIPE, SIGABRT, SIGSEGV };
1544
1545 static int install_sig_handler(int sig_num, sighandler_t handler)
1546 {
1547         orig_sig[sig_num].handler = signal(sig_num, handler);
1548
1549         if (orig_sig[sig_num].handler == SIG_ERR)
1550                 return -1;
1551
1552         orig_sig[sig_num].installed = true;
1553
1554         return 0;
1555 }
1556
1557 static void restore_sig_handler(int sig_num)
1558 {
1559         if (orig_sig[sig_num].installed)
1560                 signal(sig_num, orig_sig[sig_num].handler);
1561 }
1562
1563 static void restore_all_sig_handler(void)
1564 {
1565         int i;
1566
1567         for (i = 0; i < ARRAY_SIZE(orig_sig); i++)
1568                 restore_sig_handler(i);
1569 }
1570
1571 static void call_exit_handlers(int sig)
1572 {
1573         int i;
1574
1575         if (!exit_handler_count) {
1576                 fprintf(stderr, "no exit handlers?\n");
1577                 return;
1578         }
1579
1580         for (i = exit_handler_count - 1; i >= 0; i--)
1581                 exit_handler_fn[i](sig);
1582 }
1583
1584 static void igt_atexit_handler(void)
1585 {
1586         restore_all_sig_handler();
1587
1588         if (!exit_handler_disabled)
1589                 call_exit_handlers(0);
1590 }
1591
1592 static void igt_sig_handler(int sig)
1593 {
1594         restore_all_sig_handler();
1595
1596         /*
1597          * exit_handler_disabled is always false here, since when we set it
1598          * we also block signals.
1599          */
1600         call_exit_handlers(sig);
1601
1602         raise(sig);
1603 }
1604
1605 /*
1606  * Set a handler that will be called either when the process calls exit() or
1607  * returns from the main function, or one of the signals in 'handled_signals'
1608  * is raised. MAX_EXIT_HANDLERS handlers can be installed, each of which will
1609  * be called only once, even if a subsequent signal is raised. If the exit
1610  * handlers are called due to a signal, the signal will be re-raised with the
1611  * original signal disposition after all handlers returned.
1612  *
1613  * The handler will be passed the signal number if called due to a signal, or
1614  * 0 otherwise.
1615  */
1616 int igt_install_exit_handler(igt_exit_handler_t fn)
1617 {
1618         int i;
1619
1620         if (exit_handler_count == MAX_EXIT_HANDLERS)
1621                 return -1;
1622
1623         exit_handler_fn[exit_handler_count] = fn;
1624         exit_handler_count++;
1625
1626         if (exit_handler_count > 1)
1627                 return 0;
1628
1629         for (i = 0; i < ARRAY_SIZE(handled_signals); i++) {
1630                 if (install_sig_handler(handled_signals[i],
1631                                         igt_sig_handler))
1632                         goto err;
1633         }
1634
1635         if (atexit(igt_atexit_handler))
1636                 goto err;
1637
1638         return 0;
1639 err:
1640         restore_all_sig_handler();
1641         exit_handler_count--;
1642
1643         return -1;
1644 }
1645
1646 void igt_disable_exit_handler(void)
1647 {
1648         sigset_t set;
1649         int i;
1650
1651         if (exit_handler_disabled)
1652                 return;
1653
1654         sigemptyset(&set);
1655         for (i = 0; i < ARRAY_SIZE(handled_signals); i++)
1656                 sigaddset(&set, handled_signals[i]);
1657
1658         if (sigprocmask(SIG_BLOCK, &set, &saved_sig_mask)) {
1659                 perror("sigprocmask");
1660                 return;
1661         }
1662
1663         exit_handler_disabled = true;
1664 }
1665
1666 void igt_enable_exit_handler(void)
1667 {
1668         if (!exit_handler_disabled)
1669                 return;
1670
1671         if (sigprocmask(SIG_SETMASK, &saved_sig_mask, NULL)) {
1672                 perror("sigprocmask");
1673                 return;
1674         }
1675
1676         exit_handler_disabled = false;
1677 }
1678
1679 static signed long set_vt_mode(unsigned long mode)
1680 {
1681         int fd;
1682         unsigned long prev_mode;
1683
1684         fd = open("/dev/tty0", O_RDONLY);
1685         if (fd < 0)
1686                 return -errno;
1687
1688         prev_mode = 0;
1689         if (drmIoctl(fd, KDGETMODE, &prev_mode))
1690                 goto err;
1691         if (drmIoctl(fd, KDSETMODE, (void *)mode))
1692                 goto err;
1693
1694         close(fd);
1695
1696         return prev_mode;
1697 err:
1698         close(fd);
1699
1700         return -errno;
1701 }
1702
1703 static unsigned long orig_vt_mode = -1UL;
1704
1705 static void restore_vt_mode_at_exit(int sig)
1706 {
1707         if (orig_vt_mode != -1UL)
1708                 set_vt_mode(orig_vt_mode);
1709 }
1710
1711 /*
1712  * Set the VT to graphics mode and install an exit handler to restore the
1713  * original mode.
1714  */
1715
1716 int igt_set_vt_graphics_mode(void)
1717 {
1718         if (igt_install_exit_handler(restore_vt_mode_at_exit))
1719                 return -1;
1720
1721         igt_disable_exit_handler();
1722         orig_vt_mode = set_vt_mode(KD_GRAPHICS);
1723         if (orig_vt_mode < 0)
1724                 orig_vt_mode = -1UL;
1725         igt_enable_exit_handler();
1726
1727         return orig_vt_mode < 0 ? -1 : 0;
1728 }
1729
1730 int kmstest_get_connector_default_mode(int drm_fd, drmModeConnector *connector,
1731                                       drmModeModeInfo *mode)
1732 {
1733         drmModeRes *resources;
1734         int i;
1735
1736         resources = drmModeGetResources(drm_fd);
1737         if (!resources) {
1738                 perror("drmModeGetResources failed");
1739
1740                 return -1;
1741         }
1742
1743         if (!connector->count_modes) {
1744                 fprintf(stderr, "no modes for connector %d\n",
1745                         connector->connector_id);
1746                 drmModeFreeResources(resources);
1747
1748                 return -1;
1749         }
1750
1751         for (i = 0; i < connector->count_modes; i++) {
1752                 if (i == 0 ||
1753                     connector->modes[i].type & DRM_MODE_TYPE_PREFERRED) {
1754                         *mode = connector->modes[i];
1755                         if (mode->type & DRM_MODE_TYPE_PREFERRED)
1756                                 break;
1757                 }
1758         }
1759
1760         drmModeFreeResources(resources);
1761
1762         return 0;
1763 }
1764
1765 int kmstest_get_connector_config(int drm_fd, uint32_t connector_id,
1766                                  unsigned long crtc_idx_mask,
1767                                  struct kmstest_connector_config *config)
1768 {
1769         drmModeRes *resources;
1770         drmModeConnector *connector;
1771         drmModeEncoder *encoder;
1772         int i, j;
1773
1774         resources = drmModeGetResources(drm_fd);
1775         if (!resources) {
1776                 perror("drmModeGetResources failed");
1777                 goto err1;
1778         }
1779
1780         /* First, find the connector & mode */
1781         connector = drmModeGetConnector(drm_fd, connector_id);
1782         if (!connector)
1783                 goto err2;
1784
1785         if (connector->connection != DRM_MODE_CONNECTED)
1786                 goto err3;
1787
1788         if (!connector->count_modes) {
1789                 fprintf(stderr, "connector %d has no modes\n", connector_id);
1790                 goto err3;
1791         }
1792
1793         if (connector->connector_id != connector_id) {
1794                 fprintf(stderr, "connector id doesn't match (%d != %d)\n",
1795                         connector->connector_id, connector_id);
1796                 goto err3;
1797         }
1798
1799         /*
1800          * Find given CRTC if crtc_id != 0 or else the first CRTC not in use.
1801          * In both cases find the first compatible encoder and skip the CRTC
1802          * if there is non such.
1803          */
1804         encoder = NULL;         /* suppress GCC warning */
1805         for (i = 0; i < resources->count_crtcs; i++) {
1806                 if (!resources->crtcs[i] || !(crtc_idx_mask & (1 << i)))
1807                         continue;
1808
1809                 /* Now get a compatible encoder */
1810                 for (j = 0; j < connector->count_encoders; j++) {
1811                         encoder = drmModeGetEncoder(drm_fd,
1812                                                     connector->encoders[j]);
1813
1814                         if (!encoder) {
1815                                 fprintf(stderr, "could not get encoder %d: %s\n",
1816                                         resources->encoders[j], strerror(errno));
1817
1818                                 continue;
1819                         }
1820
1821                         if (encoder->possible_crtcs & (1 << i))
1822                                 goto found;
1823
1824                         drmModeFreeEncoder(encoder);
1825                 }
1826         }
1827
1828         fprintf(stderr,
1829                 "no crtc with a compatible encoder (crtc_idx_mask %08lx)\n",
1830                 crtc_idx_mask);
1831         goto err3;
1832
1833 found:
1834         if (kmstest_get_connector_default_mode(drm_fd, connector,
1835                                        &config->default_mode) < 0)
1836                 goto err4;
1837
1838         config->connector = connector;
1839         config->encoder = encoder;
1840         config->crtc = drmModeGetCrtc(drm_fd, resources->crtcs[i]);
1841         config->crtc_idx = i;
1842         config->pipe = kmstest_get_pipe_from_crtc_id(drm_fd,
1843                                                      config->crtc->crtc_id);
1844
1845         drmModeFreeResources(resources);
1846
1847         return 0;
1848 err4:
1849         drmModeFreeEncoder(encoder);
1850 err3:
1851         drmModeFreeConnector(connector);
1852 err2:
1853         drmModeFreeResources(resources);
1854 err1:
1855         return -1;
1856 }
1857
1858 void kmstest_free_connector_config(struct kmstest_connector_config *config)
1859 {
1860         drmModeFreeCrtc(config->crtc);
1861         drmModeFreeEncoder(config->encoder);
1862         drmModeFreeConnector(config->connector);
1863 }
1864
1865 #define PREFAULT_DEBUGFS "/sys/module/i915/parameters/prefault_disable"
1866 static int igt_prefault_control(bool enable)
1867 {
1868         const char *name = PREFAULT_DEBUGFS;
1869         int fd;
1870         char buf[2] = {'Y', 'N'};
1871         int index;
1872         int result = 0;
1873
1874         fd = open(name, O_RDWR);
1875         if (fd == -1) {
1876                 fprintf(stderr, "Couldn't open prefault_debugfs.%s\n",
1877                                 strerror(errno));
1878                 return -1;
1879         }
1880
1881         if (enable)
1882                 index = 1;
1883         else
1884                 index = 0;
1885
1886         if (write(fd, &buf[index], 1) != 1) {
1887                 fprintf(stderr, "write prefault_debugfs error.%s\n",
1888                                 strerror(errno));
1889                 result = -1;
1890         }
1891
1892         close(fd);
1893
1894         return result;
1895 }
1896
1897 static void enable_prefault_at_exit(int sig)
1898 {
1899         igt_enable_prefault();
1900 }
1901
1902 int igt_disable_prefault(void)
1903 {
1904         igt_install_exit_handler(enable_prefault_at_exit);
1905
1906         return igt_prefault_control(false);
1907 }
1908
1909 int igt_enable_prefault(void)
1910 {
1911         return igt_prefault_control(true);
1912 }
1913
1914 void igt_system_suspend_autoresume(void)
1915 {
1916         int ret;
1917
1918         ret = system("rtcwake -s 30 -m mem");
1919         igt_assert(ret == 0);
1920 }