OSDN Git Service

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