OSDN Git Service

libdrm: Add NVIDIA Tegra support
[android-x86/external-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 #ifdef HAVE_CONFIG_H
41 #include "config.h"
42 #endif
43
44 #include <assert.h>
45 #include <ctype.h>
46 #include <stdbool.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <stdint.h>
50 #include <inttypes.h>
51 #include <unistd.h>
52 #include <string.h>
53 #include <errno.h>
54 #include <sys/poll.h>
55 #include <sys/time.h>
56
57 #include "xf86drm.h"
58 #include "xf86drmMode.h"
59 #include "drm_fourcc.h"
60 #include "libkms.h"
61
62 #include "buffers.h"
63 #include "cursor.h"
64
65 struct crtc {
66         drmModeCrtc *crtc;
67         drmModeObjectProperties *props;
68         drmModePropertyRes **props_info;
69         drmModeModeInfo *mode;
70 };
71
72 struct encoder {
73         drmModeEncoder *encoder;
74 };
75
76 struct connector {
77         drmModeConnector *connector;
78         drmModeObjectProperties *props;
79         drmModePropertyRes **props_info;
80 };
81
82 struct fb {
83         drmModeFB *fb;
84 };
85
86 struct plane {
87         drmModePlane *plane;
88         drmModeObjectProperties *props;
89         drmModePropertyRes **props_info;
90 };
91
92 struct resources {
93         drmModeRes *res;
94         drmModePlaneRes *plane_res;
95
96         struct crtc *crtcs;
97         struct encoder *encoders;
98         struct connector *connectors;
99         struct fb *fbs;
100         struct plane *planes;
101 };
102
103 struct device {
104         int fd;
105
106         struct resources *resources;
107         struct kms_driver *kms;
108
109         struct {
110                 unsigned int width;
111                 unsigned int height;
112
113                 unsigned int fb_id;
114                 struct kms_bo *bo;
115         } mode;
116 };
117
118 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
119 static inline int64_t U642I64(uint64_t val)
120 {
121         return (int64_t)*((int64_t *)&val);
122 }
123
124 struct type_name {
125         int type;
126         const char *name;
127 };
128
129 #define type_name_fn(res) \
130 const char * res##_str(int type) {                      \
131         unsigned int i;                                 \
132         for (i = 0; i < ARRAY_SIZE(res##_names); i++) { \
133                 if (res##_names[i].type == type)        \
134                         return res##_names[i].name;     \
135         }                                               \
136         return "(invalid)";                             \
137 }
138
139 struct type_name encoder_type_names[] = {
140         { DRM_MODE_ENCODER_NONE, "none" },
141         { DRM_MODE_ENCODER_DAC, "DAC" },
142         { DRM_MODE_ENCODER_TMDS, "TMDS" },
143         { DRM_MODE_ENCODER_LVDS, "LVDS" },
144         { DRM_MODE_ENCODER_TVDAC, "TVDAC" },
145 };
146
147 static type_name_fn(encoder_type)
148
149 struct type_name connector_status_names[] = {
150         { DRM_MODE_CONNECTED, "connected" },
151         { DRM_MODE_DISCONNECTED, "disconnected" },
152         { DRM_MODE_UNKNOWNCONNECTION, "unknown" },
153 };
154
155 static type_name_fn(connector_status)
156
157 struct type_name connector_type_names[] = {
158         { DRM_MODE_CONNECTOR_Unknown, "unknown" },
159         { DRM_MODE_CONNECTOR_VGA, "VGA" },
160         { DRM_MODE_CONNECTOR_DVII, "DVI-I" },
161         { DRM_MODE_CONNECTOR_DVID, "DVI-D" },
162         { DRM_MODE_CONNECTOR_DVIA, "DVI-A" },
163         { DRM_MODE_CONNECTOR_Composite, "composite" },
164         { DRM_MODE_CONNECTOR_SVIDEO, "s-video" },
165         { DRM_MODE_CONNECTOR_LVDS, "LVDS" },
166         { DRM_MODE_CONNECTOR_Component, "component" },
167         { DRM_MODE_CONNECTOR_9PinDIN, "9-pin DIN" },
168         { DRM_MODE_CONNECTOR_DisplayPort, "DP" },
169         { DRM_MODE_CONNECTOR_HDMIA, "HDMI-A" },
170         { DRM_MODE_CONNECTOR_HDMIB, "HDMI-B" },
171         { DRM_MODE_CONNECTOR_TV, "TV" },
172         { DRM_MODE_CONNECTOR_eDP, "eDP" },
173 };
174
175 static type_name_fn(connector_type)
176
177 #define bit_name_fn(res)                                        \
178 const char * res##_str(int type) {                              \
179         unsigned int i;                                         \
180         const char *sep = "";                                   \
181         for (i = 0; i < ARRAY_SIZE(res##_names); i++) {         \
182                 if (type & (1 << i)) {                          \
183                         printf("%s%s", sep, res##_names[i]);    \
184                         sep = ", ";                             \
185                 }                                               \
186         }                                                       \
187         return NULL;                                            \
188 }
189
190 static const char *mode_type_names[] = {
191         "builtin",
192         "clock_c",
193         "crtc_c",
194         "preferred",
195         "default",
196         "userdef",
197         "driver",
198 };
199
200 static bit_name_fn(mode_type)
201
202 static const char *mode_flag_names[] = {
203         "phsync",
204         "nhsync",
205         "pvsync",
206         "nvsync",
207         "interlace",
208         "dblscan",
209         "csync",
210         "pcsync",
211         "ncsync",
212         "hskew",
213         "bcast",
214         "pixmux",
215         "dblclk",
216         "clkdiv2"
217 };
218
219 static bit_name_fn(mode_flag)
220
221 static void dump_encoders(struct device *dev)
222 {
223         drmModeEncoder *encoder;
224         int i;
225
226         printf("Encoders:\n");
227         printf("id\tcrtc\ttype\tpossible crtcs\tpossible clones\t\n");
228         for (i = 0; i < dev->resources->res->count_encoders; i++) {
229                 encoder = dev->resources->encoders[i].encoder;
230                 if (!encoder)
231                         continue;
232
233                 printf("%d\t%d\t%s\t0x%08x\t0x%08x\n",
234                        encoder->encoder_id,
235                        encoder->crtc_id,
236                        encoder_type_str(encoder->encoder_type),
237                        encoder->possible_crtcs,
238                        encoder->possible_clones);
239         }
240         printf("\n");
241 }
242
243 static void dump_mode(drmModeModeInfo *mode)
244 {
245         printf("  %s %d %d %d %d %d %d %d %d %d",
246                mode->name,
247                mode->vrefresh,
248                mode->hdisplay,
249                mode->hsync_start,
250                mode->hsync_end,
251                mode->htotal,
252                mode->vdisplay,
253                mode->vsync_start,
254                mode->vsync_end,
255                mode->vtotal);
256
257         printf(" flags: ");
258         mode_flag_str(mode->flags);
259         printf("; type: ");
260         mode_type_str(mode->type);
261         printf("\n");
262 }
263
264 static void dump_blob(struct device *dev, uint32_t blob_id)
265 {
266         uint32_t i;
267         unsigned char *blob_data;
268         drmModePropertyBlobPtr blob;
269
270         blob = drmModeGetPropertyBlob(dev->fd, blob_id);
271         if (!blob) {
272                 printf("\n");
273                 return;
274         }
275
276         blob_data = blob->data;
277
278         for (i = 0; i < blob->length; i++) {
279                 if (i % 16 == 0)
280                         printf("\n\t\t\t");
281                 printf("%.2hhx", blob_data[i]);
282         }
283         printf("\n");
284
285         drmModeFreePropertyBlob(blob);
286 }
287
288 static void dump_prop(struct device *dev, drmModePropertyPtr prop,
289                       uint32_t prop_id, uint64_t value)
290 {
291         int i;
292         printf("\t%d", prop_id);
293         if (!prop) {
294                 printf("\n");
295                 return;
296         }
297
298         printf(" %s:\n", prop->name);
299
300         printf("\t\tflags:");
301         if (prop->flags & DRM_MODE_PROP_PENDING)
302                 printf(" pending");
303         if (prop->flags & DRM_MODE_PROP_IMMUTABLE)
304                 printf(" immutable");
305         if (drm_property_type_is(prop, DRM_MODE_PROP_SIGNED_RANGE))
306                 printf(" signed range");
307         if (drm_property_type_is(prop, DRM_MODE_PROP_RANGE))
308                 printf(" range");
309         if (drm_property_type_is(prop, DRM_MODE_PROP_ENUM))
310                 printf(" enum");
311         if (drm_property_type_is(prop, DRM_MODE_PROP_BITMASK))
312                 printf(" bitmask");
313         if (drm_property_type_is(prop, DRM_MODE_PROP_BLOB))
314                 printf(" blob");
315         if (drm_property_type_is(prop, DRM_MODE_PROP_OBJECT))
316                 printf(" object");
317         printf("\n");
318
319         if (drm_property_type_is(prop, DRM_MODE_PROP_SIGNED_RANGE)) {
320                 printf("\t\tvalues:");
321                 for (i = 0; i < prop->count_values; i++)
322                         printf(" %"PRId64, U642I64(prop->values[i]));
323                 printf("\n");
324         }
325
326         if (drm_property_type_is(prop, DRM_MODE_PROP_RANGE)) {
327                 printf("\t\tvalues:");
328                 for (i = 0; i < prop->count_values; i++)
329                         printf(" %"PRIu64, prop->values[i]);
330                 printf("\n");
331         }
332
333         if (drm_property_type_is(prop, DRM_MODE_PROP_ENUM)) {
334                 printf("\t\tenums:");
335                 for (i = 0; i < prop->count_enums; i++)
336                         printf(" %s=%llu", prop->enums[i].name,
337                                prop->enums[i].value);
338                 printf("\n");
339         } else if (drm_property_type_is(prop, DRM_MODE_PROP_BITMASK)) {
340                 printf("\t\tvalues:");
341                 for (i = 0; i < prop->count_enums; i++)
342                         printf(" %s=0x%llx", prop->enums[i].name,
343                                (1LL << prop->enums[i].value));
344                 printf("\n");
345         } else {
346                 assert(prop->count_enums == 0);
347         }
348
349         if (drm_property_type_is(prop, DRM_MODE_PROP_BLOB)) {
350                 printf("\t\tblobs:\n");
351                 for (i = 0; i < prop->count_blobs; i++)
352                         dump_blob(dev, prop->blob_ids[i]);
353                 printf("\n");
354         } else {
355                 assert(prop->count_blobs == 0);
356         }
357
358         printf("\t\tvalue:");
359         if (drm_property_type_is(prop, DRM_MODE_PROP_BLOB))
360                 dump_blob(dev, value);
361         else
362                 printf(" %"PRIu64"\n", value);
363 }
364
365 static void dump_connectors(struct device *dev)
366 {
367         int i, j;
368
369         printf("Connectors:\n");
370         printf("id\tencoder\tstatus\t\ttype\tsize (mm)\tmodes\tencoders\n");
371         for (i = 0; i < dev->resources->res->count_connectors; i++) {
372                 struct connector *_connector = &dev->resources->connectors[i];
373                 drmModeConnector *connector = _connector->connector;
374                 if (!connector)
375                         continue;
376
377                 printf("%d\t%d\t%s\t%s\t%dx%d\t\t%d\t",
378                        connector->connector_id,
379                        connector->encoder_id,
380                        connector_status_str(connector->connection),
381                        connector_type_str(connector->connector_type),
382                        connector->mmWidth, connector->mmHeight,
383                        connector->count_modes);
384
385                 for (j = 0; j < connector->count_encoders; j++)
386                         printf("%s%d", j > 0 ? ", " : "", connector->encoders[j]);
387                 printf("\n");
388
389                 if (connector->count_modes) {
390                         printf("  modes:\n");
391                         printf("\tname refresh (Hz) hdisp hss hse htot vdisp "
392                                "vss vse vtot)\n");
393                         for (j = 0; j < connector->count_modes; j++)
394                                 dump_mode(&connector->modes[j]);
395                 }
396
397                 if (_connector->props) {
398                         printf("  props:\n");
399                         for (j = 0; j < (int)_connector->props->count_props; j++)
400                                 dump_prop(dev, _connector->props_info[j],
401                                           _connector->props->props[j],
402                                           _connector->props->prop_values[j]);
403                 }
404         }
405         printf("\n");
406 }
407
408 static void dump_crtcs(struct device *dev)
409 {
410         int i;
411         uint32_t j;
412
413         printf("CRTCs:\n");
414         printf("id\tfb\tpos\tsize\n");
415         for (i = 0; i < dev->resources->res->count_crtcs; i++) {
416                 struct crtc *_crtc = &dev->resources->crtcs[i];
417                 drmModeCrtc *crtc = _crtc->crtc;
418                 if (!crtc)
419                         continue;
420
421                 printf("%d\t%d\t(%d,%d)\t(%dx%d)\n",
422                        crtc->crtc_id,
423                        crtc->buffer_id,
424                        crtc->x, crtc->y,
425                        crtc->width, crtc->height);
426                 dump_mode(&crtc->mode);
427
428                 if (_crtc->props) {
429                         printf("  props:\n");
430                         for (j = 0; j < _crtc->props->count_props; j++)
431                                 dump_prop(dev, _crtc->props_info[j],
432                                           _crtc->props->props[j],
433                                           _crtc->props->prop_values[j]);
434                 } else {
435                         printf("  no properties found\n");
436                 }
437         }
438         printf("\n");
439 }
440
441 static void dump_framebuffers(struct device *dev)
442 {
443         drmModeFB *fb;
444         int i;
445
446         printf("Frame buffers:\n");
447         printf("id\tsize\tpitch\n");
448         for (i = 0; i < dev->resources->res->count_fbs; i++) {
449                 fb = dev->resources->fbs[i].fb;
450                 if (!fb)
451                         continue;
452
453                 printf("%u\t(%ux%u)\t%u\n",
454                        fb->fb_id,
455                        fb->width, fb->height,
456                        fb->pitch);
457         }
458         printf("\n");
459 }
460
461 static void dump_planes(struct device *dev)
462 {
463         unsigned int i, j;
464
465         printf("Planes:\n");
466         printf("id\tcrtc\tfb\tCRTC x,y\tx,y\tgamma size\tpossible crtcs\n");
467
468         if (!dev->resources->plane_res)
469                 return;
470
471         for (i = 0; i < dev->resources->plane_res->count_planes; i++) {
472                 struct plane *plane = &dev->resources->planes[i];
473                 drmModePlane *ovr = plane->plane;
474                 if (!ovr)
475                         continue;
476
477                 printf("%d\t%d\t%d\t%d,%d\t\t%d,%d\t%-8d\t0x%08x\n",
478                        ovr->plane_id, ovr->crtc_id, ovr->fb_id,
479                        ovr->crtc_x, ovr->crtc_y, ovr->x, ovr->y,
480                        ovr->gamma_size, ovr->possible_crtcs);
481
482                 if (!ovr->count_formats)
483                         continue;
484
485                 printf("  formats:");
486                 for (j = 0; j < ovr->count_formats; j++)
487                         printf(" %4.4s", (char *)&ovr->formats[j]);
488                 printf("\n");
489
490                 if (plane->props) {
491                         printf("  props:\n");
492                         for (j = 0; j < plane->props->count_props; j++)
493                                 dump_prop(dev, plane->props_info[j],
494                                           plane->props->props[j],
495                                           plane->props->prop_values[j]);
496                 } else {
497                         printf("  no properties found\n");
498                 }
499         }
500         printf("\n");
501
502         return;
503 }
504
505 static void free_resources(struct resources *res)
506 {
507         if (!res)
508                 return;
509
510 #define free_resource(_res, __res, type, Type)                                  \
511         do {                                                                    \
512                 int i;                                                          \
513                 if (!(_res)->type##s)                                           \
514                         break;                                                  \
515                 for (i = 0; i < (int)(_res)->__res->count_##type##s; ++i) {     \
516                         if (!(_res)->type##s[i].type)                           \
517                                 break;                                          \
518                         drmModeFree##Type((_res)->type##s[i].type);             \
519                 }                                                               \
520                 free((_res)->type##s);                                          \
521         } while (0)
522
523 #define free_properties(_res, __res, type)                                      \
524         do {                                                                    \
525                 int i;                                                          \
526                 for (i = 0; i < (int)(_res)->__res->count_##type##s; ++i) {     \
527                         drmModeFreeObjectProperties(res->type##s[i].props);     \
528                         free(res->type##s[i].props_info);                       \
529                 }                                                               \
530         } while (0)
531
532         if (res->res) {
533                 free_properties(res, res, crtc);
534
535                 free_resource(res, res, crtc, Crtc);
536                 free_resource(res, res, encoder, Encoder);
537                 free_resource(res, res, connector, Connector);
538                 free_resource(res, res, fb, FB);
539
540                 drmModeFreeResources(res->res);
541         }
542
543         if (res->plane_res) {
544                 free_properties(res, plane_res, plane);
545
546                 free_resource(res, plane_res, plane, Plane);
547
548                 drmModeFreePlaneResources(res->plane_res);
549         }
550
551         free(res);
552 }
553
554 static struct resources *get_resources(struct device *dev)
555 {
556         struct resources *res;
557         int i;
558
559         res = malloc(sizeof *res);
560         if (res == 0)
561                 return NULL;
562
563         memset(res, 0, sizeof *res);
564
565         drmSetClientCap(dev->fd, DRM_CLIENT_CAP_UNIVERSAL_PLANES, 1);
566
567         res->res = drmModeGetResources(dev->fd);
568         if (!res->res) {
569                 fprintf(stderr, "drmModeGetResources failed: %s\n",
570                         strerror(errno));
571                 goto error;
572         }
573
574         res->crtcs = malloc(res->res->count_crtcs * sizeof *res->crtcs);
575         res->encoders = malloc(res->res->count_encoders * sizeof *res->encoders);
576         res->connectors = malloc(res->res->count_connectors * sizeof *res->connectors);
577         res->fbs = malloc(res->res->count_fbs * sizeof *res->fbs);
578
579         if (!res->crtcs || !res->encoders || !res->connectors || !res->fbs)
580                 goto error;
581
582         memset(res->crtcs , 0, res->res->count_crtcs * sizeof *res->crtcs);
583         memset(res->encoders, 0, res->res->count_encoders * sizeof *res->encoders);
584         memset(res->connectors, 0, res->res->count_connectors * sizeof *res->connectors);
585         memset(res->fbs, 0, res->res->count_fbs * sizeof *res->fbs);
586
587 #define get_resource(_res, __res, type, Type)                                   \
588         do {                                                                    \
589                 int i;                                                          \
590                 for (i = 0; i < (int)(_res)->__res->count_##type##s; ++i) {     \
591                         (_res)->type##s[i].type =                               \
592                                 drmModeGet##Type(dev->fd, (_res)->__res->type##s[i]); \
593                         if (!(_res)->type##s[i].type)                           \
594                                 fprintf(stderr, "could not get %s %i: %s\n",    \
595                                         #type, (_res)->__res->type##s[i],       \
596                                         strerror(errno));                       \
597                 }                                                               \
598         } while (0)
599
600         get_resource(res, res, crtc, Crtc);
601         get_resource(res, res, encoder, Encoder);
602         get_resource(res, res, connector, Connector);
603         get_resource(res, res, fb, FB);
604
605 #define get_properties(_res, __res, type, Type)                                 \
606         do {                                                                    \
607                 int i;                                                          \
608                 for (i = 0; i < (int)(_res)->__res->count_##type##s; ++i) {     \
609                         struct type *obj = &res->type##s[i];                    \
610                         unsigned int j;                                         \
611                         obj->props =                                            \
612                                 drmModeObjectGetProperties(dev->fd, obj->type->type##_id, \
613                                                            DRM_MODE_OBJECT_##Type); \
614                         if (!obj->props) {                                      \
615                                 fprintf(stderr,                                 \
616                                         "could not get %s %i properties: %s\n", \
617                                         #type, obj->type->type##_id,            \
618                                         strerror(errno));                       \
619                                 continue;                                       \
620                         }                                                       \
621                         obj->props_info = malloc(obj->props->count_props *      \
622                                                  sizeof *obj->props_info);      \
623                         if (!obj->props_info)                                   \
624                                 continue;                                       \
625                         for (j = 0; j < obj->props->count_props; ++j)           \
626                                 obj->props_info[j] =                            \
627                                         drmModeGetProperty(dev->fd, obj->props->props[j]); \
628                 }                                                               \
629         } while (0)
630
631         get_properties(res, res, crtc, CRTC);
632         get_properties(res, res, connector, CONNECTOR);
633
634         for (i = 0; i < res->res->count_crtcs; ++i)
635                 res->crtcs[i].mode = &res->crtcs[i].crtc->mode;
636
637         res->plane_res = drmModeGetPlaneResources(dev->fd);
638         if (!res->plane_res) {
639                 fprintf(stderr, "drmModeGetPlaneResources failed: %s\n",
640                         strerror(errno));
641                 return res;
642         }
643
644         res->planes = malloc(res->plane_res->count_planes * sizeof *res->planes);
645         if (!res->planes)
646                 goto error;
647
648         memset(res->planes, 0, res->plane_res->count_planes * sizeof *res->planes);
649
650         get_resource(res, plane_res, plane, Plane);
651         get_properties(res, plane_res, plane, PLANE);
652
653         return res;
654
655 error:
656         free_resources(res);
657         return NULL;
658 }
659
660 static int get_crtc_index(struct device *dev, uint32_t id)
661 {
662         int i;
663
664         for (i = 0; i < dev->resources->res->count_crtcs; ++i) {
665                 drmModeCrtc *crtc = dev->resources->crtcs[i].crtc;
666                 if (crtc && crtc->crtc_id == id)
667                         return i;
668         }
669
670         return -1;
671 }
672
673 static drmModeConnector *get_connector_by_id(struct device *dev, uint32_t id)
674 {
675         drmModeConnector *connector;
676         int i;
677
678         for (i = 0; i < dev->resources->res->count_connectors; i++) {
679                 connector = dev->resources->connectors[i].connector;
680                 if (connector && connector->connector_id == id)
681                         return connector;
682         }
683
684         return NULL;
685 }
686
687 static drmModeEncoder *get_encoder_by_id(struct device *dev, uint32_t id)
688 {
689         drmModeEncoder *encoder;
690         int i;
691
692         for (i = 0; i < dev->resources->res->count_encoders; i++) {
693                 encoder = dev->resources->encoders[i].encoder;
694                 if (encoder && encoder->encoder_id == id)
695                         return encoder;
696         }
697
698         return NULL;
699 }
700
701 /* -----------------------------------------------------------------------------
702  * Pipes and planes
703  */
704
705 /*
706  * Mode setting with the kernel interfaces is a bit of a chore.
707  * First you have to find the connector in question and make sure the
708  * requested mode is available.
709  * Then you need to find the encoder attached to that connector so you
710  * can bind it with a free crtc.
711  */
712 struct pipe_arg {
713         uint32_t *con_ids;
714         unsigned int num_cons;
715         uint32_t crtc_id;
716         char mode_str[64];
717         char format_str[5];
718         unsigned int vrefresh;
719         unsigned int fourcc;
720         drmModeModeInfo *mode;
721         struct crtc *crtc;
722         unsigned int fb_id[2], current_fb_id;
723         struct timeval start;
724
725         int swap_count;
726 };
727
728 struct plane_arg {
729         uint32_t crtc_id;  /* the id of CRTC to bind to */
730         bool has_position;
731         int32_t x, y;
732         uint32_t w, h;
733         double scale;
734         unsigned int fb_id;
735         char format_str[5]; /* need to leave room for terminating \0 */
736         unsigned int fourcc;
737 };
738
739 static drmModeModeInfo *
740 connector_find_mode(struct device *dev, uint32_t con_id, const char *mode_str,
741         const unsigned int vrefresh)
742 {
743         drmModeConnector *connector;
744         drmModeModeInfo *mode;
745         int i;
746
747         connector = get_connector_by_id(dev, con_id);
748         if (!connector || !connector->count_modes)
749                 return NULL;
750
751         for (i = 0; i < connector->count_modes; i++) {
752                 mode = &connector->modes[i];
753                 if (!strcmp(mode->name, mode_str)) {
754                         /* If the vertical refresh frequency is not specified then return the
755                          * first mode that match with the name. Else, return the mode that match
756                          * the name and the specified vertical refresh frequency.
757                          */
758                         if (vrefresh == 0)
759                                 return mode;
760                         else if (mode->vrefresh == vrefresh)
761                                 return mode;
762                 }
763         }
764
765         return NULL;
766 }
767
768 static struct crtc *pipe_find_crtc(struct device *dev, struct pipe_arg *pipe)
769 {
770         uint32_t possible_crtcs = ~0;
771         uint32_t active_crtcs = 0;
772         unsigned int crtc_idx;
773         unsigned int i;
774         int j;
775
776         for (i = 0; i < pipe->num_cons; ++i) {
777                 uint32_t crtcs_for_connector = 0;
778                 drmModeConnector *connector;
779                 drmModeEncoder *encoder;
780                 int idx;
781
782                 connector = get_connector_by_id(dev, pipe->con_ids[i]);
783                 if (!connector)
784                         return NULL;
785
786                 for (j = 0; j < connector->count_encoders; ++j) {
787                         encoder = get_encoder_by_id(dev, connector->encoders[j]);
788                         if (!encoder)
789                                 continue;
790
791                         crtcs_for_connector |= encoder->possible_crtcs;
792
793                         idx = get_crtc_index(dev, encoder->crtc_id);
794                         if (idx >= 0)
795                                 active_crtcs |= 1 << idx;
796                 }
797
798                 possible_crtcs &= crtcs_for_connector;
799         }
800
801         if (!possible_crtcs)
802                 return NULL;
803
804         /* Return the first possible and active CRTC if one exists, or the first
805          * possible CRTC otherwise.
806          */
807         if (possible_crtcs & active_crtcs)
808                 crtc_idx = ffs(possible_crtcs & active_crtcs);
809         else
810                 crtc_idx = ffs(possible_crtcs);
811
812         return &dev->resources->crtcs[crtc_idx - 1];
813 }
814
815 static int pipe_find_crtc_and_mode(struct device *dev, struct pipe_arg *pipe)
816 {
817         drmModeModeInfo *mode = NULL;
818         int i;
819
820         pipe->mode = NULL;
821
822         for (i = 0; i < (int)pipe->num_cons; i++) {
823                 mode = connector_find_mode(dev, pipe->con_ids[i],
824                                            pipe->mode_str, pipe->vrefresh);
825                 if (mode == NULL) {
826                         fprintf(stderr,
827                                 "failed to find mode \"%s\" for connector %u\n",
828                                 pipe->mode_str, pipe->con_ids[i]);
829                         return -EINVAL;
830                 }
831         }
832
833         /* If the CRTC ID was specified, get the corresponding CRTC. Otherwise
834          * locate a CRTC that can be attached to all the connectors.
835          */
836         if (pipe->crtc_id != (uint32_t)-1) {
837                 for (i = 0; i < dev->resources->res->count_crtcs; i++) {
838                         struct crtc *crtc = &dev->resources->crtcs[i];
839
840                         if (pipe->crtc_id == crtc->crtc->crtc_id) {
841                                 pipe->crtc = crtc;
842                                 break;
843                         }
844                 }
845         } else {
846                 pipe->crtc = pipe_find_crtc(dev, pipe);
847         }
848
849         if (!pipe->crtc) {
850                 fprintf(stderr, "failed to find CRTC for pipe\n");
851                 return -EINVAL;
852         }
853
854         pipe->mode = mode;
855         pipe->crtc->mode = mode;
856
857         return 0;
858 }
859
860 /* -----------------------------------------------------------------------------
861  * Properties
862  */
863
864 struct property_arg {
865         uint32_t obj_id;
866         uint32_t obj_type;
867         char name[DRM_PROP_NAME_LEN+1];
868         uint32_t prop_id;
869         uint64_t value;
870 };
871
872 static void set_property(struct device *dev, struct property_arg *p)
873 {
874         drmModeObjectProperties *props = NULL;
875         drmModePropertyRes **props_info = NULL;
876         const char *obj_type;
877         int ret;
878         int i;
879
880         p->obj_type = 0;
881         p->prop_id = 0;
882
883 #define find_object(_res, __res, type, Type)                                    \
884         do {                                                                    \
885                 for (i = 0; i < (int)(_res)->__res->count_##type##s; ++i) {     \
886                         struct type *obj = &(_res)->type##s[i];                 \
887                         if (obj->type->type##_id != p->obj_id)                  \
888                                 continue;                                       \
889                         p->obj_type = DRM_MODE_OBJECT_##Type;                   \
890                         obj_type = #Type;                                       \
891                         props = obj->props;                                     \
892                         props_info = obj->props_info;                           \
893                 }                                                               \
894         } while(0)                                                              \
895
896         find_object(dev->resources, res, crtc, CRTC);
897         if (p->obj_type == 0)
898                 find_object(dev->resources, res, connector, CONNECTOR);
899         if (p->obj_type == 0)
900                 find_object(dev->resources, plane_res, plane, PLANE);
901         if (p->obj_type == 0) {
902                 fprintf(stderr, "Object %i not found, can't set property\n",
903                         p->obj_id);
904                         return;
905         }
906
907         if (!props) {
908                 fprintf(stderr, "%s %i has no properties\n",
909                         obj_type, p->obj_id);
910                 return;
911         }
912
913         for (i = 0; i < (int)props->count_props; ++i) {
914                 if (!props_info[i])
915                         continue;
916                 if (strcmp(props_info[i]->name, p->name) == 0)
917                         break;
918         }
919
920         if (i == (int)props->count_props) {
921                 fprintf(stderr, "%s %i has no %s property\n",
922                         obj_type, p->obj_id, p->name);
923                 return;
924         }
925
926         p->prop_id = props->props[i];
927
928         ret = drmModeObjectSetProperty(dev->fd, p->obj_id, p->obj_type,
929                                        p->prop_id, p->value);
930         if (ret < 0)
931                 fprintf(stderr, "failed to set %s %i property %s to %" PRIu64 ": %s\n",
932                         obj_type, p->obj_id, p->name, p->value, strerror(errno));
933 }
934
935 /* -------------------------------------------------------------------------- */
936
937 static void
938 page_flip_handler(int fd, unsigned int frame,
939                   unsigned int sec, unsigned int usec, void *data)
940 {
941         struct pipe_arg *pipe;
942         unsigned int new_fb_id;
943         struct timeval end;
944         double t;
945
946         pipe = data;
947         if (pipe->current_fb_id == pipe->fb_id[0])
948                 new_fb_id = pipe->fb_id[1];
949         else
950                 new_fb_id = pipe->fb_id[0];
951
952         drmModePageFlip(fd, pipe->crtc->crtc->crtc_id, new_fb_id,
953                         DRM_MODE_PAGE_FLIP_EVENT, pipe);
954         pipe->current_fb_id = new_fb_id;
955         pipe->swap_count++;
956         if (pipe->swap_count == 60) {
957                 gettimeofday(&end, NULL);
958                 t = end.tv_sec + end.tv_usec * 1e-6 -
959                         (pipe->start.tv_sec + pipe->start.tv_usec * 1e-6);
960                 fprintf(stderr, "freq: %.02fHz\n", pipe->swap_count / t);
961                 pipe->swap_count = 0;
962                 pipe->start = end;
963         }
964 }
965
966 static int set_plane(struct device *dev, struct plane_arg *p)
967 {
968         drmModePlane *ovr;
969         uint32_t handles[4], pitches[4], offsets[4] = {0}; /* we only use [0] */
970         uint32_t plane_id = 0;
971         struct kms_bo *plane_bo;
972         uint32_t plane_flags = 0;
973         int crtc_x, crtc_y, crtc_w, crtc_h;
974         struct crtc *crtc = NULL;
975         unsigned int pipe;
976         unsigned int i;
977
978         /* Find an unused plane which can be connected to our CRTC. Find the
979          * CRTC index first, then iterate over available planes.
980          */
981         for (i = 0; i < (unsigned int)dev->resources->res->count_crtcs; i++) {
982                 if (p->crtc_id == dev->resources->res->crtcs[i]) {
983                         crtc = &dev->resources->crtcs[i];
984                         pipe = i;
985                         break;
986                 }
987         }
988
989         if (!crtc) {
990                 fprintf(stderr, "CRTC %u not found\n", p->crtc_id);
991                 return -1;
992         }
993
994         for (i = 0; i < dev->resources->plane_res->count_planes && !plane_id; i++) {
995                 ovr = dev->resources->planes[i].plane;
996                 if (!ovr)
997                         continue;
998
999                 if ((ovr->possible_crtcs & (1 << pipe)) && !ovr->crtc_id)
1000                         plane_id = ovr->plane_id;
1001         }
1002
1003         if (!plane_id) {
1004                 fprintf(stderr, "no unused plane available for CRTC %u\n",
1005                         crtc->crtc->crtc_id);
1006                 return -1;
1007         }
1008
1009         fprintf(stderr, "testing %dx%d@%s overlay plane %u\n",
1010                 p->w, p->h, p->format_str, plane_id);
1011
1012         plane_bo = create_test_buffer(dev->kms, p->fourcc, p->w, p->h, handles,
1013                                       pitches, offsets, PATTERN_TILES);
1014         if (plane_bo == NULL)
1015                 return -1;
1016
1017         /* just use single plane format for now.. */
1018         if (drmModeAddFB2(dev->fd, p->w, p->h, p->fourcc,
1019                         handles, pitches, offsets, &p->fb_id, plane_flags)) {
1020                 fprintf(stderr, "failed to add fb: %s\n", strerror(errno));
1021                 return -1;
1022         }
1023
1024         crtc_w = p->w * p->scale;
1025         crtc_h = p->h * p->scale;
1026         if (!p->has_position) {
1027                 /* Default to the middle of the screen */
1028                 crtc_x = (crtc->mode->hdisplay - crtc_w) / 2;
1029                 crtc_y = (crtc->mode->vdisplay - crtc_h) / 2;
1030         } else {
1031                 crtc_x = p->x;
1032                 crtc_y = p->y;
1033         }
1034
1035         /* note src coords (last 4 args) are in Q16 format */
1036         if (drmModeSetPlane(dev->fd, plane_id, crtc->crtc->crtc_id, p->fb_id,
1037                             plane_flags, crtc_x, crtc_y, crtc_w, crtc_h,
1038                             0, 0, p->w << 16, p->h << 16)) {
1039                 fprintf(stderr, "failed to enable plane: %s\n",
1040                         strerror(errno));
1041                 return -1;
1042         }
1043
1044         ovr->crtc_id = crtc->crtc->crtc_id;
1045
1046         return 0;
1047 }
1048
1049 static void set_mode(struct device *dev, struct pipe_arg *pipes, unsigned int count)
1050 {
1051         uint32_t handles[4], pitches[4], offsets[4] = {0}; /* we only use [0] */
1052         unsigned int fb_id;
1053         struct kms_bo *bo;
1054         unsigned int i;
1055         unsigned int j;
1056         int ret, x;
1057
1058         dev->mode.width = 0;
1059         dev->mode.height = 0;
1060
1061         for (i = 0; i < count; i++) {
1062                 struct pipe_arg *pipe = &pipes[i];
1063
1064                 ret = pipe_find_crtc_and_mode(dev, pipe);
1065                 if (ret < 0)
1066                         continue;
1067
1068                 dev->mode.width += pipe->mode->hdisplay;
1069                 if (dev->mode.height < pipe->mode->vdisplay)
1070                         dev->mode.height = pipe->mode->vdisplay;
1071         }
1072
1073         bo = create_test_buffer(dev->kms, pipes[0].fourcc,
1074                                 dev->mode.width, dev->mode.height,
1075                                 handles, pitches, offsets, PATTERN_SMPTE);
1076         if (bo == NULL)
1077                 return;
1078
1079         ret = drmModeAddFB2(dev->fd, dev->mode.width, dev->mode.height,
1080                             pipes[0].fourcc, handles, pitches, offsets, &fb_id, 0);
1081         if (ret) {
1082                 fprintf(stderr, "failed to add fb (%ux%u): %s\n",
1083                         dev->mode.width, dev->mode.height, strerror(errno));
1084                 return;
1085         }
1086
1087         x = 0;
1088         for (i = 0; i < count; i++) {
1089                 struct pipe_arg *pipe = &pipes[i];
1090
1091                 if (pipe->mode == NULL)
1092                         continue;
1093
1094                 printf("setting mode %s-%dHz@%s on connectors ",
1095                        pipe->mode_str, pipe->mode->vrefresh, pipe->format_str);
1096                 for (j = 0; j < pipe->num_cons; ++j)
1097                         printf("%u, ", pipe->con_ids[j]);
1098                 printf("crtc %d\n", pipe->crtc->crtc->crtc_id);
1099
1100                 ret = drmModeSetCrtc(dev->fd, pipe->crtc->crtc->crtc_id, fb_id,
1101                                      x, 0, pipe->con_ids, pipe->num_cons,
1102                                      pipe->mode);
1103
1104                 /* XXX: Actually check if this is needed */
1105                 drmModeDirtyFB(dev->fd, fb_id, NULL, 0);
1106
1107                 x += pipe->mode->hdisplay;
1108
1109                 if (ret) {
1110                         fprintf(stderr, "failed to set mode: %s\n", strerror(errno));
1111                         return;
1112                 }
1113         }
1114
1115         dev->mode.bo = bo;
1116         dev->mode.fb_id = fb_id;
1117 }
1118
1119 static void set_planes(struct device *dev, struct plane_arg *p, unsigned int count)
1120 {
1121         unsigned int i;
1122
1123         /* set up planes/overlays */
1124         for (i = 0; i < count; i++)
1125                 if (set_plane(dev, &p[i]))
1126                         return;
1127 }
1128
1129 static void set_cursors(struct device *dev, struct pipe_arg *pipes, unsigned int count)
1130 {
1131         uint32_t handles[4], pitches[4], offsets[4] = {0}; /* we only use [0] */
1132         struct kms_bo *bo;
1133         unsigned int i;
1134         int ret;
1135
1136         /* maybe make cursor width/height configurable some day */
1137         uint32_t cw = 64;
1138         uint32_t ch = 64;
1139
1140         /* create cursor bo.. just using PATTERN_PLAIN as it has
1141          * translucent alpha
1142          */
1143         bo = create_test_buffer(dev->kms, DRM_FORMAT_ARGB8888,
1144                         cw, ch, handles, pitches, offsets, PATTERN_PLAIN);
1145         if (bo == NULL)
1146                 return;
1147
1148         for (i = 0; i < count; i++) {
1149                 struct pipe_arg *pipe = &pipes[i];
1150                 ret = cursor_init(dev->fd, handles[0],
1151                                 pipe->crtc->crtc->crtc_id,
1152                                 pipe->mode->hdisplay, pipe->mode->vdisplay,
1153                                 cw, ch);
1154                 if (ret) {
1155                         fprintf(stderr, "failed to init cursor for CRTC[%u]\n",
1156                                         pipe->crtc_id);
1157                         return;
1158                 }
1159         }
1160
1161         cursor_start();
1162 }
1163
1164 static void clear_cursors(struct device *dev)
1165 {
1166         cursor_stop();
1167 }
1168
1169 static void test_page_flip(struct device *dev, struct pipe_arg *pipes, unsigned int count)
1170 {
1171         uint32_t handles[4], pitches[4], offsets[4] = {0}; /* we only use [0] */
1172         unsigned int other_fb_id;
1173         struct kms_bo *other_bo;
1174         drmEventContext evctx;
1175         unsigned int i;
1176         int ret;
1177
1178         other_bo = create_test_buffer(dev->kms, pipes[0].fourcc,
1179                                       dev->mode.width, dev->mode.height,
1180                                       handles, pitches, offsets, PATTERN_PLAIN);
1181         if (other_bo == NULL)
1182                 return;
1183
1184         ret = drmModeAddFB2(dev->fd, dev->mode.width, dev->mode.height,
1185                             pipes[0].fourcc, handles, pitches, offsets,
1186                             &other_fb_id, 0);
1187         if (ret) {
1188                 fprintf(stderr, "failed to add fb: %s\n", strerror(errno));
1189                 return;
1190         }
1191
1192         for (i = 0; i < count; i++) {
1193                 struct pipe_arg *pipe = &pipes[i];
1194
1195                 if (pipe->mode == NULL)
1196                         continue;
1197
1198                 ret = drmModePageFlip(dev->fd, pipe->crtc->crtc->crtc_id,
1199                                       other_fb_id, DRM_MODE_PAGE_FLIP_EVENT,
1200                                       pipe);
1201                 if (ret) {
1202                         fprintf(stderr, "failed to page flip: %s\n", strerror(errno));
1203                         return;
1204                 }
1205                 gettimeofday(&pipe->start, NULL);
1206                 pipe->swap_count = 0;
1207                 pipe->fb_id[0] = dev->mode.fb_id;
1208                 pipe->fb_id[1] = other_fb_id;
1209                 pipe->current_fb_id = other_fb_id;
1210         }
1211
1212         memset(&evctx, 0, sizeof evctx);
1213         evctx.version = DRM_EVENT_CONTEXT_VERSION;
1214         evctx.vblank_handler = NULL;
1215         evctx.page_flip_handler = page_flip_handler;
1216         
1217         while (1) {
1218 #if 0
1219                 struct pollfd pfd[2];
1220
1221                 pfd[0].fd = 0;
1222                 pfd[0].events = POLLIN;
1223                 pfd[1].fd = fd;
1224                 pfd[1].events = POLLIN;
1225
1226                 if (poll(pfd, 2, -1) < 0) {
1227                         fprintf(stderr, "poll error\n");
1228                         break;
1229                 }
1230
1231                 if (pfd[0].revents)
1232                         break;
1233 #else
1234                 struct timeval timeout = { .tv_sec = 3, .tv_usec = 0 };
1235                 fd_set fds;
1236                 int ret;
1237
1238                 FD_ZERO(&fds);
1239                 FD_SET(0, &fds);
1240                 FD_SET(dev->fd, &fds);
1241                 ret = select(dev->fd + 1, &fds, NULL, NULL, &timeout);
1242
1243                 if (ret <= 0) {
1244                         fprintf(stderr, "select timed out or error (ret %d)\n",
1245                                 ret);
1246                         continue;
1247                 } else if (FD_ISSET(0, &fds)) {
1248                         break;
1249                 }
1250 #endif
1251
1252                 drmHandleEvent(dev->fd, &evctx);
1253         }
1254
1255         kms_bo_destroy(&other_bo);
1256 }
1257
1258 #define min(a, b)       ((a) < (b) ? (a) : (b))
1259
1260 static int parse_connector(struct pipe_arg *pipe, const char *arg)
1261 {
1262         unsigned int len;
1263         unsigned int i;
1264         const char *p;
1265         char *endp;
1266
1267         pipe->vrefresh = 0;
1268         pipe->crtc_id = (uint32_t)-1;
1269         strcpy(pipe->format_str, "XR24");
1270
1271         /* Count the number of connectors and allocate them. */
1272         pipe->num_cons = 1;
1273         for (p = arg; isdigit(*p) || *p == ','; ++p) {
1274                 if (*p == ',')
1275                         pipe->num_cons++;
1276         }
1277
1278         pipe->con_ids = malloc(pipe->num_cons * sizeof *pipe->con_ids);
1279         if (pipe->con_ids == NULL)
1280                 return -1;
1281
1282         /* Parse the connectors. */
1283         for (i = 0, p = arg; i < pipe->num_cons; ++i, p = endp + 1) {
1284                 pipe->con_ids[i] = strtoul(p, &endp, 10);
1285                 if (*endp != ',')
1286                         break;
1287         }
1288
1289         if (i != pipe->num_cons - 1)
1290                 return -1;
1291
1292         /* Parse the remaining parameters. */
1293         if (*endp == '@') {
1294                 arg = endp + 1;
1295                 pipe->crtc_id = strtoul(arg, &endp, 10);
1296         }
1297         if (*endp != ':')
1298                 return -1;
1299
1300         arg = endp + 1;
1301
1302         /* Search for the vertical refresh or the format. */
1303         p = strpbrk(arg, "-@");
1304         if (p == NULL)
1305                 p = arg + strlen(arg);
1306         len = min(sizeof pipe->mode_str - 1, (unsigned int)(p - arg));
1307         strncpy(pipe->mode_str, arg, len);
1308         pipe->mode_str[len] = '\0';
1309
1310         if (*p == '-') {
1311                 pipe->vrefresh = strtoul(p + 1, &endp, 10);
1312                 p = endp;
1313         }
1314
1315         if (*p == '@') {
1316                 strncpy(pipe->format_str, p + 1, 4);
1317                 pipe->format_str[4] = '\0';
1318         }
1319
1320         pipe->fourcc = format_fourcc(pipe->format_str);
1321         if (pipe->fourcc == 0)  {
1322                 fprintf(stderr, "unknown format %s\n", pipe->format_str);
1323                 return -1;
1324         }
1325
1326         return 0;
1327 }
1328
1329 static int parse_plane(struct plane_arg *plane, const char *p)
1330 {
1331         char *end;
1332
1333         memset(plane, 0, sizeof *plane);
1334
1335         plane->crtc_id = strtoul(p, &end, 10);
1336         if (*end != ':')
1337                 return -EINVAL;
1338
1339         p = end + 1;
1340         plane->w = strtoul(p, &end, 10);
1341         if (*end != 'x')
1342                 return -EINVAL;
1343
1344         p = end + 1;
1345         plane->h = strtoul(p, &end, 10);
1346
1347         if (*end == '+' || *end == '-') {
1348                 plane->x = strtol(end, &end, 10);
1349                 if (*end != '+' && *end != '-')
1350                         return -EINVAL;
1351                 plane->y = strtol(end, &end, 10);
1352
1353                 plane->has_position = true;
1354         }
1355
1356         if (*end == '*') {
1357                 p = end + 1;
1358                 plane->scale = strtod(p, &end);
1359                 if (plane->scale <= 0.0)
1360                         return -EINVAL;
1361         } else {
1362                 plane->scale = 1.0;
1363         }
1364
1365         if (*end == '@') {
1366                 p = end + 1;
1367                 if (strlen(p) != 4)
1368                         return -EINVAL;
1369
1370                 strcpy(plane->format_str, p);
1371         } else {
1372                 strcpy(plane->format_str, "XR24");
1373         }
1374
1375         plane->fourcc = format_fourcc(plane->format_str);
1376         if (plane->fourcc == 0) {
1377                 fprintf(stderr, "unknown format %s\n", plane->format_str);
1378                 return -EINVAL;
1379         }
1380
1381         return 0;
1382 }
1383
1384 static int parse_property(struct property_arg *p, const char *arg)
1385 {
1386         if (sscanf(arg, "%d:%32[^:]:%" SCNu64, &p->obj_id, p->name, &p->value) != 3)
1387                 return -1;
1388
1389         p->obj_type = 0;
1390         p->name[DRM_PROP_NAME_LEN] = '\0';
1391
1392         return 0;
1393 }
1394
1395 static void usage(char *name)
1396 {
1397         fprintf(stderr, "usage: %s [-cDdefMPpsCvw]\n", name);
1398
1399         fprintf(stderr, "\n Query options:\n\n");
1400         fprintf(stderr, "\t-c\tlist connectors\n");
1401         fprintf(stderr, "\t-e\tlist encoders\n");
1402         fprintf(stderr, "\t-f\tlist framebuffers\n");
1403         fprintf(stderr, "\t-p\tlist CRTCs and planes (pipes)\n");
1404
1405         fprintf(stderr, "\n Test options:\n\n");
1406         fprintf(stderr, "\t-P <crtc_id>:<w>x<h>[+<x>+<y>][*<scale>][@<format>]\tset a plane\n");
1407         fprintf(stderr, "\t-s <connector_id>[,<connector_id>][@<crtc_id>]:<mode>[-<vrefresh>][@<format>]\tset a mode\n");
1408         fprintf(stderr, "\t-C\ttest hw cursor\n");
1409         fprintf(stderr, "\t-v\ttest vsynced page flipping\n");
1410         fprintf(stderr, "\t-w <obj_id>:<prop_name>:<value>\tset property\n");
1411
1412         fprintf(stderr, "\n Generic options:\n\n");
1413         fprintf(stderr, "\t-d\tdrop master after mode set\n");
1414         fprintf(stderr, "\t-M module\tuse the given driver\n");
1415         fprintf(stderr, "\t-D device\tuse the given device\n");
1416
1417         fprintf(stderr, "\n\tDefault is to dump all info.\n");
1418         exit(0);
1419 }
1420
1421 static int page_flipping_supported(void)
1422 {
1423         /*FIXME: generic ioctl needed? */
1424         return 1;
1425 #if 0
1426         int ret, value;
1427         struct drm_i915_getparam gp;
1428
1429         gp.param = I915_PARAM_HAS_PAGEFLIPPING;
1430         gp.value = &value;
1431
1432         ret = drmCommandWriteRead(fd, DRM_I915_GETPARAM, &gp, sizeof(gp));
1433         if (ret) {
1434                 fprintf(stderr, "drm_i915_getparam: %m\n");
1435                 return 0;
1436         }
1437
1438         return *gp.value;
1439 #endif
1440 }
1441
1442 static int cursor_supported(void)
1443 {
1444         /*FIXME: generic ioctl needed? */
1445         return 1;
1446 }
1447
1448 static char optstr[] = "cdD:efM:P:ps:Cvw:";
1449
1450 int main(int argc, char **argv)
1451 {
1452         struct device dev;
1453
1454         int c;
1455         int encoders = 0, connectors = 0, crtcs = 0, planes = 0, framebuffers = 0;
1456         int drop_master = 0;
1457         int test_vsync = 0;
1458         int test_cursor = 0;
1459         const char *modules[] = { "i915", "radeon", "nouveau", "vmwgfx", "omapdrm", "exynos", "tilcdc", "msm", "sti", "tegra" };
1460         char *device = NULL;
1461         char *module = NULL;
1462         unsigned int i;
1463         int count = 0, plane_count = 0;
1464         unsigned int prop_count = 0;
1465         struct pipe_arg *pipe_args = NULL;
1466         struct plane_arg *plane_args = NULL;
1467         struct property_arg *prop_args = NULL;
1468         unsigned int args = 0;
1469         int ret;
1470
1471         memset(&dev, 0, sizeof dev);
1472
1473         opterr = 0;
1474         while ((c = getopt(argc, argv, optstr)) != -1) {
1475                 args++;
1476
1477                 switch (c) {
1478                 case 'c':
1479                         connectors = 1;
1480                         break;
1481                 case 'D':
1482                         device = optarg;
1483                         args--;
1484                         break;
1485                 case 'd':
1486                         drop_master = 1;
1487                         break;
1488                 case 'e':
1489                         encoders = 1;
1490                         break;
1491                 case 'f':
1492                         framebuffers = 1;
1493                         break;
1494                 case 'M':
1495                         module = optarg;
1496                         /* Preserve the default behaviour of dumping all information. */
1497                         args--;
1498                         break;
1499                 case 'P':
1500                         plane_args = realloc(plane_args,
1501                                              (plane_count + 1) * sizeof *plane_args);
1502                         if (plane_args == NULL) {
1503                                 fprintf(stderr, "memory allocation failed\n");
1504                                 return 1;
1505                         }
1506
1507                         if (parse_plane(&plane_args[plane_count], optarg) < 0)
1508                                 usage(argv[0]);
1509
1510                         plane_count++;
1511                         break;
1512                 case 'p':
1513                         crtcs = 1;
1514                         planes = 1;
1515                         break;
1516                 case 's':
1517                         pipe_args = realloc(pipe_args,
1518                                             (count + 1) * sizeof *pipe_args);
1519                         if (pipe_args == NULL) {
1520                                 fprintf(stderr, "memory allocation failed\n");
1521                                 return 1;
1522                         }
1523
1524                         if (parse_connector(&pipe_args[count], optarg) < 0)
1525                                 usage(argv[0]);
1526
1527                         count++;                                      
1528                         break;
1529                 case 'C':
1530                         test_cursor = 1;
1531                         break;
1532                 case 'v':
1533                         test_vsync = 1;
1534                         break;
1535                 case 'w':
1536                         prop_args = realloc(prop_args,
1537                                            (prop_count + 1) * sizeof *prop_args);
1538                         if (prop_args == NULL) {
1539                                 fprintf(stderr, "memory allocation failed\n");
1540                                 return 1;
1541                         }
1542
1543                         if (parse_property(&prop_args[prop_count], optarg) < 0)
1544                                 usage(argv[0]);
1545
1546                         prop_count++;
1547                         break;
1548                 default:
1549                         usage(argv[0]);
1550                         break;
1551                 }
1552         }
1553
1554         if (!args)
1555                 encoders = connectors = crtcs = planes = framebuffers = 1;
1556
1557         if (module) {
1558                 dev.fd = drmOpen(module, device);
1559                 if (dev.fd < 0) {
1560                         fprintf(stderr, "failed to open device '%s'.\n", module);
1561                         return 1;
1562                 }
1563         } else {
1564                 for (i = 0; i < ARRAY_SIZE(modules); i++) {
1565                         printf("trying to open device '%s'...", modules[i]);
1566                         dev.fd = drmOpen(modules[i], device);
1567                         if (dev.fd < 0) {
1568                                 printf("failed.\n");
1569                         } else {
1570                                 printf("success.\n");
1571                                 break;
1572                         }
1573                 }
1574
1575                 if (dev.fd < 0) {
1576                         fprintf(stderr, "no device found.\n");
1577                         return 1;
1578                 }
1579         }
1580
1581         if (test_vsync && !page_flipping_supported()) {
1582                 fprintf(stderr, "page flipping not supported by drm.\n");
1583                 return -1;
1584         }
1585
1586         if (test_vsync && !count) {
1587                 fprintf(stderr, "page flipping requires at least one -s option.\n");
1588                 return -1;
1589         }
1590
1591         if (test_cursor && !cursor_supported()) {
1592                 fprintf(stderr, "hw cursor not supported by drm.\n");
1593                 return -1;
1594         }
1595
1596         dev.resources = get_resources(&dev);
1597         if (!dev.resources) {
1598                 drmClose(dev.fd);
1599                 return 1;
1600         }
1601
1602 #define dump_resource(dev, res) if (res) dump_##res(dev)
1603
1604         dump_resource(&dev, encoders);
1605         dump_resource(&dev, connectors);
1606         dump_resource(&dev, crtcs);
1607         dump_resource(&dev, planes);
1608         dump_resource(&dev, framebuffers);
1609
1610         for (i = 0; i < prop_count; ++i)
1611                 set_property(&dev, &prop_args[i]);
1612
1613         if (count || plane_count) {
1614                 ret = kms_create(dev.fd, &dev.kms);
1615                 if (ret) {
1616                         fprintf(stderr, "failed to create kms driver: %s\n",
1617                                 strerror(-ret));
1618                         return 1;
1619                 }
1620
1621                 if (count)
1622                         set_mode(&dev, pipe_args, count);
1623
1624                 if (plane_count)
1625                         set_planes(&dev, plane_args, plane_count);
1626
1627                 if (test_cursor)
1628                         set_cursors(&dev, pipe_args, count);
1629
1630                 if (test_vsync)
1631                         test_page_flip(&dev, pipe_args, count);
1632
1633                 if (drop_master)
1634                         drmDropMaster(dev.fd);
1635
1636                 getchar();
1637
1638                 if (test_cursor)
1639                         clear_cursors(&dev);
1640
1641                 kms_bo_destroy(&dev.mode.bo);
1642                 kms_destroy(&dev.kms);
1643         }
1644
1645         free_resources(dev.resources);
1646
1647         return 0;
1648 }