237eac1463ade43da6c86f302c92bb3ea0cbd984
[platform/upstream/libdrm.git] / tests / modetest / modetest.c
1 /*
2  * DRM based mode setting test program
3  * Copyright 2008 Tungsten Graphics
4  *   Jakob Bornecrantz <jakob@tungstengraphics.com>
5  * Copyright 2008 Intel Corporation
6  *   Jesse Barnes <jesse.barnes@intel.com>
7  *
8  * Permission is hereby granted, free of charge, to any person obtaining a
9  * copy of this software and associated documentation files (the "Software"),
10  * to deal in the Software without restriction, including without limitation
11  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12  * and/or sell copies of the Software, and to permit persons to whom the
13  * Software is furnished to do so, subject to the following conditions:
14  *
15  * The above copyright notice and this permission notice shall be included in
16  * all copies or substantial portions of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
24  * IN THE SOFTWARE.
25  */
26
27 /*
28  * This fairly simple test program dumps output in a similar format to the
29  * "xrandr" tool everyone knows & loves.  It's necessarily slightly different
30  * since the kernel separates outputs into encoder and connector structures,
31  * each with their own unique ID.  The program also allows test testing of the
32  * memory management and mode setting APIs by allowing the user to specify a
33  * connector and mode to use for mode setting.  If all works as expected, a
34  * blue background should be painted on the monitor attached to the specified
35  * connector after the selected mode is set.
36  *
37  * TODO: use cairo to write the mode info on the selected output once
38  *       the mode has been programmed, along with possible test patterns.
39  */
40 #include "config.h"
41
42 #include <assert.h>
43 #include <stdbool.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <stdint.h>
47 #include <inttypes.h>
48 #include <unistd.h>
49 #include <string.h>
50 #include <errno.h>
51 #include <sys/poll.h>
52 #include <sys/time.h>
53
54 #include "xf86drm.h"
55 #include "xf86drmMode.h"
56 #include "drm_fourcc.h"
57 #include "libkms.h"
58
59 #include "buffers.h"
60
61 struct crtc {
62         drmModeCrtc *crtc;
63         drmModeObjectProperties *props;
64         drmModePropertyRes **props_info;
65         drmModeModeInfo *mode;
66 };
67
68 struct encoder {
69         drmModeEncoder *encoder;
70 };
71
72 struct connector {
73         drmModeConnector *connector;
74         drmModeObjectProperties *props;
75         drmModePropertyRes **props_info;
76 };
77
78 struct fb {
79         drmModeFB *fb;
80 };
81
82 struct plane {
83         drmModePlane *plane;
84         drmModeObjectProperties *props;
85         drmModePropertyRes **props_info;
86 };
87
88 struct resources {
89         drmModeRes *res;
90         drmModePlaneRes *plane_res;
91
92         struct crtc *crtcs;
93         struct encoder *encoders;
94         struct connector *connectors;
95         struct fb *fbs;
96         struct plane *planes;
97 };
98
99 struct device {
100         int fd;
101
102         struct resources *resources;
103         struct kms_driver *kms;
104
105         struct {
106                 unsigned int width;
107                 unsigned int height;
108
109                 unsigned int fb_id;
110                 struct kms_bo *bo;
111         } mode;
112 };
113
114 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
115
116 struct type_name {
117         int type;
118         const char *name;
119 };
120
121 #define type_name_fn(res) \
122 const char * res##_str(int type) {                      \
123         unsigned int i;                                 \
124         for (i = 0; i < ARRAY_SIZE(res##_names); i++) { \
125                 if (res##_names[i].type == type)        \
126                         return res##_names[i].name;     \
127         }                                               \
128         return "(invalid)";                             \
129 }
130
131 struct type_name encoder_type_names[] = {
132         { DRM_MODE_ENCODER_NONE, "none" },
133         { DRM_MODE_ENCODER_DAC, "DAC" },
134         { DRM_MODE_ENCODER_TMDS, "TMDS" },
135         { DRM_MODE_ENCODER_LVDS, "LVDS" },
136         { DRM_MODE_ENCODER_TVDAC, "TVDAC" },
137 };
138
139 static type_name_fn(encoder_type)
140
141 struct type_name connector_status_names[] = {
142         { DRM_MODE_CONNECTED, "connected" },
143         { DRM_MODE_DISCONNECTED, "disconnected" },
144         { DRM_MODE_UNKNOWNCONNECTION, "unknown" },
145 };
146
147 static type_name_fn(connector_status)
148
149 struct type_name connector_type_names[] = {
150         { DRM_MODE_CONNECTOR_Unknown, "unknown" },
151         { DRM_MODE_CONNECTOR_VGA, "VGA" },
152         { DRM_MODE_CONNECTOR_DVII, "DVI-I" },
153         { DRM_MODE_CONNECTOR_DVID, "DVI-D" },
154         { DRM_MODE_CONNECTOR_DVIA, "DVI-A" },
155         { DRM_MODE_CONNECTOR_Composite, "composite" },
156         { DRM_MODE_CONNECTOR_SVIDEO, "s-video" },
157         { DRM_MODE_CONNECTOR_LVDS, "LVDS" },
158         { DRM_MODE_CONNECTOR_Component, "component" },
159         { DRM_MODE_CONNECTOR_9PinDIN, "9-pin DIN" },
160         { DRM_MODE_CONNECTOR_DisplayPort, "DP" },
161         { DRM_MODE_CONNECTOR_HDMIA, "HDMI-A" },
162         { DRM_MODE_CONNECTOR_HDMIB, "HDMI-B" },
163         { DRM_MODE_CONNECTOR_TV, "TV" },
164         { DRM_MODE_CONNECTOR_eDP, "eDP" },
165 };
166
167 static type_name_fn(connector_type)
168
169 #define bit_name_fn(res)                                        \
170 const char * res##_str(int type) {                              \
171         unsigned int i;                                         \
172         const char *sep = "";                                   \
173         for (i = 0; i < ARRAY_SIZE(res##_names); i++) {         \
174                 if (type & (1 << i)) {                          \
175                         printf("%s%s", sep, res##_names[i]);    \
176                         sep = ", ";                             \
177                 }                                               \
178         }                                                       \
179         return NULL;                                            \
180 }
181
182 static const char *mode_type_names[] = {
183         "builtin",
184         "clock_c",
185         "crtc_c",
186         "preferred",
187         "default",
188         "userdef",
189         "driver",
190 };
191
192 static bit_name_fn(mode_type)
193
194 static const char *mode_flag_names[] = {
195         "phsync",
196         "nhsync",
197         "pvsync",
198         "nvsync",
199         "interlace",
200         "dblscan",
201         "csync",
202         "pcsync",
203         "ncsync",
204         "hskew",
205         "bcast",
206         "pixmux",
207         "dblclk",
208         "clkdiv2"
209 };
210
211 static bit_name_fn(mode_flag)
212
213 static void dump_encoders(struct device *dev)
214 {
215         drmModeEncoder *encoder;
216         int i;
217
218         printf("Encoders:\n");
219         printf("id\tcrtc\ttype\tpossible crtcs\tpossible clones\t\n");
220         for (i = 0; i < dev->resources->res->count_encoders; i++) {
221                 encoder = dev->resources->encoders[i].encoder;
222                 if (!encoder)
223                         continue;
224
225                 printf("%d\t%d\t%s\t0x%08x\t0x%08x\n",
226                        encoder->encoder_id,
227                        encoder->crtc_id,
228                        encoder_type_str(encoder->encoder_type),
229                        encoder->possible_crtcs,
230                        encoder->possible_clones);
231         }
232         printf("\n");
233 }
234
235 static void dump_mode(drmModeModeInfo *mode)
236 {
237         printf("  %s %d %d %d %d %d %d %d %d %d",
238                mode->name,
239                mode->vrefresh,
240                mode->hdisplay,
241                mode->hsync_start,
242                mode->hsync_end,
243                mode->htotal,
244                mode->vdisplay,
245                mode->vsync_start,
246                mode->vsync_end,
247                mode->vtotal);
248
249         printf(" flags: ");
250         mode_flag_str(mode->flags);
251         printf("; type: ");
252         mode_type_str(mode->type);
253         printf("\n");
254 }
255
256 static void dump_blob(struct device *dev, uint32_t blob_id)
257 {
258         uint32_t i;
259         unsigned char *blob_data;
260         drmModePropertyBlobPtr blob;
261
262         blob = drmModeGetPropertyBlob(dev->fd, blob_id);
263         if (!blob)
264                 return;
265
266         blob_data = blob->data;
267
268         for (i = 0; i < blob->length; i++) {
269                 if (i % 16 == 0)
270                         printf("\n\t\t\t");
271                 printf("%.2hhx", blob_data[i]);
272         }
273         printf("\n");
274
275         drmModeFreePropertyBlob(blob);
276 }
277
278 static void dump_prop(struct device *dev, drmModePropertyPtr prop,
279                       uint32_t prop_id, uint64_t value)
280 {
281         int i;
282         printf("\t%d", prop_id);
283         if (!prop) {
284                 printf("\n");
285                 return;
286         }
287
288         printf(" %s:\n", prop->name);
289
290         printf("\t\tflags:");
291         if (prop->flags & DRM_MODE_PROP_PENDING)
292                 printf(" pending");
293         if (prop->flags & DRM_MODE_PROP_RANGE)
294                 printf(" range");
295         if (prop->flags & DRM_MODE_PROP_IMMUTABLE)
296                 printf(" immutable");
297         if (prop->flags & DRM_MODE_PROP_ENUM)
298                 printf(" enum");
299         if (prop->flags & DRM_MODE_PROP_BITMASK)
300                 printf(" bitmask");
301         if (prop->flags & DRM_MODE_PROP_BLOB)
302                 printf(" blob");
303         printf("\n");
304
305         if (prop->flags & DRM_MODE_PROP_RANGE) {
306                 printf("\t\tvalues:");
307                 for (i = 0; i < prop->count_values; i++)
308                         printf(" %"PRIu64, prop->values[i]);
309                 printf("\n");
310         }
311
312         if (prop->flags & DRM_MODE_PROP_ENUM) {
313                 printf("\t\tenums:");
314                 for (i = 0; i < prop->count_enums; i++)
315                         printf(" %s=%llu", prop->enums[i].name,
316                                prop->enums[i].value);
317                 printf("\n");
318         } else if (prop->flags & DRM_MODE_PROP_BITMASK) {
319                 printf("\t\tvalues:");
320                 for (i = 0; i < prop->count_enums; i++)
321                         printf(" %s=0x%llx", prop->enums[i].name,
322                                (1LL << prop->enums[i].value));
323                 printf("\n");
324         } else {
325                 assert(prop->count_enums == 0);
326         }
327
328         if (prop->flags & DRM_MODE_PROP_BLOB) {
329                 printf("\t\tblobs:\n");
330                 for (i = 0; i < prop->count_blobs; i++)
331                         dump_blob(dev, prop->blob_ids[i]);
332                 printf("\n");
333         } else {
334                 assert(prop->count_blobs == 0);
335         }
336
337         printf("\t\tvalue:");
338         if (prop->flags & DRM_MODE_PROP_BLOB)
339                 dump_blob(dev, value);
340         else
341                 printf(" %"PRIu64"\n", value);
342 }
343
344 static void dump_connectors(struct device *dev)
345 {
346         int i, j;
347
348         printf("Connectors:\n");
349         printf("id\tencoder\tstatus\t\ttype\tsize (mm)\tmodes\tencoders\n");
350         for (i = 0; i < dev->resources->res->count_connectors; i++) {
351                 struct connector *_connector = &dev->resources->connectors[i];
352                 drmModeConnector *connector = _connector->connector;
353                 if (!connector)
354                         continue;
355
356                 printf("%d\t%d\t%s\t%s\t%dx%d\t\t%d\t",
357                        connector->connector_id,
358                        connector->encoder_id,
359                        connector_status_str(connector->connection),
360                        connector_type_str(connector->connector_type),
361                        connector->mmWidth, connector->mmHeight,
362                        connector->count_modes);
363
364                 for (j = 0; j < connector->count_encoders; j++)
365                         printf("%s%d", j > 0 ? ", " : "", connector->encoders[j]);
366                 printf("\n");
367
368                 if (connector->count_modes) {
369                         printf("  modes:\n");
370                         printf("\tname refresh (Hz) hdisp hss hse htot vdisp "
371                                "vss vse vtot)\n");
372                         for (j = 0; j < connector->count_modes; j++)
373                                 dump_mode(&connector->modes[j]);
374                 }
375
376                 if (_connector->props) {
377                         printf("  props:\n");
378                         for (j = 0; j < (int)_connector->props->count_props; j++)
379                                 dump_prop(dev, _connector->props_info[j],
380                                           _connector->props->props[j],
381                                           _connector->props->prop_values[j]);
382                 }
383         }
384         printf("\n");
385 }
386
387 static void dump_crtcs(struct device *dev)
388 {
389         int i;
390         uint32_t j;
391
392         printf("CRTCs:\n");
393         printf("id\tfb\tpos\tsize\n");
394         for (i = 0; i < dev->resources->res->count_crtcs; i++) {
395                 struct crtc *_crtc = &dev->resources->crtcs[i];
396                 drmModeCrtc *crtc = _crtc->crtc;
397                 if (!crtc)
398                         continue;
399
400                 printf("%d\t%d\t(%d,%d)\t(%dx%d)\n",
401                        crtc->crtc_id,
402                        crtc->buffer_id,
403                        crtc->x, crtc->y,
404                        crtc->width, crtc->height);
405                 dump_mode(&crtc->mode);
406
407                 if (_crtc->props) {
408                         printf("  props:\n");
409                         for (j = 0; j < _crtc->props->count_props; j++)
410                                 dump_prop(dev, _crtc->props_info[j],
411                                           _crtc->props->props[j],
412                                           _crtc->props->prop_values[j]);
413                 } else {
414                         printf("  no properties found\n");
415                 }
416         }
417         printf("\n");
418 }
419
420 static void dump_framebuffers(struct device *dev)
421 {
422         drmModeFB *fb;
423         int i;
424
425         printf("Frame buffers:\n");
426         printf("id\tsize\tpitch\n");
427         for (i = 0; i < dev->resources->res->count_fbs; i++) {
428                 fb = dev->resources->fbs[i].fb;
429                 if (!fb)
430                         continue;
431
432                 printf("%u\t(%ux%u)\t%u\n",
433                        fb->fb_id,
434                        fb->width, fb->height,
435                        fb->pitch);
436         }
437         printf("\n");
438 }
439
440 static void dump_planes(struct device *dev)
441 {
442         unsigned int i, j;
443
444         printf("Planes:\n");
445         printf("id\tcrtc\tfb\tCRTC x,y\tx,y\tgamma size\tpossible crtcs\n");
446
447         if (!dev->resources->plane_res)
448                 return;
449
450         for (i = 0; i < dev->resources->plane_res->count_planes; i++) {
451                 struct plane *plane = &dev->resources->planes[i];
452                 drmModePlane *ovr = plane->plane;
453                 if (!ovr)
454                         continue;
455
456                 printf("%d\t%d\t%d\t%d,%d\t\t%d,%d\t%-8d\t0x%08x\n",
457                        ovr->plane_id, ovr->crtc_id, ovr->fb_id,
458                        ovr->crtc_x, ovr->crtc_y, ovr->x, ovr->y,
459                        ovr->gamma_size, ovr->possible_crtcs);
460
461                 if (!ovr->count_formats)
462                         continue;
463
464                 printf("  formats:");
465                 for (j = 0; j < ovr->count_formats; j++)
466                         printf(" %4.4s", (char *)&ovr->formats[j]);
467                 printf("\n");
468
469                 if (plane->props) {
470                         printf("  props:\n");
471                         for (j = 0; j < plane->props->count_props; j++)
472                                 dump_prop(dev, plane->props_info[j],
473                                           plane->props->props[j],
474                                           plane->props->prop_values[j]);
475                 } else {
476                         printf("  no properties found\n");
477                 }
478         }
479         printf("\n");
480
481         return;
482 }
483
484 static void free_resources(struct resources *res)
485 {
486         if (!res)
487                 return;
488
489 #define free_resource(_res, __res, type, Type)                                  \
490         do {                                                                    \
491                 int i;                                                          \
492                 if (!(_res)->type##s)                                           \
493                         break;                                                  \
494                 for (i = 0; i < (int)(_res)->__res->count_##type##s; ++i) {     \
495                         if (!(_res)->type##s[i].type)                           \
496                                 break;                                          \
497                         drmModeFree##Type((_res)->type##s[i].type);             \
498                 }                                                               \
499                 free((_res)->type##s);                                          \
500         } while (0)
501
502 #define free_properties(_res, __res, type)                                      \
503         do {                                                                    \
504                 int i;                                                          \
505                 for (i = 0; i < (int)(_res)->__res->count_##type##s; ++i) {     \
506                         drmModeFreeObjectProperties(res->type##s[i].props);     \
507                         free(res->type##s[i].props_info);                       \
508                 }                                                               \
509         } while (0)
510
511         if (res->res) {
512                 free_properties(res, res, crtc);
513
514                 free_resource(res, res, crtc, Crtc);
515                 free_resource(res, res, encoder, Encoder);
516                 free_resource(res, res, connector, Connector);
517                 free_resource(res, res, fb, FB);
518
519                 drmModeFreeResources(res->res);
520         }
521
522         if (res->plane_res) {
523                 free_properties(res, plane_res, plane);
524
525                 free_resource(res, plane_res, plane, Plane);
526
527                 drmModeFreePlaneResources(res->plane_res);
528         }
529
530         free(res);
531 }
532
533 static struct resources *get_resources(struct device *dev)
534 {
535         struct resources *res;
536         int i;
537
538         res = malloc(sizeof *res);
539         if (res == 0)
540                 return NULL;
541
542         memset(res, 0, sizeof *res);
543
544         res->res = drmModeGetResources(dev->fd);
545         if (!res->res) {
546                 fprintf(stderr, "drmModeGetResources failed: %s\n",
547                         strerror(errno));
548                 goto error;
549         }
550
551         res->crtcs = malloc(res->res->count_crtcs * sizeof *res->crtcs);
552         res->encoders = malloc(res->res->count_encoders * sizeof *res->encoders);
553         res->connectors = malloc(res->res->count_connectors * sizeof *res->connectors);
554         res->fbs = malloc(res->res->count_fbs * sizeof *res->fbs);
555
556         if (!res->crtcs || !res->encoders || !res->connectors || !res->fbs)
557                 goto error;
558
559         memset(res->crtcs , 0, res->res->count_crtcs * sizeof *res->crtcs);
560         memset(res->encoders, 0, res->res->count_encoders * sizeof *res->encoders);
561         memset(res->connectors, 0, res->res->count_connectors * sizeof *res->connectors);
562         memset(res->fbs, 0, res->res->count_fbs * sizeof *res->fbs);
563
564 #define get_resource(_res, __res, type, Type)                                   \
565         do {                                                                    \
566                 int i;                                                          \
567                 for (i = 0; i < (int)(_res)->__res->count_##type##s; ++i) {     \
568                         (_res)->type##s[i].type =                               \
569                                 drmModeGet##Type(dev->fd, (_res)->__res->type##s[i]); \
570                         if (!(_res)->type##s[i].type)                           \
571                                 fprintf(stderr, "could not get %s %i: %s\n",    \
572                                         #type, (_res)->__res->type##s[i],       \
573                                         strerror(errno));                       \
574                 }                                                               \
575         } while (0)
576
577         get_resource(res, res, crtc, Crtc);
578         get_resource(res, res, encoder, Encoder);
579         get_resource(res, res, connector, Connector);
580         get_resource(res, res, fb, FB);
581
582 #define get_properties(_res, __res, type, Type)                                 \
583         do {                                                                    \
584                 int i;                                                          \
585                 for (i = 0; i < (int)(_res)->__res->count_##type##s; ++i) {     \
586                         struct type *obj = &res->type##s[i];                    \
587                         unsigned int j;                                         \
588                         obj->props =                                            \
589                                 drmModeObjectGetProperties(dev->fd, obj->type->type##_id, \
590                                                            DRM_MODE_OBJECT_##Type); \
591                         if (!obj->props) {                                      \
592                                 fprintf(stderr,                                 \
593                                         "could not get %s %i properties: %s\n", \
594                                         #type, obj->type->type##_id,            \
595                                         strerror(errno));                       \
596                                 continue;                                       \
597                         }                                                       \
598                         obj->props_info = malloc(obj->props->count_props *      \
599                                                  sizeof *obj->props_info);      \
600                         if (!obj->props_info)                                   \
601                                 continue;                                       \
602                         for (j = 0; j < obj->props->count_props; ++j)           \
603                                 obj->props_info[j] =                            \
604                                         drmModeGetProperty(dev->fd, obj->props->props[j]); \
605                 }                                                               \
606         } while (0)
607
608         get_properties(res, res, crtc, CRTC);
609         get_properties(res, res, connector, CONNECTOR);
610
611         for (i = 0; i < res->res->count_crtcs; ++i)
612                 res->crtcs[i].mode = &res->crtcs[i].crtc->mode;
613
614         res->plane_res = drmModeGetPlaneResources(dev->fd);
615         if (!res->plane_res) {
616                 fprintf(stderr, "drmModeGetPlaneResources failed: %s\n",
617                         strerror(errno));
618                 return res;
619         }
620
621         res->planes = malloc(res->plane_res->count_planes * sizeof *res->planes);
622         if (!res->planes)
623                 goto error;
624
625         memset(res->planes, 0, res->plane_res->count_planes * sizeof *res->planes);
626
627         get_resource(res, plane_res, plane, Plane);
628         get_properties(res, plane_res, plane, PLANE);
629
630         return res;
631
632 error:
633         free_resources(res);
634         return NULL;
635 }
636
637 /* -----------------------------------------------------------------------------
638  * Connectors and planes
639  */
640
641 /*
642  * Mode setting with the kernel interfaces is a bit of a chore.
643  * First you have to find the connector in question and make sure the
644  * requested mode is available.
645  * Then you need to find the encoder attached to that connector so you
646  * can bind it with a free crtc.
647  */
648 struct connector_arg {
649         uint32_t id;
650         uint32_t crtc_id;
651         char mode_str[64];
652         char format_str[5];
653         unsigned int fourcc;
654         drmModeModeInfo *mode;
655         struct crtc *crtc;
656         unsigned int fb_id[2], current_fb_id;
657         struct timeval start;
658
659         int swap_count;
660 };
661
662 struct plane_arg {
663         uint32_t crtc_id;  /* the id of CRTC to bind to */
664         bool has_position;
665         int32_t x, y;
666         uint32_t w, h;
667         unsigned int fb_id;
668         char format_str[5]; /* need to leave room for terminating \0 */
669         unsigned int fourcc;
670 };
671
672 static void connector_find_mode(struct device *dev, struct connector_arg *c)
673 {
674         drmModeConnector *connector;
675         drmModeEncoder *encoder;
676         int i, j;
677
678         /* First, find the connector & mode */
679         c->mode = NULL;
680         for (i = 0; i < dev->resources->res->count_connectors; i++) {
681                 connector = dev->resources->connectors[i].connector;
682                 if (!connector)
683                         continue;
684
685                 if (!connector->count_modes)
686                         continue;
687
688                 if (connector->connector_id != c->id)
689                         continue;
690
691                 for (j = 0; j < connector->count_modes; j++) {
692                         c->mode = &connector->modes[j];
693                         if (!strcmp(c->mode->name, c->mode_str))
694                                 break;
695                 }
696
697                 /* Found it, break out */
698                 if (c->mode)
699                         break;
700         }
701
702         if (!c->mode) {
703                 fprintf(stderr, "failed to find mode \"%s\"\n", c->mode_str);
704                 return;
705         }
706
707         /* If the CRTC ID was specified, get the corresponding CRTC. Otherwise
708          * locate a CRTC that can be attached to the connector.
709          */
710         if (c->crtc_id == (uint32_t)-1) {
711                 for (i = 0; i < dev->resources->res->count_encoders; i++) {
712                         encoder = dev->resources->encoders[i].encoder;
713                         if (!encoder)
714                                 continue;
715
716                         if (encoder->encoder_id  == connector->encoder_id) {
717                                 c->crtc_id = encoder->crtc_id;
718                                 break;
719                         }
720                 }
721         }
722
723         if (c->crtc_id == (uint32_t)-1)
724                 return;
725
726         for (i = 0; i < dev->resources->res->count_crtcs; i++) {
727                 struct crtc *crtc = &dev->resources->crtcs[i];
728
729                 if (c->crtc_id == crtc->crtc->crtc_id) {
730                         crtc->mode = c->mode;
731                         c->crtc = crtc;
732                         break;
733                 }
734         }
735 }
736
737 /* -----------------------------------------------------------------------------
738  * Properties
739  */
740
741 struct property_arg {
742         uint32_t obj_id;
743         uint32_t obj_type;
744         char name[DRM_PROP_NAME_LEN+1];
745         uint32_t prop_id;
746         uint64_t value;
747 };
748
749 static void set_property(struct device *dev, struct property_arg *p)
750 {
751         drmModeObjectProperties *props;
752         drmModePropertyRes **props_info;
753         const char *obj_type;
754         int ret;
755         int i;
756
757         p->obj_type = 0;
758         p->prop_id = 0;
759
760 #define find_object(_res, __res, type, Type)                                    \
761         do {                                                                    \
762                 for (i = 0; i < (int)(_res)->__res->count_##type##s; ++i) {     \
763                         struct type *obj = &(_res)->type##s[i];                 \
764                         if (obj->type->type##_id != p->obj_id)                  \
765                                 continue;                                       \
766                         p->obj_type = DRM_MODE_OBJECT_##Type;                   \
767                         obj_type = #Type;                                       \
768                         props = obj->props;                                     \
769                         props_info = obj->props_info;                           \
770                 }                                                               \
771         } while(0)                                                              \
772
773         find_object(dev->resources, res, crtc, CRTC);
774         if (p->obj_type == 0)
775                 find_object(dev->resources, res, connector, CONNECTOR);
776         if (p->obj_type == 0)
777                 find_object(dev->resources, plane_res, plane, PLANE);
778         if (p->obj_type == 0) {
779                 fprintf(stderr, "Object %i not found, can't set property\n",
780                         p->obj_id);
781                         return;
782         }
783
784         if (!props) {
785                 fprintf(stderr, "%s %i has no properties\n",
786                         obj_type, p->obj_id);
787                 return;
788         }
789
790         for (i = 0; i < (int)props->count_props; ++i) {
791                 if (!props_info[i])
792                         continue;
793                 if (strcmp(props_info[i]->name, p->name) == 0)
794                         break;
795         }
796
797         if (i == (int)props->count_props) {
798                 fprintf(stderr, "%s %i has no %s property\n",
799                         obj_type, p->obj_id, p->name);
800                 return;
801         }
802
803         p->prop_id = props->props[i];
804
805         ret = drmModeObjectSetProperty(dev->fd, p->obj_id, p->obj_type,
806                                        p->prop_id, p->value);
807         if (ret < 0)
808                 fprintf(stderr, "failed to set %s %i property %s to %" PRIu64 ": %s\n",
809                         obj_type, p->obj_id, p->name, p->value, strerror(errno));
810 }
811
812 /* -------------------------------------------------------------------------- */
813
814 static void
815 page_flip_handler(int fd, unsigned int frame,
816                   unsigned int sec, unsigned int usec, void *data)
817 {
818         struct connector_arg *c;
819         unsigned int new_fb_id;
820         struct timeval end;
821         double t;
822
823         c = data;
824         if (c->current_fb_id == c->fb_id[0])
825                 new_fb_id = c->fb_id[1];
826         else
827                 new_fb_id = c->fb_id[0];
828
829         drmModePageFlip(fd, c->crtc_id, new_fb_id,
830                         DRM_MODE_PAGE_FLIP_EVENT, c);
831         c->current_fb_id = new_fb_id;
832         c->swap_count++;
833         if (c->swap_count == 60) {
834                 gettimeofday(&end, NULL);
835                 t = end.tv_sec + end.tv_usec * 1e-6 -
836                         (c->start.tv_sec + c->start.tv_usec * 1e-6);
837                 fprintf(stderr, "freq: %.02fHz\n", c->swap_count / t);
838                 c->swap_count = 0;
839                 c->start = end;
840         }
841 }
842
843 static int set_plane(struct device *dev, struct plane_arg *p)
844 {
845         drmModePlane *ovr;
846         uint32_t handles[4], pitches[4], offsets[4] = {0}; /* we only use [0] */
847         uint32_t plane_id = 0;
848         struct kms_bo *plane_bo;
849         uint32_t plane_flags = 0;
850         int crtc_x, crtc_y, crtc_w, crtc_h;
851         struct crtc *crtc = NULL;
852         unsigned int pipe;
853         unsigned int i;
854
855         /* Find an unused plane which can be connected to our CRTC. Find the
856          * CRTC index first, then iterate over available planes.
857          */
858         for (i = 0; i < (unsigned int)dev->resources->res->count_crtcs; i++) {
859                 if (p->crtc_id == dev->resources->res->crtcs[i]) {
860                         crtc = &dev->resources->crtcs[i];
861                         pipe = i;
862                         break;
863                 }
864         }
865
866         if (!crtc) {
867                 fprintf(stderr, "CRTC %u not found\n", p->crtc_id);
868                 return -1;
869         }
870
871         for (i = 0; i < dev->resources->plane_res->count_planes && !plane_id; i++) {
872                 ovr = dev->resources->planes[i].plane;
873                 if (!ovr)
874                         continue;
875
876                 if ((ovr->possible_crtcs & (1 << pipe)) && !ovr->crtc_id)
877                         plane_id = ovr->plane_id;
878         }
879
880         if (!plane_id) {
881                 fprintf(stderr, "no unused plane available for CRTC %u\n",
882                         crtc->crtc->crtc_id);
883                 return -1;
884         }
885
886         fprintf(stderr, "testing %dx%d@%s overlay plane %u\n",
887                 p->w, p->h, p->format_str, plane_id);
888
889         plane_bo = create_test_buffer(dev->kms, p->fourcc, p->w, p->h, handles,
890                                       pitches, offsets, PATTERN_TILES);
891         if (plane_bo == NULL)
892                 return -1;
893
894         /* just use single plane format for now.. */
895         if (drmModeAddFB2(dev->fd, p->w, p->h, p->fourcc,
896                         handles, pitches, offsets, &p->fb_id, plane_flags)) {
897                 fprintf(stderr, "failed to add fb: %s\n", strerror(errno));
898                 return -1;
899         }
900
901         if (!p->has_position) {
902                 /* Default to the middle of the screen */
903                 crtc_x = (crtc->mode->hdisplay - p->w) / 2;
904                 crtc_y = (crtc->mode->vdisplay - p->h) / 2;
905         } else {
906                 crtc_x = p->x;
907                 crtc_y = p->y;
908         }
909         crtc_w = p->w;
910         crtc_h = p->h;
911
912         /* note src coords (last 4 args) are in Q16 format */
913         if (drmModeSetPlane(dev->fd, plane_id, crtc->crtc->crtc_id, p->fb_id,
914                             plane_flags, crtc_x, crtc_y, crtc_w, crtc_h,
915                             0, 0, p->w << 16, p->h << 16)) {
916                 fprintf(stderr, "failed to enable plane: %s\n",
917                         strerror(errno));
918                 return -1;
919         }
920
921         ovr->crtc_id = crtc->crtc->crtc_id;
922
923         return 0;
924 }
925
926 static void set_mode(struct device *dev, struct connector_arg *c, unsigned int count)
927 {
928         uint32_t handles[4], pitches[4], offsets[4] = {0}; /* we only use [0] */
929         unsigned int fb_id;
930         struct kms_bo *bo;
931         unsigned int i;
932         int ret, x;
933
934         dev->mode.width = 0;
935         dev->mode.height = 0;
936
937         for (i = 0; i < count; i++) {
938                 connector_find_mode(dev, &c[i]);
939                 if (c[i].mode == NULL)
940                         continue;
941                 dev->mode.width += c[i].mode->hdisplay;
942                 if (dev->mode.height < c[i].mode->vdisplay)
943                         dev->mode.height = c[i].mode->vdisplay;
944         }
945
946         bo = create_test_buffer(dev->kms, c->fourcc,
947                                 dev->mode.width, dev->mode.height,
948                                 handles, pitches, offsets, PATTERN_SMPTE);
949         if (bo == NULL)
950                 return;
951
952         ret = drmModeAddFB2(dev->fd, dev->mode.width, dev->mode.height, c->fourcc,
953                             handles, pitches, offsets, &fb_id, 0);
954         if (ret) {
955                 fprintf(stderr, "failed to add fb (%ux%u): %s\n",
956                         dev->mode.width, dev->mode.height, strerror(errno));
957                 return;
958         }
959
960         x = 0;
961         for (i = 0; i < count; i++) {
962                 if (c[i].mode == NULL)
963                         continue;
964
965                 printf("setting mode %s@%s on connector %d, crtc %d\n",
966                        c[i].mode_str, c[i].format_str, c[i].id, c[i].crtc_id);
967
968                 ret = drmModeSetCrtc(dev->fd, c[i].crtc_id, fb_id, x, 0,
969                                      &c[i].id, 1, c[i].mode);
970
971                 /* XXX: Actually check if this is needed */
972                 drmModeDirtyFB(dev->fd, fb_id, NULL, 0);
973
974                 x += c[i].mode->hdisplay;
975
976                 if (ret) {
977                         fprintf(stderr, "failed to set mode: %s\n", strerror(errno));
978                         return;
979                 }
980         }
981
982         dev->mode.bo = bo;
983         dev->mode.fb_id = fb_id;
984 }
985
986 static void set_planes(struct device *dev, struct plane_arg *p, unsigned int count)
987 {
988         unsigned int i;
989
990         /* set up planes/overlays */
991         for (i = 0; i < count; i++)
992                 if (set_plane(dev, &p[i]))
993                         return;
994 }
995
996 static void test_page_flip(struct device *dev, struct connector_arg *c, unsigned int count)
997 {
998         uint32_t handles[4], pitches[4], offsets[4] = {0}; /* we only use [0] */
999         unsigned int other_fb_id;
1000         struct kms_bo *other_bo;
1001         drmEventContext evctx;
1002         unsigned int i;
1003         int ret;
1004
1005         other_bo = create_test_buffer(dev->kms, c->fourcc,
1006                                       dev->mode.width, dev->mode.height,
1007                                       handles, pitches, offsets, PATTERN_PLAIN);
1008         if (other_bo == NULL)
1009                 return;
1010
1011         ret = drmModeAddFB2(dev->fd, dev->mode.width, dev->mode.height, c->fourcc,
1012                             handles, pitches, offsets, &other_fb_id, 0);
1013         if (ret) {
1014                 fprintf(stderr, "failed to add fb: %s\n", strerror(errno));
1015                 return;
1016         }
1017
1018         for (i = 0; i < count; i++) {
1019                 if (c[i].mode == NULL)
1020                         continue;
1021
1022                 ret = drmModePageFlip(dev->fd, c[i].crtc_id, other_fb_id,
1023                                       DRM_MODE_PAGE_FLIP_EVENT, &c[i]);
1024                 if (ret) {
1025                         fprintf(stderr, "failed to page flip: %s\n", strerror(errno));
1026                         return;
1027                 }
1028                 gettimeofday(&c[i].start, NULL);
1029                 c[i].swap_count = 0;
1030                 c[i].fb_id[0] = dev->mode.fb_id;
1031                 c[i].fb_id[1] = other_fb_id;
1032                 c[i].current_fb_id = other_fb_id;
1033         }
1034
1035         memset(&evctx, 0, sizeof evctx);
1036         evctx.version = DRM_EVENT_CONTEXT_VERSION;
1037         evctx.vblank_handler = NULL;
1038         evctx.page_flip_handler = page_flip_handler;
1039         
1040         while (1) {
1041 #if 0
1042                 struct pollfd pfd[2];
1043
1044                 pfd[0].fd = 0;
1045                 pfd[0].events = POLLIN;
1046                 pfd[1].fd = fd;
1047                 pfd[1].events = POLLIN;
1048
1049                 if (poll(pfd, 2, -1) < 0) {
1050                         fprintf(stderr, "poll error\n");
1051                         break;
1052                 }
1053
1054                 if (pfd[0].revents)
1055                         break;
1056 #else
1057                 struct timeval timeout = { .tv_sec = 3, .tv_usec = 0 };
1058                 fd_set fds;
1059                 int ret;
1060
1061                 FD_ZERO(&fds);
1062                 FD_SET(0, &fds);
1063                 FD_SET(dev->fd, &fds);
1064                 ret = select(dev->fd + 1, &fds, NULL, NULL, &timeout);
1065
1066                 if (ret <= 0) {
1067                         fprintf(stderr, "select timed out or error (ret %d)\n",
1068                                 ret);
1069                         continue;
1070                 } else if (FD_ISSET(0, &fds)) {
1071                         break;
1072                 }
1073 #endif
1074
1075                 drmHandleEvent(dev->fd, &evctx);
1076         }
1077
1078         kms_bo_destroy(&other_bo);
1079 }
1080
1081 #define min(a, b)       ((a) < (b) ? (a) : (b))
1082
1083 static int parse_connector(struct connector_arg *c, const char *arg)
1084 {
1085         unsigned int len;
1086         const char *p;
1087         char *endp;
1088
1089         c->crtc_id = (uint32_t)-1;
1090         strcpy(c->format_str, "XR24");
1091
1092         c->id = strtoul(arg, &endp, 10);
1093         if (*endp == '@') {
1094                 arg = endp + 1;
1095                 c->crtc_id = strtoul(arg, &endp, 10);
1096         }
1097         if (*endp != ':')
1098                 return -1;
1099
1100         arg = endp + 1;
1101
1102         p = strchrnul(arg, '@');
1103         len = min(sizeof c->mode_str - 1, (unsigned int)(p - arg));
1104         strncpy(c->mode_str, arg, len);
1105         c->mode_str[len] = '\0';
1106
1107         if (*p == '@') {
1108                 strncpy(c->format_str, p + 1, 4);
1109                 c->format_str[4] = '\0';
1110         }
1111
1112         c->fourcc = format_fourcc(c->format_str);
1113         if (c->fourcc == 0)  {
1114                 fprintf(stderr, "unknown format %s\n", c->format_str);
1115                 return -1;
1116         }
1117
1118         return 0;
1119 }
1120
1121 static int parse_plane(struct plane_arg *plane, const char *p)
1122 {
1123         char *end;
1124
1125         memset(plane, 0, sizeof *plane);
1126
1127         plane->crtc_id = strtoul(p, &end, 10);
1128         if (*end != ':')
1129                 return -EINVAL;
1130
1131         p = end + 1;
1132         plane->w = strtoul(p, &end, 10);
1133         if (*end != 'x')
1134                 return -EINVAL;
1135
1136         p = end + 1;
1137         plane->h = strtoul(p, &end, 10);
1138
1139         if (*end == '+' || *end == '-') {
1140                 plane->x = strtol(end, &end, 10);
1141                 if (*end != '+' && *end != '-')
1142                         return -EINVAL;
1143                 plane->y = strtol(end, &end, 10);
1144
1145                 plane->has_position = true;
1146         }
1147
1148         if (*end == '@') {
1149                 p = end + 1;
1150                 if (strlen(p) != 4)
1151                         return -EINVAL;
1152
1153                 strcpy(plane->format_str, p);
1154         } else {
1155                 strcpy(plane->format_str, "XR24");
1156         }
1157
1158         plane->fourcc = format_fourcc(plane->format_str);
1159         if (plane->fourcc == 0) {
1160                 fprintf(stderr, "unknown format %s\n", plane->format_str);
1161                 return -EINVAL;
1162         }
1163
1164         return 0;
1165 }
1166
1167 static int parse_property(struct property_arg *p, const char *arg)
1168 {
1169         if (sscanf(arg, "%d:%32[^:]:%" SCNu64, &p->obj_id, p->name, &p->value) != 3)
1170                 return -1;
1171
1172         p->obj_type = 0;
1173         p->name[DRM_PROP_NAME_LEN] = '\0';
1174
1175         return 0;
1176 }
1177
1178 static void usage(char *name)
1179 {
1180         fprintf(stderr, "usage: %s [-cdefMmPpsvw]\n", name);
1181
1182         fprintf(stderr, "\n Query options:\n\n");
1183         fprintf(stderr, "\t-c\tlist connectors\n");
1184         fprintf(stderr, "\t-e\tlist encoders\n");
1185         fprintf(stderr, "\t-f\tlist framebuffers\n");
1186         fprintf(stderr, "\t-p\tlist CRTCs and planes (pipes)\n");
1187
1188         fprintf(stderr, "\n Test options:\n\n");
1189         fprintf(stderr, "\t-P <crtc_id>:<w>x<h>[+<x>+<y>][@<format>]\tset a plane\n");
1190         fprintf(stderr, "\t-s <connector_id>[@<crtc_id>]:<mode>[@<format>]\tset a mode\n");
1191         fprintf(stderr, "\t-v\ttest vsynced page flipping\n");
1192         fprintf(stderr, "\t-w <obj_id>:<prop_name>:<value>\tset property\n");
1193
1194         fprintf(stderr, "\n Generic options:\n\n");
1195         fprintf(stderr, "\t-d\tdrop master after mode set\n");
1196         fprintf(stderr, "\t-M module\tuse the given driver\n");
1197
1198         fprintf(stderr, "\n\tDefault is to dump all info.\n");
1199         exit(0);
1200 }
1201
1202 static int page_flipping_supported(void)
1203 {
1204         /*FIXME: generic ioctl needed? */
1205         return 1;
1206 #if 0
1207         int ret, value;
1208         struct drm_i915_getparam gp;
1209
1210         gp.param = I915_PARAM_HAS_PAGEFLIPPING;
1211         gp.value = &value;
1212
1213         ret = drmCommandWriteRead(fd, DRM_I915_GETPARAM, &gp, sizeof(gp));
1214         if (ret) {
1215                 fprintf(stderr, "drm_i915_getparam: %m\n");
1216                 return 0;
1217         }
1218
1219         return *gp.value;
1220 #endif
1221 }
1222
1223 static char optstr[] = "cdefM:P:ps:vw:";
1224
1225 int main(int argc, char **argv)
1226 {
1227         struct device dev;
1228
1229         int c;
1230         int encoders = 0, connectors = 0, crtcs = 0, planes = 0, framebuffers = 0;
1231         int drop_master = 0;
1232         int test_vsync = 0;
1233         const char *modules[] = { "i915", "radeon", "nouveau", "vmwgfx", "omapdrm", "exynos", "tilcdc" };
1234         char *module = NULL;
1235         unsigned int i;
1236         int count = 0, plane_count = 0;
1237         unsigned int prop_count = 0;
1238         struct connector_arg *con_args = NULL;
1239         struct plane_arg *plane_args = NULL;
1240         struct property_arg *prop_args = NULL;
1241         unsigned int args = 0;
1242         int ret;
1243
1244         memset(&dev, 0, sizeof dev);
1245
1246         opterr = 0;
1247         while ((c = getopt(argc, argv, optstr)) != -1) {
1248                 args++;
1249
1250                 switch (c) {
1251                 case 'c':
1252                         connectors = 1;
1253                         break;
1254                 case 'd':
1255                         drop_master = 1;
1256                         break;
1257                 case 'e':
1258                         encoders = 1;
1259                         break;
1260                 case 'f':
1261                         framebuffers = 1;
1262                         break;
1263                 case 'M':
1264                         module = optarg;
1265                         /* Preserve the default behaviour of dumping all information. */
1266                         args--;
1267                         break;
1268                 case 'P':
1269                         plane_args = realloc(plane_args,
1270                                              (plane_count + 1) * sizeof *plane_args);
1271                         if (plane_args == NULL) {
1272                                 fprintf(stderr, "memory allocation failed\n");
1273                                 return 1;
1274                         }
1275
1276                         if (parse_plane(&plane_args[plane_count], optarg) < 0)
1277                                 usage(argv[0]);
1278
1279                         plane_count++;
1280                         break;
1281                 case 'p':
1282                         crtcs = 1;
1283                         planes = 1;
1284                         break;
1285                 case 's':
1286                         con_args = realloc(con_args,
1287                                            (count + 1) * sizeof *con_args);
1288                         if (con_args == NULL) {
1289                                 fprintf(stderr, "memory allocation failed\n");
1290                                 return 1;
1291                         }
1292
1293                         if (parse_connector(&con_args[count], optarg) < 0)
1294                                 usage(argv[0]);
1295
1296                         count++;                                      
1297                         break;
1298                 case 'v':
1299                         test_vsync = 1;
1300                         break;
1301                 case 'w':
1302                         prop_args = realloc(prop_args,
1303                                            (prop_count + 1) * sizeof *prop_args);
1304                         if (prop_args == NULL) {
1305                                 fprintf(stderr, "memory allocation failed\n");
1306                                 return 1;
1307                         }
1308
1309                         if (parse_property(&prop_args[prop_count], optarg) < 0)
1310                                 usage(argv[0]);
1311
1312                         prop_count++;
1313                         break;
1314                 default:
1315                         usage(argv[0]);
1316                         break;
1317                 }
1318         }
1319
1320         if (!args)
1321                 encoders = connectors = crtcs = planes = framebuffers = 1;
1322
1323         if (module) {
1324                 dev.fd = drmOpen(module, NULL);
1325                 if (dev.fd < 0) {
1326                         fprintf(stderr, "failed to open device '%s'.\n", module);
1327                         return 1;
1328                 }
1329         } else {
1330                 for (i = 0; i < ARRAY_SIZE(modules); i++) {
1331                         printf("trying to open device '%s'...", modules[i]);
1332                         dev.fd = drmOpen(modules[i], NULL);
1333                         if (dev.fd < 0) {
1334                                 printf("failed.\n");
1335                         } else {
1336                                 printf("success.\n");
1337                                 break;
1338                         }
1339                 }
1340
1341                 if (dev.fd < 0) {
1342                         fprintf(stderr, "no device found.\n");
1343                         return 1;
1344                 }
1345         }
1346
1347         if (test_vsync && !page_flipping_supported()) {
1348                 fprintf(stderr, "page flipping not supported by drm.\n");
1349                 return -1;
1350         }
1351
1352         if (test_vsync && !count) {
1353                 fprintf(stderr, "page flipping requires at least one -s option.\n");
1354                 return -1;
1355         }
1356
1357         dev.resources = get_resources(&dev);
1358         if (!dev.resources) {
1359                 drmClose(dev.fd);
1360                 return 1;
1361         }
1362
1363 #define dump_resource(dev, res) if (res) dump_##res(dev)
1364
1365         dump_resource(&dev, encoders);
1366         dump_resource(&dev, connectors);
1367         dump_resource(&dev, crtcs);
1368         dump_resource(&dev, planes);
1369         dump_resource(&dev, framebuffers);
1370
1371         for (i = 0; i < prop_count; ++i)
1372                 set_property(&dev, &prop_args[i]);
1373
1374         if (count || plane_count) {
1375                 ret = kms_create(dev.fd, &dev.kms);
1376                 if (ret) {
1377                         fprintf(stderr, "failed to create kms driver: %s\n",
1378                                 strerror(-ret));
1379                         return 1;
1380                 }
1381
1382                 if (count)
1383                         set_mode(&dev, con_args, count);
1384
1385                 if (plane_count)
1386                         set_planes(&dev, plane_args, plane_count);
1387
1388                 if (test_vsync)
1389                         test_page_flip(&dev, con_args, count);
1390
1391                 if (drop_master)
1392                         drmDropMaster(dev.fd);
1393
1394                 kms_bo_destroy(&dev.mode.bo);
1395                 kms_destroy(&dev.kms);
1396
1397                 getchar();
1398         }
1399
1400         free_resources(dev.resources);
1401
1402         return 0;
1403 }