OSDN Git Service

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