OSDN Git Service

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