OSDN Git Service

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