e714818ed9b65109b64caceebbf39bdde7dcd8a2
[platform/upstream/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 #include <assert.h>
42 #include <ctype.h>
43 #include <stdbool.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <stdint.h>
47 #include <inttypes.h>
48 #include <unistd.h>
49 #include <string.h>
50 #include <strings.h>
51 #include <errno.h>
52 #include <poll.h>
53 #include <sys/time.h>
54 #if HAVE_SYS_SELECT_H
55 #include <sys/select.h>
56 #endif
57 #include <math.h>
58
59 #include "xf86drm.h"
60 #include "xf86drmMode.h"
61 #include "drm_fourcc.h"
62
63 #include "util/common.h"
64 #include "util/format.h"
65 #include "util/kms.h"
66 #include "util/pattern.h"
67
68 #include "buffers.h"
69 #include "cursor.h"
70
71 static enum util_fill_pattern primary_fill = UTIL_PATTERN_SMPTE;
72 static enum util_fill_pattern secondary_fill = UTIL_PATTERN_TILES;
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         struct crtc *crtcs;
104         int count_crtcs;
105         struct encoder *encoders;
106         int count_encoders;
107         struct connector *connectors;
108         int count_connectors;
109         struct fb *fbs;
110         int count_fbs;
111         struct plane *planes;
112         uint32_t count_planes;
113 };
114
115 struct device {
116         int fd;
117
118         struct resources *resources;
119
120         struct {
121                 unsigned int width;
122                 unsigned int height;
123
124                 unsigned int fb_id;
125                 struct bo *bo;
126                 struct bo *cursor_bo;
127         } mode;
128
129         int use_atomic;
130         drmModeAtomicReq *req;
131         int32_t writeback_fence_fd;
132 };
133
134 static inline int64_t U642I64(uint64_t val)
135 {
136         return (int64_t)*((int64_t *)&val);
137 }
138
139 static float mode_vrefresh(drmModeModeInfo *mode)
140 {
141         return  mode->clock * 1000.00
142                         / (mode->htotal * mode->vtotal);
143 }
144
145 #define bit_name_fn(res)                                        \
146 const char * res##_str(int type) {                              \
147         unsigned int i;                                         \
148         const char *sep = "";                                   \
149         for (i = 0; i < ARRAY_SIZE(res##_names); i++) {         \
150                 if (type & (1 << i)) {                          \
151                         printf("%s%s", sep, res##_names[i]);    \
152                         sep = ", ";                             \
153                 }                                               \
154         }                                                       \
155         return NULL;                                            \
156 }
157
158 static const char *mode_type_names[] = {
159         "builtin",
160         "clock_c",
161         "crtc_c",
162         "preferred",
163         "default",
164         "userdef",
165         "driver",
166 };
167
168 static bit_name_fn(mode_type)
169
170 static const char *mode_flag_names[] = {
171         "phsync",
172         "nhsync",
173         "pvsync",
174         "nvsync",
175         "interlace",
176         "dblscan",
177         "csync",
178         "pcsync",
179         "ncsync",
180         "hskew",
181         "bcast",
182         "pixmux",
183         "dblclk",
184         "clkdiv2"
185 };
186
187 static bit_name_fn(mode_flag)
188
189 static void dump_fourcc(uint32_t fourcc)
190 {
191         char *name = drmGetFormatName(fourcc);
192         printf(" %s", name);
193         free(name);
194 }
195
196 static void dump_encoders(struct device *dev)
197 {
198         drmModeEncoder *encoder;
199         int i;
200
201         printf("Encoders:\n");
202         printf("id\tcrtc\ttype\tpossible crtcs\tpossible clones\t\n");
203         for (i = 0; i < dev->resources->count_encoders; i++) {
204                 encoder = dev->resources->encoders[i].encoder;
205                 if (!encoder)
206                         continue;
207
208                 printf("%d\t%d\t%s\t0x%08x\t0x%08x\n",
209                        encoder->encoder_id,
210                        encoder->crtc_id,
211                        util_lookup_encoder_type_name(encoder->encoder_type),
212                        encoder->possible_crtcs,
213                        encoder->possible_clones);
214         }
215         printf("\n");
216 }
217
218 static void dump_mode(drmModeModeInfo *mode, int index)
219 {
220         printf("  #%i %s %.2f %d %d %d %d %d %d %d %d %d",
221                index,
222                mode->name,
223                mode_vrefresh(mode),
224                mode->hdisplay,
225                mode->hsync_start,
226                mode->hsync_end,
227                mode->htotal,
228                mode->vdisplay,
229                mode->vsync_start,
230                mode->vsync_end,
231                mode->vtotal,
232                mode->clock);
233
234         printf(" flags: ");
235         mode_flag_str(mode->flags);
236         printf("; type: ");
237         mode_type_str(mode->type);
238         printf("\n");
239 }
240
241 static void dump_blob(struct device *dev, uint32_t blob_id)
242 {
243         uint32_t i;
244         unsigned char *blob_data;
245         drmModePropertyBlobPtr blob;
246
247         blob = drmModeGetPropertyBlob(dev->fd, blob_id);
248         if (!blob) {
249                 printf("\n");
250                 return;
251         }
252
253         blob_data = blob->data;
254
255         for (i = 0; i < blob->length; i++) {
256                 if (i % 16 == 0)
257                         printf("\n\t\t\t");
258                 printf("%.2hhx", blob_data[i]);
259         }
260         printf("\n");
261
262         drmModeFreePropertyBlob(blob);
263 }
264
265 static const char *modifier_to_string(uint64_t modifier)
266 {
267         static char mod_string[4096];
268
269         char *modifier_name = drmGetFormatModifierName(modifier);
270         char *vendor_name = drmGetFormatModifierVendor(modifier);
271         memset(mod_string, 0x00, sizeof(mod_string));
272
273         if (!modifier_name) {
274                 if (vendor_name)
275                         snprintf(mod_string, sizeof(mod_string), "%s_%s",
276                                  vendor_name, "UNKNOWN_MODIFIER");
277                 else
278                         snprintf(mod_string, sizeof(mod_string), "%s_%s",
279                                  "UNKNOWN_VENDOR", "UNKNOWN_MODIFIER");
280                 /* safe, as free is no-op for NULL */
281                 free(vendor_name);
282                 return mod_string;
283         }
284
285         if (modifier == DRM_FORMAT_MOD_LINEAR) {
286                 snprintf(mod_string, sizeof(mod_string), "%s", modifier_name);
287                 free(modifier_name);
288                 free(vendor_name);
289                 return mod_string;
290         }
291
292         snprintf(mod_string, sizeof(mod_string), "%s_%s",
293                  vendor_name, modifier_name);
294
295         free(modifier_name);
296         free(vendor_name);
297         return mod_string;
298 }
299
300 static void dump_in_formats(struct device *dev, uint32_t blob_id)
301 {
302         drmModeFormatModifierIterator iter = {0};
303         drmModePropertyBlobPtr blob;
304         uint32_t fmt = 0;
305
306         printf("\t\tin_formats blob decoded:\n");
307         blob = drmModeGetPropertyBlob(dev->fd, blob_id);
308         if (!blob) {
309                 printf("\n");
310                 return;
311         }
312
313         while (drmModeFormatModifierBlobIterNext(blob, &iter)) {
314                 if (!fmt || fmt != iter.fmt) {
315                         printf("%s\t\t\t", !fmt ? "" : "\n");
316                         fmt = iter.fmt;
317                         dump_fourcc(fmt);
318                         printf(": ");
319                 }
320
321                 printf(" %s", modifier_to_string(iter.mod));
322         }
323
324         printf("\n");
325
326         drmModeFreePropertyBlob(blob);
327 }
328
329 static void dump_prop(struct device *dev, drmModePropertyPtr prop,
330                       uint32_t prop_id, uint64_t value)
331 {
332         int i;
333         printf("\t%d", prop_id);
334         if (!prop) {
335                 printf("\n");
336                 return;
337         }
338
339         printf(" %s:\n", prop->name);
340
341         printf("\t\tflags:");
342         if (prop->flags & DRM_MODE_PROP_PENDING)
343                 printf(" pending");
344         if (prop->flags & DRM_MODE_PROP_IMMUTABLE)
345                 printf(" immutable");
346         if (drm_property_type_is(prop, DRM_MODE_PROP_SIGNED_RANGE))
347                 printf(" signed range");
348         if (drm_property_type_is(prop, DRM_MODE_PROP_RANGE))
349                 printf(" range");
350         if (drm_property_type_is(prop, DRM_MODE_PROP_ENUM))
351                 printf(" enum");
352         if (drm_property_type_is(prop, DRM_MODE_PROP_BITMASK))
353                 printf(" bitmask");
354         if (drm_property_type_is(prop, DRM_MODE_PROP_BLOB))
355                 printf(" blob");
356         if (drm_property_type_is(prop, DRM_MODE_PROP_OBJECT))
357                 printf(" object");
358         printf("\n");
359
360         if (drm_property_type_is(prop, DRM_MODE_PROP_SIGNED_RANGE)) {
361                 printf("\t\tvalues:");
362                 for (i = 0; i < prop->count_values; i++)
363                         printf(" %"PRId64, U642I64(prop->values[i]));
364                 printf("\n");
365         }
366
367         if (drm_property_type_is(prop, DRM_MODE_PROP_RANGE)) {
368                 printf("\t\tvalues:");
369                 for (i = 0; i < prop->count_values; i++)
370                         printf(" %"PRIu64, prop->values[i]);
371                 printf("\n");
372         }
373
374         if (drm_property_type_is(prop, DRM_MODE_PROP_ENUM)) {
375                 printf("\t\tenums:");
376                 for (i = 0; i < prop->count_enums; i++)
377                         printf(" %s=%"PRIu64, prop->enums[i].name,
378                                (uint64_t)prop->enums[i].value);
379                 printf("\n");
380         } else if (drm_property_type_is(prop, DRM_MODE_PROP_BITMASK)) {
381                 printf("\t\tvalues:");
382                 for (i = 0; i < prop->count_enums; i++)
383                         printf(" %s=0x%llx", prop->enums[i].name,
384                                (1LL << prop->enums[i].value));
385                 printf("\n");
386         } else {
387                 assert(prop->count_enums == 0);
388         }
389
390         if (drm_property_type_is(prop, DRM_MODE_PROP_BLOB)) {
391                 printf("\t\tblobs:\n");
392                 for (i = 0; i < prop->count_blobs; i++)
393                         dump_blob(dev, prop->blob_ids[i]);
394                 printf("\n");
395         } else {
396                 assert(prop->count_blobs == 0);
397         }
398
399         printf("\t\tvalue:");
400         if (drm_property_type_is(prop, DRM_MODE_PROP_BLOB))
401                 dump_blob(dev, value);
402         else if (drm_property_type_is(prop, DRM_MODE_PROP_SIGNED_RANGE))
403                 printf(" %"PRId64"\n", value);
404         else
405                 printf(" %"PRIu64"\n", value);
406
407         if (strcmp(prop->name, "IN_FORMATS") == 0)
408                 dump_in_formats(dev, value);
409 }
410
411 static void dump_connectors(struct device *dev)
412 {
413         int i, j;
414
415         printf("Connectors:\n");
416         printf("id\tencoder\tstatus\t\tname\t\tsize (mm)\tmodes\tencoders\n");
417         for (i = 0; i < dev->resources->count_connectors; i++) {
418                 struct connector *_connector = &dev->resources->connectors[i];
419                 drmModeConnector *connector = _connector->connector;
420                 if (!connector)
421                         continue;
422
423                 printf("%d\t%d\t%s\t%-15s\t%dx%d\t\t%d\t",
424                        connector->connector_id,
425                        connector->encoder_id,
426                        util_lookup_connector_status_name(connector->connection),
427                        _connector->name,
428                        connector->mmWidth, connector->mmHeight,
429                        connector->count_modes);
430
431                 for (j = 0; j < connector->count_encoders; j++)
432                         printf("%s%d", j > 0 ? ", " : "", connector->encoders[j]);
433                 printf("\n");
434
435                 if (connector->count_modes) {
436                         printf("  modes:\n");
437                         printf("\tindex name refresh (Hz) hdisp hss hse htot vdisp "
438                                "vss vse vtot\n");
439                         for (j = 0; j < connector->count_modes; j++)
440                                 dump_mode(&connector->modes[j], j);
441                 }
442
443                 if (_connector->props) {
444                         printf("  props:\n");
445                         for (j = 0; j < (int)_connector->props->count_props; j++)
446                                 dump_prop(dev, _connector->props_info[j],
447                                           _connector->props->props[j],
448                                           _connector->props->prop_values[j]);
449                 }
450         }
451         printf("\n");
452 }
453
454 static void dump_crtcs(struct device *dev)
455 {
456         int i;
457         uint32_t j;
458
459         printf("CRTCs:\n");
460         printf("id\tfb\tpos\tsize\n");
461         for (i = 0; i < dev->resources->count_crtcs; i++) {
462                 struct crtc *_crtc = &dev->resources->crtcs[i];
463                 drmModeCrtc *crtc = _crtc->crtc;
464                 if (!crtc)
465                         continue;
466
467                 printf("%d\t%d\t(%d,%d)\t(%dx%d)\n",
468                        crtc->crtc_id,
469                        crtc->buffer_id,
470                        crtc->x, crtc->y,
471                        crtc->width, crtc->height);
472                 dump_mode(&crtc->mode, 0);
473
474                 if (_crtc->props) {
475                         printf("  props:\n");
476                         for (j = 0; j < _crtc->props->count_props; j++)
477                                 dump_prop(dev, _crtc->props_info[j],
478                                           _crtc->props->props[j],
479                                           _crtc->props->prop_values[j]);
480                 } else {
481                         printf("  no properties found\n");
482                 }
483         }
484         printf("\n");
485 }
486
487 static void dump_framebuffers(struct device *dev)
488 {
489         drmModeFB *fb;
490         int i;
491
492         printf("Frame buffers:\n");
493         printf("id\tsize\tpitch\n");
494         for (i = 0; i < dev->resources->count_fbs; i++) {
495                 fb = dev->resources->fbs[i].fb;
496                 if (!fb)
497                         continue;
498
499                 printf("%u\t(%ux%u)\t%u\n",
500                        fb->fb_id,
501                        fb->width, fb->height,
502                        fb->pitch);
503         }
504         printf("\n");
505 }
506
507 static void dump_planes(struct device *dev)
508 {
509         unsigned int i, j;
510
511         printf("Planes:\n");
512         printf("id\tcrtc\tfb\tCRTC x,y\tx,y\tgamma size\tpossible crtcs\n");
513
514         for (i = 0; i < dev->resources->count_planes; i++) {
515                 struct plane *plane = &dev->resources->planes[i];
516                 drmModePlane *ovr = plane->plane;
517                 if (!ovr)
518                         continue;
519
520                 printf("%d\t%d\t%d\t%d,%d\t\t%d,%d\t%-8d\t0x%08x\n",
521                        ovr->plane_id, ovr->crtc_id, ovr->fb_id,
522                        ovr->crtc_x, ovr->crtc_y, ovr->x, ovr->y,
523                        ovr->gamma_size, ovr->possible_crtcs);
524
525                 if (!ovr->count_formats)
526                         continue;
527
528                 printf("  formats:");
529                 for (j = 0; j < ovr->count_formats; j++)
530                         dump_fourcc(ovr->formats[j]);
531                 printf("\n");
532
533                 if (plane->props) {
534                         printf("  props:\n");
535                         for (j = 0; j < plane->props->count_props; j++)
536                                 dump_prop(dev, plane->props_info[j],
537                                           plane->props->props[j],
538                                           plane->props->prop_values[j]);
539                 } else {
540                         printf("  no properties found\n");
541                 }
542         }
543         printf("\n");
544
545         return;
546 }
547
548 static void free_resources(struct resources *res)
549 {
550         int i;
551
552         if (!res)
553                 return;
554
555 #define free_resource(_res, type, Type)                                 \
556         do {                                                                    \
557                 if (!(_res)->type##s)                                           \
558                         break;                                                  \
559                 for (i = 0; i < (int)(_res)->count_##type##s; ++i) {    \
560                         if (!(_res)->type##s[i].type)                           \
561                                 break;                                          \
562                         drmModeFree##Type((_res)->type##s[i].type);             \
563                 }                                                               \
564                 free((_res)->type##s);                                          \
565         } while (0)
566
567 #define free_properties(_res, type)                                     \
568         do {                                                                    \
569                 for (i = 0; i < (int)(_res)->count_##type##s; ++i) {    \
570                         unsigned int j;                                                                         \
571                         for (j = 0; j < res->type##s[i].props->count_props; ++j)\
572                                 drmModeFreeProperty(res->type##s[i].props_info[j]);\
573                         free(res->type##s[i].props_info);                       \
574                         drmModeFreeObjectProperties(res->type##s[i].props);     \
575                 }                                                               \
576         } while (0)
577
578         free_properties(res, plane);
579         free_resource(res, plane, Plane);
580
581         free_properties(res, connector);
582         free_properties(res, crtc);
583
584         for (i = 0; i < res->count_connectors; i++)
585                 free(res->connectors[i].name);
586
587         free_resource(res, fb, FB);
588         free_resource(res, connector, Connector);
589         free_resource(res, encoder, Encoder);
590         free_resource(res, crtc, Crtc);
591
592         free(res);
593 }
594
595 static struct resources *get_resources(struct device *dev)
596 {
597         drmModeRes *_res;
598         drmModePlaneRes *plane_res;
599         struct resources *res;
600         int i;
601
602         res = calloc(1, sizeof(*res));
603         if (res == 0)
604                 return NULL;
605
606         drmSetClientCap(dev->fd, DRM_CLIENT_CAP_UNIVERSAL_PLANES, 1);
607
608         _res = drmModeGetResources(dev->fd);
609         if (!_res) {
610                 fprintf(stderr, "drmModeGetResources failed: %s\n",
611                         strerror(errno));
612                 free(res);
613                 return NULL;
614         }
615
616         res->count_crtcs = _res->count_crtcs;
617         res->count_encoders = _res->count_encoders;
618         res->count_connectors = _res->count_connectors;
619         res->count_fbs = _res->count_fbs;
620
621         res->crtcs = calloc(res->count_crtcs, sizeof(*res->crtcs));
622         res->encoders = calloc(res->count_encoders, sizeof(*res->encoders));
623         res->connectors = calloc(res->count_connectors, sizeof(*res->connectors));
624         res->fbs = calloc(res->count_fbs, sizeof(*res->fbs));
625
626         if (!res->crtcs || !res->encoders || !res->connectors || !res->fbs) {
627             drmModeFreeResources(_res);
628                 goto error;
629     }
630
631 #define get_resource(_res, __res, type, Type)                                   \
632         do {                                                                    \
633                 for (i = 0; i < (int)(_res)->count_##type##s; ++i) {    \
634                         uint32_t type##id = (__res)->type##s[i];                        \
635                         (_res)->type##s[i].type =                                                       \
636                                 drmModeGet##Type(dev->fd, type##id);                    \
637                         if (!(_res)->type##s[i].type)                                           \
638                                 fprintf(stderr, "could not get %s %i: %s\n",    \
639                                         #type, type##id,                                                        \
640                                         strerror(errno));                       \
641                 }                                                               \
642         } while (0)
643
644         get_resource(res, _res, crtc, Crtc);
645         get_resource(res, _res, encoder, Encoder);
646         get_resource(res, _res, connector, Connector);
647         get_resource(res, _res, fb, FB);
648
649         drmModeFreeResources(_res);
650
651         /* Set the name of all connectors based on the type name and the per-type ID. */
652         for (i = 0; i < res->count_connectors; i++) {
653                 struct connector *connector = &res->connectors[i];
654                 drmModeConnector *conn = connector->connector;
655                 int num;
656
657                 num = asprintf(&connector->name, "%s-%u",
658                          drmModeGetConnectorTypeName(conn->connector_type),
659                          conn->connector_type_id);
660                 if (num < 0)
661                         goto error;
662         }
663
664 #define get_properties(_res, type, Type)                                        \
665         do {                                                                    \
666                 for (i = 0; i < (int)(_res)->count_##type##s; ++i) {    \
667                         struct type *obj = &res->type##s[i];                    \
668                         unsigned int j;                                         \
669                         obj->props =                                            \
670                                 drmModeObjectGetProperties(dev->fd, obj->type->type##_id, \
671                                                            DRM_MODE_OBJECT_##Type); \
672                         if (!obj->props) {                                      \
673                                 fprintf(stderr,                                 \
674                                         "could not get %s %i properties: %s\n", \
675                                         #type, obj->type->type##_id,            \
676                                         strerror(errno));                       \
677                                 continue;                                       \
678                         }                                                       \
679                         obj->props_info = calloc(obj->props->count_props,       \
680                                                  sizeof(*obj->props_info));     \
681                         if (!obj->props_info)                                   \
682                                 continue;                                       \
683                         for (j = 0; j < obj->props->count_props; ++j)           \
684                                 obj->props_info[j] =                            \
685                                         drmModeGetProperty(dev->fd, obj->props->props[j]); \
686                 }                                                               \
687         } while (0)
688
689         get_properties(res, crtc, CRTC);
690         get_properties(res, connector, CONNECTOR);
691
692         for (i = 0; i < res->count_crtcs; ++i)
693                 res->crtcs[i].mode = &res->crtcs[i].crtc->mode;
694
695         plane_res = drmModeGetPlaneResources(dev->fd);
696         if (!plane_res) {
697                 fprintf(stderr, "drmModeGetPlaneResources failed: %s\n",
698                         strerror(errno));
699                 return res;
700         }
701
702         res->count_planes = plane_res->count_planes;
703
704         res->planes = calloc(res->count_planes, sizeof(*res->planes));
705         if (!res->planes) {
706                 drmModeFreePlaneResources(plane_res);
707                 goto error;
708         }
709
710         get_resource(res, plane_res, plane, Plane);
711         drmModeFreePlaneResources(plane_res);
712         get_properties(res, plane, PLANE);
713
714         return res;
715
716 error:
717         free_resources(res);
718         return NULL;
719 }
720
721 static struct crtc *get_crtc_by_id(struct device *dev, uint32_t id)
722 {
723         int i;
724
725         for (i = 0; i < dev->resources->count_crtcs; ++i) {
726                 drmModeCrtc *crtc = dev->resources->crtcs[i].crtc;
727                 if (crtc && crtc->crtc_id == id)
728                         return &dev->resources->crtcs[i];
729         }
730
731         return NULL;
732 }
733
734 static uint32_t get_crtc_mask(struct device *dev, struct crtc *crtc)
735 {
736         unsigned int i;
737
738         for (i = 0; i < (unsigned int)dev->resources->count_crtcs; i++) {
739                 if (crtc->crtc->crtc_id == dev->resources->crtcs[i].crtc->crtc_id)
740                         return 1 << i;
741         }
742     /* Unreachable: crtc->crtc is one of resources->crtcs[] */
743     /* Don't return zero or static analysers will complain */
744         abort();
745         return 0;
746 }
747
748 static drmModeConnector *get_connector_by_name(struct device *dev, const char *name)
749 {
750         struct connector *connector;
751         int i;
752
753         for (i = 0; i < dev->resources->count_connectors; i++) {
754                 connector = &dev->resources->connectors[i];
755
756                 if (strcmp(connector->name, name) == 0)
757                         return connector->connector;
758         }
759
760         return NULL;
761 }
762
763 static drmModeConnector *get_connector_by_id(struct device *dev, uint32_t id)
764 {
765         drmModeConnector *connector;
766         int i;
767
768         for (i = 0; i < dev->resources->count_connectors; i++) {
769                 connector = dev->resources->connectors[i].connector;
770                 if (connector && connector->connector_id == id)
771                         return connector;
772         }
773
774         return NULL;
775 }
776
777 static drmModeEncoder *get_encoder_by_id(struct device *dev, uint32_t id)
778 {
779         drmModeEncoder *encoder;
780         int i;
781
782         for (i = 0; i < dev->resources->count_encoders; i++) {
783                 encoder = dev->resources->encoders[i].encoder;
784                 if (encoder && encoder->encoder_id == id)
785                         return encoder;
786         }
787
788         return NULL;
789 }
790
791 /* -----------------------------------------------------------------------------
792  * Pipes and planes
793  */
794
795 /*
796  * Mode setting with the kernel interfaces is a bit of a chore.
797  * First you have to find the connector in question and make sure the
798  * requested mode is available.
799  * Then you need to find the encoder attached to that connector so you
800  * can bind it with a free crtc.
801  */
802 struct pipe_arg {
803         const char **cons;
804         uint32_t *con_ids;
805         unsigned int num_cons;
806         uint32_t crtc_id;
807         char mode_str[64];
808         char format_str[5];
809         float vrefresh;
810         unsigned int fourcc;
811         drmModeModeInfo *mode;
812         struct crtc *crtc;
813         unsigned int fb_id[2], current_fb_id;
814         struct timeval start;
815         unsigned int out_fb_id;
816         struct bo *out_bo;
817
818         int swap_count;
819 };
820
821 struct plane_arg {
822         uint32_t plane_id;  /* the id of plane to use */
823         uint32_t crtc_id;  /* the id of CRTC to bind to */
824         bool has_position;
825         int32_t x, y;
826         uint32_t w, h;
827         double scale;
828         unsigned int fb_id;
829         unsigned int old_fb_id;
830         struct bo *bo;
831         struct bo *old_bo;
832         char format_str[5]; /* need to leave room for terminating \0 */
833         unsigned int fourcc;
834 };
835
836 static drmModeModeInfo *
837 connector_find_mode(struct device *dev, uint32_t con_id, const char *mode_str,
838         const float vrefresh)
839 {
840         drmModeConnector *connector;
841         drmModeModeInfo *mode;
842         int i;
843
844         connector = get_connector_by_id(dev, con_id);
845         if (!connector || !connector->count_modes)
846                 return NULL;
847
848         /* Pick by Index */
849         if (mode_str[0] == '#') {
850                 int index = atoi(mode_str + 1);
851
852                 if (index >= connector->count_modes || index < 0)
853                         return NULL;
854                 return &connector->modes[index];
855         }
856
857         /* Pick by Name */
858         for (i = 0; i < connector->count_modes; i++) {
859                 mode = &connector->modes[i];
860                 if (!strcmp(mode->name, mode_str)) {
861                         /* If the vertical refresh frequency is not specified
862                          * then return the first mode that match with the name.
863                          * Else, return the mode that match the name and
864                          * the specified vertical refresh frequency.
865                          */
866                         if (vrefresh == 0)
867                                 return mode;
868                         else if (fabs(mode_vrefresh(mode) - vrefresh) < 0.005)
869                                 return mode;
870                 }
871         }
872
873         return NULL;
874 }
875
876 static struct crtc *pipe_find_crtc(struct device *dev, struct pipe_arg *pipe)
877 {
878         uint32_t possible_crtcs = ~0;
879         uint32_t active_crtcs = 0;
880         unsigned int crtc_idx;
881         unsigned int i;
882         int j;
883
884         for (i = 0; i < pipe->num_cons; ++i) {
885                 uint32_t crtcs_for_connector = 0;
886                 drmModeConnector *connector;
887                 drmModeEncoder *encoder;
888                 struct crtc *crtc;
889
890                 connector = get_connector_by_id(dev, pipe->con_ids[i]);
891                 if (!connector)
892                         return NULL;
893
894                 for (j = 0; j < connector->count_encoders; ++j) {
895                         encoder = get_encoder_by_id(dev, connector->encoders[j]);
896                         if (!encoder)
897                                 continue;
898
899                         crtcs_for_connector |= encoder->possible_crtcs;
900                         crtc = get_crtc_by_id(dev, encoder->crtc_id);
901                         if (!crtc)
902                                 continue;
903                         active_crtcs |= get_crtc_mask(dev, crtc);
904                 }
905
906                 possible_crtcs &= crtcs_for_connector;
907         }
908
909         if (!possible_crtcs)
910                 return NULL;
911
912         /* Return the first possible and active CRTC if one exists, or the first
913          * possible CRTC otherwise.
914          */
915         if (possible_crtcs & active_crtcs)
916                 crtc_idx = ffs(possible_crtcs & active_crtcs);
917         else
918                 crtc_idx = ffs(possible_crtcs);
919
920         return &dev->resources->crtcs[crtc_idx - 1];
921 }
922
923 static int pipe_find_crtc_and_mode(struct device *dev, struct pipe_arg *pipe)
924 {
925         drmModeModeInfo *mode = NULL;
926         int i;
927
928         pipe->mode = NULL;
929
930         for (i = 0; i < (int)pipe->num_cons; i++) {
931                 mode = connector_find_mode(dev, pipe->con_ids[i],
932                                            pipe->mode_str, pipe->vrefresh);
933                 if (mode == NULL) {
934                         if (pipe->vrefresh)
935                                 fprintf(stderr,
936                                 "failed to find mode "
937                                 "\"%s-%.2fHz\" for connector %s\n",
938                                 pipe->mode_str, pipe->vrefresh, pipe->cons[i]);
939                         else
940                                 fprintf(stderr,
941                                 "failed to find mode \"%s\" for connector %s\n",
942                                 pipe->mode_str, pipe->cons[i]);
943                         return -EINVAL;
944                 }
945         }
946
947         /* If the CRTC ID was specified, get the corresponding CRTC. Otherwise
948          * locate a CRTC that can be attached to all the connectors.
949          */
950         if (pipe->crtc_id != (uint32_t)-1) {
951                 pipe->crtc = get_crtc_by_id(dev, pipe->crtc_id);
952         } else {
953                 pipe->crtc = pipe_find_crtc(dev, pipe);
954                 pipe->crtc_id = pipe->crtc->crtc->crtc_id;
955         }
956
957         if (!pipe->crtc) {
958                 fprintf(stderr, "failed to find CRTC for pipe\n");
959                 return -EINVAL;
960         }
961
962         pipe->mode = mode;
963         pipe->crtc->mode = mode;
964
965         return 0;
966 }
967
968 /* -----------------------------------------------------------------------------
969  * Properties
970  */
971
972 struct property_arg {
973         uint32_t obj_id;
974         uint32_t obj_type;
975         char name[DRM_PROP_NAME_LEN+1];
976         uint32_t prop_id;
977         uint64_t value;
978         bool optional;
979 };
980
981 static bool set_property(struct device *dev, struct property_arg *p)
982 {
983         drmModeObjectProperties *props = NULL;
984         drmModePropertyRes **props_info = NULL;
985         const char *obj_type;
986         int ret;
987         int i;
988
989         p->obj_type = 0;
990         p->prop_id = 0;
991
992 #define find_object(_res, type, Type)                                   \
993         do {                                                                    \
994                 for (i = 0; i < (int)(_res)->count_##type##s; ++i) {    \
995                         struct type *obj = &(_res)->type##s[i];                 \
996                         if (obj->type->type##_id != p->obj_id)                  \
997                                 continue;                                       \
998                         p->obj_type = DRM_MODE_OBJECT_##Type;                   \
999                         obj_type = #Type;                                       \
1000                         props = obj->props;                                     \
1001                         props_info = obj->props_info;                           \
1002                 }                                                               \
1003         } while(0)                                                              \
1004
1005         find_object(dev->resources, crtc, CRTC);
1006         if (p->obj_type == 0)
1007                 find_object(dev->resources, connector, CONNECTOR);
1008         if (p->obj_type == 0)
1009                 find_object(dev->resources, plane, PLANE);
1010         if (p->obj_type == 0) {
1011                 fprintf(stderr, "Object %i not found, can't set property\n",
1012                         p->obj_id);
1013                 return false;
1014         }
1015
1016         if (!props) {
1017                 fprintf(stderr, "%s %i has no properties\n",
1018                         obj_type, p->obj_id);
1019                 return false;
1020         }
1021
1022         for (i = 0; i < (int)props->count_props; ++i) {
1023                 if (!props_info[i])
1024                         continue;
1025                 if (strcmp(props_info[i]->name, p->name) == 0)
1026                         break;
1027         }
1028
1029         if (i == (int)props->count_props) {
1030                 if (!p->optional)
1031                         fprintf(stderr, "%s %i has no %s property\n",
1032                                 obj_type, p->obj_id, p->name);
1033                 return false;
1034         }
1035
1036         p->prop_id = props->props[i];
1037
1038         if (!dev->use_atomic)
1039                 ret = drmModeObjectSetProperty(dev->fd, p->obj_id, p->obj_type,
1040                                                                            p->prop_id, p->value);
1041         else
1042                 ret = drmModeAtomicAddProperty(dev->req, p->obj_id, p->prop_id, p->value);
1043
1044         if (ret < 0)
1045                 fprintf(stderr, "failed to set %s %i property %s to %" PRIu64 ": %s\n",
1046                         obj_type, p->obj_id, p->name, p->value, strerror(errno));
1047
1048         return true;
1049 }
1050
1051 /* -------------------------------------------------------------------------- */
1052
1053 static void
1054 page_flip_handler(int fd, unsigned int frame,
1055                   unsigned int sec, unsigned int usec, void *data)
1056 {
1057         struct pipe_arg *pipe;
1058         unsigned int new_fb_id;
1059         struct timeval end;
1060         double t;
1061
1062         pipe = data;
1063         if (pipe->current_fb_id == pipe->fb_id[0])
1064                 new_fb_id = pipe->fb_id[1];
1065         else
1066                 new_fb_id = pipe->fb_id[0];
1067
1068         drmModePageFlip(fd, pipe->crtc_id, new_fb_id,
1069                         DRM_MODE_PAGE_FLIP_EVENT, pipe);
1070         pipe->current_fb_id = new_fb_id;
1071         pipe->swap_count++;
1072         if (pipe->swap_count == 60) {
1073                 gettimeofday(&end, NULL);
1074                 t = end.tv_sec + end.tv_usec * 1e-6 -
1075                         (pipe->start.tv_sec + pipe->start.tv_usec * 1e-6);
1076                 fprintf(stderr, "freq: %.02fHz\n", pipe->swap_count / t);
1077                 pipe->swap_count = 0;
1078                 pipe->start = end;
1079         }
1080 }
1081
1082 static bool format_support(const drmModePlanePtr ovr, uint32_t fmt)
1083 {
1084         unsigned int i;
1085
1086         for (i = 0; i < ovr->count_formats; ++i) {
1087                 if (ovr->formats[i] == fmt)
1088                         return true;
1089         }
1090
1091         return false;
1092 }
1093
1094 static void add_property(struct device *dev, uint32_t obj_id,
1095                                const char *name, uint64_t value)
1096 {
1097         struct property_arg p;
1098
1099         p.obj_id = obj_id;
1100         strcpy(p.name, name);
1101         p.value = value;
1102
1103         set_property(dev, &p);
1104 }
1105
1106 static bool add_property_optional(struct device *dev, uint32_t obj_id,
1107                                   const char *name, uint64_t value)
1108 {
1109         struct property_arg p;
1110
1111         p.obj_id = obj_id;
1112         strcpy(p.name, name);
1113         p.value = value;
1114         p.optional = true;
1115
1116         return set_property(dev, &p);
1117 }
1118
1119 static void set_gamma(struct device *dev, unsigned crtc_id, unsigned fourcc)
1120 {
1121         unsigned blob_id = 0;
1122         /* TODO: support 1024-sized LUTs, when the use-case arises */
1123         struct drm_color_lut gamma_lut[256];
1124         int i, ret;
1125
1126         if (fourcc == DRM_FORMAT_C8) {
1127                 /* TODO: Add C8 support for more patterns */
1128                 util_smpte_c8_gamma(256, gamma_lut);
1129                 drmModeCreatePropertyBlob(dev->fd, gamma_lut, sizeof(gamma_lut), &blob_id);
1130         } else {
1131                 for (i = 0; i < 256; i++) {
1132                         gamma_lut[i].red =
1133                         gamma_lut[i].green =
1134                         gamma_lut[i].blue = i << 8;
1135                 }
1136         }
1137
1138         add_property_optional(dev, crtc_id, "DEGAMMA_LUT", 0);
1139         add_property_optional(dev, crtc_id, "CTM", 0);
1140         if (!add_property_optional(dev, crtc_id, "GAMMA_LUT", blob_id)) {
1141                 uint16_t r[256], g[256], b[256];
1142
1143                 for (i = 0; i < 256; i++) {
1144                         r[i] = gamma_lut[i].red;
1145                         g[i] = gamma_lut[i].green;
1146                         b[i] = gamma_lut[i].blue;
1147                 }
1148
1149                 ret = drmModeCrtcSetGamma(dev->fd, crtc_id, 256, r, g, b);
1150                 if (ret)
1151                         fprintf(stderr, "failed to set gamma: %s\n", strerror(errno));
1152         }
1153 }
1154
1155 static int
1156 bo_fb_create(int fd, unsigned int fourcc, const uint32_t w, const uint32_t h,
1157              enum util_fill_pattern pat, struct bo **out_bo, unsigned int *out_fb_id)
1158 {
1159         uint32_t handles[4] = {0}, pitches[4] = {0}, offsets[4] = {0};
1160         struct bo *bo;
1161         unsigned int fb_id;
1162
1163         bo = bo_create(fd, fourcc, w, h, handles, pitches, offsets, pat);
1164
1165         if (bo == NULL)
1166                 return -1;
1167
1168         if (drmModeAddFB2(fd, w, h, fourcc, handles, pitches, offsets, &fb_id, 0)) {
1169                 fprintf(stderr, "failed to add fb (%ux%u): %s\n", w, h, strerror(errno));
1170                 bo_destroy(bo);
1171                 return -1;
1172         }
1173         *out_bo = bo;
1174         *out_fb_id = fb_id;
1175         return 0;
1176 }
1177
1178 static int atomic_set_plane(struct device *dev, struct plane_arg *p,
1179                                                         int pattern, bool update)
1180 {
1181         struct bo *plane_bo;
1182         int crtc_x, crtc_y, crtc_w, crtc_h;
1183         struct crtc *crtc = NULL;
1184         unsigned int old_fb_id;
1185
1186         /* Find an unused plane which can be connected to our CRTC. Find the
1187          * CRTC index first, then iterate over available planes.
1188          */
1189         crtc = get_crtc_by_id(dev, p->crtc_id);
1190         if (!crtc) {
1191                 fprintf(stderr, "CRTC %u not found\n", p->crtc_id);
1192                 return -1;
1193         }
1194
1195         if (!update)
1196                 fprintf(stderr, "testing %dx%d@%s on plane %u, crtc %u\n",
1197                         p->w, p->h, p->format_str, p->plane_id, p->crtc_id);
1198
1199         plane_bo = p->old_bo;
1200         p->old_bo = p->bo;
1201
1202         if (!plane_bo) {
1203                 if (bo_fb_create(dev->fd, p->fourcc, p->w, p->h,
1204                          pattern, &plane_bo, &p->fb_id))
1205                         return -1;
1206         }
1207
1208         p->bo = plane_bo;
1209
1210         old_fb_id = p->fb_id;
1211         p->old_fb_id = old_fb_id;
1212
1213         crtc_w = p->w * p->scale;
1214         crtc_h = p->h * p->scale;
1215         if (!p->has_position) {
1216                 /* Default to the middle of the screen */
1217                 crtc_x = (crtc->mode->hdisplay - crtc_w) / 2;
1218                 crtc_y = (crtc->mode->vdisplay - crtc_h) / 2;
1219         } else {
1220                 crtc_x = p->x;
1221                 crtc_y = p->y;
1222         }
1223
1224         add_property(dev, p->plane_id, "FB_ID", p->fb_id);
1225         add_property(dev, p->plane_id, "CRTC_ID", p->crtc_id);
1226         add_property(dev, p->plane_id, "SRC_X", 0);
1227         add_property(dev, p->plane_id, "SRC_Y", 0);
1228         add_property(dev, p->plane_id, "SRC_W", p->w << 16);
1229         add_property(dev, p->plane_id, "SRC_H", p->h << 16);
1230         add_property(dev, p->plane_id, "CRTC_X", crtc_x);
1231         add_property(dev, p->plane_id, "CRTC_Y", crtc_y);
1232         add_property(dev, p->plane_id, "CRTC_W", crtc_w);
1233         add_property(dev, p->plane_id, "CRTC_H", crtc_h);
1234
1235         return 0;
1236 }
1237
1238 static int set_plane(struct device *dev, struct plane_arg *p)
1239 {
1240         drmModePlane *ovr;
1241         uint32_t plane_id;
1242         int crtc_x, crtc_y, crtc_w, crtc_h;
1243         struct crtc *crtc = NULL;
1244         unsigned int i, crtc_mask;
1245
1246         /* Find an unused plane which can be connected to our CRTC. Find the
1247          * CRTC index first, then iterate over available planes.
1248          */
1249         crtc = get_crtc_by_id(dev, p->crtc_id);
1250         if (!crtc) {
1251                 fprintf(stderr, "CRTC %u not found\n", p->crtc_id);
1252                 return -1;
1253         }
1254         crtc_mask = get_crtc_mask(dev, crtc);
1255         plane_id = p->plane_id;
1256
1257         for (i = 0; i < dev->resources->count_planes; i++) {
1258                 ovr = dev->resources->planes[i].plane;
1259                 if (!ovr)
1260                         continue;
1261
1262                 if (plane_id && plane_id != ovr->plane_id)
1263                         continue;
1264
1265                 if (!format_support(ovr, p->fourcc))
1266                         continue;
1267
1268                 if ((ovr->possible_crtcs & crtc_mask) &&
1269                     (ovr->crtc_id == 0 || ovr->crtc_id == p->crtc_id)) {
1270                         plane_id = ovr->plane_id;
1271                         break;
1272                 }
1273         }
1274
1275         if (i == dev->resources->count_planes) {
1276                 fprintf(stderr, "no unused plane available for CRTC %u\n",
1277                         p->crtc_id);
1278                 return -1;
1279         }
1280
1281         fprintf(stderr, "testing %dx%d@%s overlay plane %u\n",
1282                 p->w, p->h, p->format_str, plane_id);
1283
1284         /* just use single plane format for now.. */
1285         if (bo_fb_create(dev->fd, p->fourcc, p->w, p->h,
1286                          secondary_fill, &p->bo, &p->fb_id))
1287                 return -1;
1288
1289         crtc_w = p->w * p->scale;
1290         crtc_h = p->h * p->scale;
1291         if (!p->has_position) {
1292                 /* Default to the middle of the screen */
1293                 crtc_x = (crtc->mode->hdisplay - crtc_w) / 2;
1294                 crtc_y = (crtc->mode->vdisplay - crtc_h) / 2;
1295         } else {
1296                 crtc_x = p->x;
1297                 crtc_y = p->y;
1298         }
1299
1300         /* note src coords (last 4 args) are in Q16 format */
1301         if (drmModeSetPlane(dev->fd, plane_id, p->crtc_id, p->fb_id,
1302                             0, crtc_x, crtc_y, crtc_w, crtc_h,
1303                             0, 0, p->w << 16, p->h << 16)) {
1304                 fprintf(stderr, "failed to enable plane: %s\n",
1305                         strerror(errno));
1306                 return -1;
1307         }
1308
1309         ovr->crtc_id = p->crtc_id;
1310
1311         return 0;
1312 }
1313
1314 static void atomic_set_planes(struct device *dev, struct plane_arg *p,
1315                               unsigned int count, bool update)
1316 {
1317         unsigned int i, pattern = primary_fill;
1318
1319         /* set up planes */
1320         for (i = 0; i < count; i++) {
1321                 if (i > 0)
1322                         pattern = secondary_fill;
1323                 else
1324                         set_gamma(dev, p[i].crtc_id, p[i].fourcc);
1325
1326                 if (atomic_set_plane(dev, &p[i], pattern, update))
1327                         return;
1328         }
1329 }
1330
1331 static void
1332 atomic_test_page_flip(struct device *dev, struct pipe_arg *pipe_args,
1333               struct plane_arg *plane_args, unsigned int plane_count)
1334 {
1335     int ret;
1336
1337         gettimeofday(&pipe_args->start, NULL);
1338         pipe_args->swap_count = 0;
1339
1340         while (true) {
1341                 drmModeAtomicFree(dev->req);
1342                 dev->req = drmModeAtomicAlloc();
1343                 atomic_set_planes(dev, plane_args, plane_count, true);
1344
1345                 ret = drmModeAtomicCommit(dev->fd, dev->req, DRM_MODE_ATOMIC_ALLOW_MODESET, NULL);
1346                 if (ret) {
1347                         fprintf(stderr, "Atomic Commit failed [2]\n");
1348                         return;
1349                 }
1350
1351                 pipe_args->swap_count++;
1352                 if (pipe_args->swap_count == 60) {
1353                         struct timeval end;
1354                         double t;
1355
1356                         gettimeofday(&end, NULL);
1357                         t = end.tv_sec + end.tv_usec * 1e-6 -
1358                             (pipe_args->start.tv_sec + pipe_args->start.tv_usec * 1e-6);
1359                         fprintf(stderr, "freq: %.02fHz\n", pipe_args->swap_count / t);
1360                         pipe_args->swap_count = 0;
1361                         pipe_args->start = end;
1362                 }
1363         }
1364 }
1365
1366 static void atomic_clear_planes(struct device *dev, struct plane_arg *p, unsigned int count)
1367 {
1368         unsigned int i;
1369
1370         for (i = 0; i < count; i++) {
1371                 add_property(dev, p[i].plane_id, "FB_ID", 0);
1372                 add_property(dev, p[i].plane_id, "CRTC_ID", 0);
1373                 add_property(dev, p[i].plane_id, "SRC_X", 0);
1374                 add_property(dev, p[i].plane_id, "SRC_Y", 0);
1375                 add_property(dev, p[i].plane_id, "SRC_W", 0);
1376                 add_property(dev, p[i].plane_id, "SRC_H", 0);
1377                 add_property(dev, p[i].plane_id, "CRTC_X", 0);
1378                 add_property(dev, p[i].plane_id, "CRTC_Y", 0);
1379                 add_property(dev, p[i].plane_id, "CRTC_W", 0);
1380                 add_property(dev, p[i].plane_id, "CRTC_H", 0);
1381         }
1382 }
1383
1384 static void atomic_clear_FB(struct device *dev, struct plane_arg *p, unsigned int count)
1385 {
1386         unsigned int i;
1387
1388         for (i = 0; i < count; i++) {
1389                 if (p[i].fb_id) {
1390                         drmModeRmFB(dev->fd, p[i].fb_id);
1391                         p[i].fb_id = 0;
1392                 }
1393                 if (p[i].old_fb_id) {
1394                         drmModeRmFB(dev->fd, p[i].old_fb_id);
1395                         p[i].old_fb_id = 0;
1396                 }
1397                 if (p[i].bo) {
1398                         bo_destroy(p[i].bo);
1399                         p[i].bo = NULL;
1400                 }
1401                 if (p[i].old_bo) {
1402                         bo_destroy(p[i].old_bo);
1403                         p[i].old_bo = NULL;
1404                 }
1405
1406         }
1407 }
1408
1409 static void clear_planes(struct device *dev, struct plane_arg *p, unsigned int count)
1410 {
1411         unsigned int i;
1412
1413         for (i = 0; i < count; i++) {
1414                 if (p[i].fb_id)
1415                         drmModeRmFB(dev->fd, p[i].fb_id);
1416                 if (p[i].bo)
1417                         bo_destroy(p[i].bo);
1418         }
1419 }
1420
1421 static int pipe_resolve_connectors(struct device *dev, struct pipe_arg *pipe)
1422 {
1423         drmModeConnector *connector;
1424         unsigned int i;
1425         uint32_t id;
1426         char *endp;
1427
1428         for (i = 0; i < pipe->num_cons; i++) {
1429                 id = strtoul(pipe->cons[i], &endp, 10);
1430                 if (endp == pipe->cons[i]) {
1431                         connector = get_connector_by_name(dev, pipe->cons[i]);
1432                         if (!connector) {
1433                                 fprintf(stderr, "no connector named '%s'\n",
1434                                         pipe->cons[i]);
1435                                 return -ENODEV;
1436                         }
1437
1438                         id = connector->connector_id;
1439                 }
1440
1441                 pipe->con_ids[i] = id;
1442         }
1443
1444         return 0;
1445 }
1446
1447 static bool pipe_has_writeback_connector(struct device *dev, struct pipe_arg *pipes,
1448                 unsigned int count)
1449 {
1450         drmModeConnector *connector;
1451         unsigned int i, j;
1452
1453         for (j = 0; j < count; j++) {
1454                 struct pipe_arg *pipe = &pipes[j];
1455
1456                 for (i = 0; i < pipe->num_cons; i++) {
1457                         connector = get_connector_by_id(dev, pipe->con_ids[i]);
1458                         if (connector && connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
1459                                 return true;
1460                 }
1461         }
1462         return false;
1463 }
1464
1465 static int pipe_attempt_connector(struct device *dev, drmModeConnector *con,
1466                 struct pipe_arg *pipe)
1467 {
1468         char *con_str;
1469         int i;
1470
1471         con_str = calloc(8, sizeof(char));
1472         if (!con_str)
1473                 return -1;
1474
1475         sprintf(con_str, "%d", con->connector_id);
1476         strcpy(pipe->format_str, "XR24");
1477         pipe->fourcc = util_format_fourcc(pipe->format_str);
1478         pipe->num_cons = 1;
1479         pipe->con_ids = calloc(1, sizeof(*pipe->con_ids));
1480         pipe->cons = calloc(1, sizeof(*pipe->cons));
1481
1482         if (!pipe->con_ids || !pipe->cons)
1483                 goto free_con_str;
1484
1485         pipe->con_ids[0] = con->connector_id;
1486         pipe->cons[0] = (const char*)con_str;
1487
1488         pipe->crtc = pipe_find_crtc(dev, pipe);
1489         if (!pipe->crtc)
1490                 goto free_all;
1491
1492         pipe->crtc_id = pipe->crtc->crtc->crtc_id;
1493
1494         /* Return the first mode if no preferred. */
1495         pipe->mode = &con->modes[0];
1496
1497         for (i = 0; i < con->count_modes; i++) {
1498                 drmModeModeInfo *current_mode = &con->modes[i];
1499
1500                 if (current_mode->type & DRM_MODE_TYPE_PREFERRED) {
1501                         pipe->mode = current_mode;
1502                         break;
1503                 }
1504         }
1505
1506         sprintf(pipe->mode_str, "%dx%d", pipe->mode->hdisplay, pipe->mode->vdisplay);
1507
1508         return 0;
1509
1510 free_all:
1511         free(pipe->cons);
1512         free(pipe->con_ids);
1513 free_con_str:
1514         free(con_str);
1515         return -1;
1516 }
1517
1518 static int pipe_find_preferred(struct device *dev, struct pipe_arg **out_pipes)
1519 {
1520         struct pipe_arg *pipes;
1521         struct resources *res = dev->resources;
1522         drmModeConnector *con = NULL;
1523         int i, connected = 0, attempted = 0;
1524
1525         for (i = 0; i < res->count_connectors; i++) {
1526                 con = res->connectors[i].connector;
1527                 if (!con || con->connection != DRM_MODE_CONNECTED ||
1528                     con->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
1529                         continue;
1530                 connected++;
1531         }
1532         if (!connected) {
1533                 printf("no connected connector!\n");
1534                 return 0;
1535         }
1536
1537         pipes = calloc(connected, sizeof(struct pipe_arg));
1538         if (!pipes)
1539                 return 0;
1540
1541         for (i = 0; i < res->count_connectors && attempted < connected; i++) {
1542                 con = res->connectors[i].connector;
1543                 if (!con || con->connection != DRM_MODE_CONNECTED)
1544                         continue;
1545
1546                 if (pipe_attempt_connector(dev, con, &pipes[attempted]) < 0) {
1547                         printf("failed fetching preferred mode for connector\n");
1548                         continue;
1549                 }
1550                 attempted++;
1551         }
1552
1553         *out_pipes = pipes;
1554         return attempted;
1555 }
1556
1557 static struct plane *get_primary_plane_by_crtc(struct device *dev, struct crtc *crtc)
1558 {
1559         unsigned int i;
1560
1561         for (i = 0; i < dev->resources->count_planes; i++) {
1562                 struct plane *plane = &dev->resources->planes[i];
1563                 drmModePlane *ovr = plane->plane;
1564                 if (!ovr)
1565                         continue;
1566
1567                 // XXX: add is_primary_plane and (?) format checks
1568
1569                 if (ovr->possible_crtcs & get_crtc_mask(dev, crtc))
1570             return plane;
1571         }
1572         return NULL;
1573 }
1574
1575 static void set_mode(struct device *dev, struct pipe_arg *pipes, unsigned int count)
1576 {
1577         unsigned int i, j;
1578         int ret, x = 0;
1579         int preferred = count == 0;
1580
1581         for (i = 0; i < count; i++) {
1582                 struct pipe_arg *pipe = &pipes[i];
1583
1584                 ret = pipe_resolve_connectors(dev, pipe);
1585                 if (ret < 0)
1586                         return;
1587
1588                 ret = pipe_find_crtc_and_mode(dev, pipe);
1589                 if (ret < 0)
1590                         continue;
1591         }
1592         if (preferred) {
1593                 struct pipe_arg *pipe_args;
1594
1595                 count = pipe_find_preferred(dev, &pipe_args);
1596                 if (!count) {
1597                         fprintf(stderr, "can't find any preferred connector/mode.\n");
1598                         return;
1599                 }
1600                 pipes = pipe_args;
1601         }
1602
1603         if (!dev->use_atomic) {
1604                 for (i = 0; i < count; i++) {
1605                         struct pipe_arg *pipe = &pipes[i];
1606
1607                         if (pipe->mode == NULL)
1608                                 continue;
1609
1610                         if (!preferred) {
1611                                 dev->mode.width += pipe->mode->hdisplay;
1612                                 if (dev->mode.height < pipe->mode->vdisplay)
1613                                         dev->mode.height = pipe->mode->vdisplay;
1614                         } else {
1615                                 /* XXX: Use a clone mode, more like atomic. We could do per
1616                                  * connector bo/fb, so we don't have the stretched image.
1617                                  */
1618                                 if (dev->mode.width < pipe->mode->hdisplay)
1619                                         dev->mode.width = pipe->mode->hdisplay;
1620                                 if (dev->mode.height < pipe->mode->vdisplay)
1621                                         dev->mode.height = pipe->mode->vdisplay;
1622                         }
1623                 }
1624
1625                 if (bo_fb_create(dev->fd, pipes[0].fourcc, dev->mode.width, dev->mode.height,
1626                                      primary_fill, &dev->mode.bo, &dev->mode.fb_id))
1627                         return;
1628         }
1629
1630         for (i = 0; i < count; i++) {
1631                 struct pipe_arg *pipe = &pipes[i];
1632                 uint32_t blob_id;
1633
1634                 if (pipe->mode == NULL)
1635                         continue;
1636
1637                 printf("setting mode %s-%.2fHz on connectors ",
1638                        pipe->mode->name, mode_vrefresh(pipe->mode));
1639                 for (j = 0; j < pipe->num_cons; ++j) {
1640                         printf("%s, ", pipe->cons[j]);
1641                         if (dev->use_atomic)
1642                                 add_property(dev, pipe->con_ids[j], "CRTC_ID", pipe->crtc_id);
1643                 }
1644                 printf("crtc %d\n", pipe->crtc_id);
1645
1646                 if (!dev->use_atomic) {
1647                         ret = drmModeSetCrtc(dev->fd, pipe->crtc_id, dev->mode.fb_id,
1648                                                                  x, 0, pipe->con_ids, pipe->num_cons,
1649                                                                  pipe->mode);
1650
1651                         /* XXX: Actually check if this is needed */
1652                         drmModeDirtyFB(dev->fd, dev->mode.fb_id, NULL, 0);
1653
1654                         if (!preferred)
1655                                 x += pipe->mode->hdisplay;
1656
1657                         if (ret) {
1658                                 fprintf(stderr, "failed to set mode: %s\n", strerror(errno));
1659                                 return;
1660                         }
1661
1662                         set_gamma(dev, pipe->crtc_id, pipe->fourcc);
1663                 } else {
1664                         drmModeCreatePropertyBlob(dev->fd, pipe->mode, sizeof(*pipe->mode), &blob_id);
1665                         add_property(dev, pipe->crtc_id, "MODE_ID", blob_id);
1666                         add_property(dev, pipe->crtc_id, "ACTIVE", 1);
1667
1668                         /* By default atomic modeset does not set a primary plane, shrug */
1669                         if (preferred) {
1670                                 struct plane *plane = get_primary_plane_by_crtc(dev, pipe->crtc);
1671                                 struct plane_arg plane_args = {
1672                                         .plane_id = plane->plane->plane_id,
1673                                         .crtc_id = pipe->crtc_id,
1674                                         .w = pipe->mode->hdisplay,
1675                                         .h = pipe->mode->vdisplay,
1676                                         .scale = 1.0,
1677                                         .format_str = "XR24",
1678                                         .fourcc = util_format_fourcc(pipe->format_str),
1679                                 };
1680
1681                                 atomic_set_planes(dev, &plane_args, 1, false);
1682                         }
1683                 }
1684         }
1685 }
1686
1687 static void writeback_config(struct device *dev, struct pipe_arg *pipes, unsigned int count)
1688 {
1689         drmModeConnector *connector;
1690         unsigned int i, j;
1691
1692         for (j = 0; j < count; j++) {
1693                 struct pipe_arg *pipe = &pipes[j];
1694
1695                 for (i = 0; i < pipe->num_cons; i++) {
1696                         connector = get_connector_by_id(dev, pipe->con_ids[i]);
1697                         if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK) {
1698                                 if (!pipe->mode) {
1699                                         fprintf(stderr, "no mode for writeback\n");
1700                                         return;
1701                                 }
1702                                 bo_fb_create(dev->fd, pipes[j].fourcc,
1703                                              pipe->mode->hdisplay, pipe->mode->vdisplay,
1704                                              UTIL_PATTERN_PLAIN,
1705                                              &pipe->out_bo, &pipe->out_fb_id);
1706                                 add_property(dev, pipe->con_ids[i], "WRITEBACK_FB_ID",
1707                                              pipe->out_fb_id);
1708                                 add_property(dev, pipe->con_ids[i], "WRITEBACK_OUT_FENCE_PTR",
1709                                              (uintptr_t)(&dev->writeback_fence_fd));
1710                         }
1711                 }
1712         }
1713 }
1714
1715 static int poll_writeback_fence(int fd, int timeout)
1716 {
1717         struct pollfd fds = { fd, POLLIN };
1718         int ret;
1719
1720         do {
1721                 ret = poll(&fds, 1, timeout);
1722                 if (ret > 0) {
1723                         if (fds.revents & (POLLERR | POLLNVAL))
1724                                 return -EINVAL;
1725
1726                         return 0;
1727                 } else if (ret == 0) {
1728                         return -ETIMEDOUT;
1729                 } else {
1730                         ret = -errno;
1731                         if (ret == -EINTR || ret == -EAGAIN)
1732                                 continue;
1733                         return ret;
1734                 }
1735         } while (1);
1736
1737 }
1738
1739 static void dump_output_fb(struct device *dev, struct pipe_arg *pipes, char *dump_path,
1740                            unsigned int count)
1741 {
1742         drmModeConnector *connector;
1743         unsigned int i, j;
1744
1745         for (j = 0; j < count; j++) {
1746                 struct pipe_arg *pipe = &pipes[j];
1747
1748                 for (i = 0; i < pipe->num_cons; i++) {
1749                         connector = get_connector_by_id(dev, pipe->con_ids[i]);
1750                         if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
1751                                 bo_dump(pipe->out_bo, dump_path);
1752                 }
1753         }
1754 }
1755
1756 static void atomic_clear_mode(struct device *dev, struct pipe_arg *pipes, unsigned int count)
1757 {
1758         unsigned int i;
1759         unsigned int j;
1760
1761         for (i = 0; i < count; i++) {
1762                 struct pipe_arg *pipe = &pipes[i];
1763
1764                 if (pipe->mode == NULL)
1765                         continue;
1766
1767                 for (j = 0; j < pipe->num_cons; ++j)
1768                         add_property(dev, pipe->con_ids[j], "CRTC_ID",0);
1769
1770                 add_property(dev, pipe->crtc_id, "MODE_ID", 0);
1771                 add_property(dev, pipe->crtc_id, "ACTIVE", 0);
1772         }
1773 }
1774
1775 static void clear_mode(struct device *dev)
1776 {
1777         if (dev->mode.fb_id)
1778                 drmModeRmFB(dev->fd, dev->mode.fb_id);
1779         if (dev->mode.bo)
1780                 bo_destroy(dev->mode.bo);
1781 }
1782
1783 static void set_planes(struct device *dev, struct plane_arg *p, unsigned int count)
1784 {
1785         unsigned int i;
1786
1787         /* set up planes/overlays */
1788         for (i = 0; i < count; i++)
1789                 if (set_plane(dev, &p[i]))
1790                         return;
1791 }
1792
1793 static void set_cursors(struct device *dev, struct pipe_arg *pipes, unsigned int count)
1794 {
1795         uint32_t handles[4] = {0}, pitches[4] = {0}, offsets[4] = {0};
1796         uint32_t cw = 64;
1797         uint32_t ch = 64;
1798         struct bo *bo;
1799         uint64_t value;
1800         unsigned int i;
1801         int ret;
1802
1803         ret = drmGetCap(dev->fd, DRM_CAP_CURSOR_WIDTH, &value);
1804         if (!ret)
1805                 cw = value;
1806
1807         ret = drmGetCap(dev->fd, DRM_CAP_CURSOR_HEIGHT, &value);
1808         if (!ret)
1809                 ch = value;
1810
1811
1812         /* create cursor bo.. just using PATTERN_PLAIN as it has
1813          * translucent alpha
1814          */
1815         bo = bo_create(dev->fd, DRM_FORMAT_ARGB8888, cw, ch, handles, pitches,
1816                        offsets, UTIL_PATTERN_PLAIN);
1817         if (bo == NULL)
1818                 return;
1819
1820         dev->mode.cursor_bo = bo;
1821
1822         for (i = 0; i < count; i++) {
1823                 struct pipe_arg *pipe = &pipes[i];
1824                 ret = cursor_init(dev->fd, handles[0],
1825                                 pipe->crtc_id,
1826                                 pipe->mode->hdisplay, pipe->mode->vdisplay,
1827                                 cw, ch);
1828                 if (ret) {
1829                         fprintf(stderr, "failed to init cursor for CRTC[%u]\n",
1830                                         pipe->crtc_id);
1831                         return;
1832                 }
1833         }
1834
1835         cursor_start();
1836 }
1837
1838 static void clear_cursors(struct device *dev)
1839 {
1840         cursor_stop();
1841
1842         if (dev->mode.cursor_bo)
1843                 bo_destroy(dev->mode.cursor_bo);
1844 }
1845
1846 static void test_page_flip(struct device *dev, struct pipe_arg *pipes, unsigned int count)
1847 {
1848         unsigned int other_fb_id;
1849         struct bo *other_bo;
1850         drmEventContext evctx;
1851         unsigned int i;
1852         int ret;
1853
1854         if (bo_fb_create(dev->fd, pipes[0].fourcc, dev->mode.width, dev->mode.height,
1855                          UTIL_PATTERN_PLAIN, &other_bo, &other_fb_id))
1856                 return;
1857
1858         for (i = 0; i < count; i++) {
1859                 struct pipe_arg *pipe = &pipes[i];
1860
1861                 if (pipe->mode == NULL)
1862                         continue;
1863
1864                 ret = drmModePageFlip(dev->fd, pipe->crtc_id,
1865                                       other_fb_id, DRM_MODE_PAGE_FLIP_EVENT,
1866                                       pipe);
1867                 if (ret) {
1868                         fprintf(stderr, "failed to page flip: %s\n", strerror(errno));
1869                         goto err_rmfb;
1870                 }
1871                 gettimeofday(&pipe->start, NULL);
1872                 pipe->swap_count = 0;
1873                 pipe->fb_id[0] = dev->mode.fb_id;
1874                 pipe->fb_id[1] = other_fb_id;
1875                 pipe->current_fb_id = other_fb_id;
1876         }
1877
1878         memset(&evctx, 0, sizeof evctx);
1879         evctx.version = DRM_EVENT_CONTEXT_VERSION;
1880         evctx.vblank_handler = NULL;
1881         evctx.page_flip_handler = page_flip_handler;
1882
1883         while (1) {
1884 #if 0
1885                 struct pollfd pfd[2];
1886
1887                 pfd[0].fd = 0;
1888                 pfd[0].events = POLLIN;
1889                 pfd[1].fd = fd;
1890                 pfd[1].events = POLLIN;
1891
1892                 if (poll(pfd, 2, -1) < 0) {
1893                         fprintf(stderr, "poll error\n");
1894                         break;
1895                 }
1896
1897                 if (pfd[0].revents)
1898                         break;
1899 #else
1900                 struct timeval timeout = { .tv_sec = 3, .tv_usec = 0 };
1901                 fd_set fds;
1902
1903                 FD_ZERO(&fds);
1904                 FD_SET(0, &fds);
1905                 FD_SET(dev->fd, &fds);
1906                 ret = select(dev->fd + 1, &fds, NULL, NULL, &timeout);
1907
1908                 if (ret <= 0) {
1909                         fprintf(stderr, "select timed out or error (ret %d)\n",
1910                                 ret);
1911                         continue;
1912                 } else if (FD_ISSET(0, &fds)) {
1913                         break;
1914                 }
1915 #endif
1916
1917                 drmHandleEvent(dev->fd, &evctx);
1918         }
1919
1920 err_rmfb:
1921         drmModeRmFB(dev->fd, other_fb_id);
1922         bo_destroy(other_bo);
1923 }
1924
1925 #define min(a, b)       ((a) < (b) ? (a) : (b))
1926
1927 static int parse_connector(struct pipe_arg *pipe, const char *arg)
1928 {
1929         unsigned int len;
1930         unsigned int i;
1931         const char *p;
1932         char *endp;
1933
1934         pipe->vrefresh = 0;
1935         pipe->crtc_id = (uint32_t)-1;
1936         strcpy(pipe->format_str, "XR24");
1937
1938         /* Count the number of connectors and allocate them. */
1939         pipe->num_cons = 1;
1940         for (p = arg; *p && *p != ':' && *p != '@'; ++p) {
1941                 if (*p == ',')
1942                         pipe->num_cons++;
1943         }
1944
1945         pipe->con_ids = calloc(pipe->num_cons, sizeof(*pipe->con_ids));
1946         pipe->cons = calloc(pipe->num_cons, sizeof(*pipe->cons));
1947         if (pipe->con_ids == NULL || pipe->cons == NULL)
1948                 return -1;
1949
1950         /* Parse the connectors. */
1951         for (i = 0, p = arg; i < pipe->num_cons; ++i, p = endp + 1) {
1952                 endp = strpbrk(p, ",@:");
1953                 if (!endp)
1954                         break;
1955
1956                 pipe->cons[i] = strndup(p, endp - p);
1957
1958                 if (*endp != ',')
1959                         break;
1960         }
1961
1962         if (i != pipe->num_cons - 1)
1963                 return -1;
1964
1965         /* Parse the remaining parameters. */
1966         if (!endp)
1967                 return -1;
1968         if (*endp == '@') {
1969                 arg = endp + 1;
1970                 pipe->crtc_id = strtoul(arg, &endp, 10);
1971         }
1972         if (*endp != ':')
1973                 return -1;
1974
1975         arg = endp + 1;
1976
1977         /* Search for the vertical refresh or the format. */
1978         p = strpbrk(arg, "-@");
1979         if (p == NULL)
1980                 p = arg + strlen(arg);
1981         len = min(sizeof pipe->mode_str - 1, (unsigned int)(p - arg));
1982         strncpy(pipe->mode_str, arg, len);
1983         pipe->mode_str[len] = '\0';
1984
1985         if (*p == '-') {
1986                 pipe->vrefresh = strtof(p + 1, &endp);
1987                 p = endp;
1988         }
1989
1990         if (*p == '@') {
1991                 strncpy(pipe->format_str, p + 1, 4);
1992                 pipe->format_str[4] = '\0';
1993         }
1994
1995         pipe->fourcc = util_format_fourcc(pipe->format_str);
1996         if (pipe->fourcc == 0)  {
1997                 fprintf(stderr, "unknown format %s\n", pipe->format_str);
1998                 return -1;
1999         }
2000
2001         return 0;
2002 }
2003
2004 static int parse_plane(struct plane_arg *plane, const char *p)
2005 {
2006         char *end;
2007
2008         plane->plane_id = strtoul(p, &end, 10);
2009         if (*end != '@')
2010                 return -EINVAL;
2011
2012         p = end + 1;
2013         plane->crtc_id = strtoul(p, &end, 10);
2014         if (*end != ':')
2015                 return -EINVAL;
2016
2017         p = end + 1;
2018         plane->w = strtoul(p, &end, 10);
2019         if (*end != 'x')
2020                 return -EINVAL;
2021
2022         p = end + 1;
2023         plane->h = strtoul(p, &end, 10);
2024
2025         if (*end == '+' || *end == '-') {
2026                 plane->x = strtol(end, &end, 10);
2027                 if (*end != '+' && *end != '-')
2028                         return -EINVAL;
2029                 plane->y = strtol(end, &end, 10);
2030
2031                 plane->has_position = true;
2032         }
2033
2034         if (*end == '*') {
2035                 p = end + 1;
2036                 plane->scale = strtod(p, &end);
2037                 if (plane->scale <= 0.0)
2038                         return -EINVAL;
2039         } else {
2040                 plane->scale = 1.0;
2041         }
2042
2043         if (*end == '@') {
2044                 strncpy(plane->format_str, end + 1, 4);
2045                 plane->format_str[4] = '\0';
2046         } else {
2047                 strcpy(plane->format_str, "XR24");
2048         }
2049
2050         plane->fourcc = util_format_fourcc(plane->format_str);
2051         if (plane->fourcc == 0) {
2052                 fprintf(stderr, "unknown format %s\n", plane->format_str);
2053                 return -EINVAL;
2054         }
2055
2056         return 0;
2057 }
2058
2059 static int parse_property(struct property_arg *p, const char *arg)
2060 {
2061         if (sscanf(arg, "%d:%32[^:]:%" SCNu64, &p->obj_id, p->name, &p->value) != 3)
2062                 return -1;
2063
2064         p->obj_type = 0;
2065         p->name[DRM_PROP_NAME_LEN] = '\0';
2066
2067         return 0;
2068 }
2069
2070 static void parse_fill_patterns(char *arg)
2071 {
2072         char *fill = strtok(arg, ",");
2073         if (!fill)
2074                 return;
2075         primary_fill = util_pattern_enum(fill);
2076         fill = strtok(NULL, ",");
2077         if (!fill)
2078                 return;
2079         secondary_fill = util_pattern_enum(fill);
2080 }
2081
2082 static void usage(char *name)
2083 {
2084         fprintf(stderr, "usage: %s [-acDdefMoPpsCvrw]\n", name);
2085
2086         fprintf(stderr, "\n Query options:\n\n");
2087         fprintf(stderr, "\t-c\tlist connectors\n");
2088         fprintf(stderr, "\t-e\tlist encoders\n");
2089         fprintf(stderr, "\t-f\tlist framebuffers\n");
2090         fprintf(stderr, "\t-p\tlist CRTCs and planes (pipes)\n");
2091
2092         fprintf(stderr, "\n Test options:\n\n");
2093         fprintf(stderr, "\t-P <plane_id>@<crtc_id>:<w>x<h>[+<x>+<y>][*<scale>][@<format>]\tset a plane\n");
2094         fprintf(stderr, "\t-s <connector_id>[,<connector_id>][@<crtc_id>]:[#<mode index>]<mode>[-<vrefresh>][@<format>]\tset a mode\n");
2095         fprintf(stderr, "\t-C\ttest hw cursor\n");
2096         fprintf(stderr, "\t-v\ttest vsynced page flipping\n");
2097         fprintf(stderr, "\t-r\tset the preferred mode for all connectors\n");
2098         fprintf(stderr, "\t-w <obj_id>:<prop_name>:<value>\tset property\n");
2099         fprintf(stderr, "\t-a \tuse atomic API\n");
2100         fprintf(stderr, "\t-F pattern1,pattern2\tspecify fill patterns\n");
2101         fprintf(stderr, "\t-o <desired file path> \t Dump writeback output buffer to file\n");
2102
2103         fprintf(stderr, "\n Generic options:\n\n");
2104         fprintf(stderr, "\t-d\tdrop master after mode set\n");
2105         fprintf(stderr, "\t-M module\tuse the given driver\n");
2106         fprintf(stderr, "\t-D device\tuse the given device\n");
2107
2108         fprintf(stderr, "\n\tDefault is to dump all info.\n");
2109         exit(0);
2110 }
2111
2112 static char optstr[] = "acdD:efF:M:P:ps:Cvrw:o:";
2113
2114 int main(int argc, char **argv)
2115 {
2116         struct device dev;
2117
2118         int c;
2119         int encoders = 0, connectors = 0, crtcs = 0, planes = 0, framebuffers = 0;
2120         int drop_master = 0;
2121         int test_vsync = 0;
2122         int test_cursor = 0;
2123         int set_preferred = 0;
2124         int use_atomic = 0;
2125         char *device = NULL;
2126         char *module = NULL;
2127         unsigned int i;
2128         unsigned int count = 0, plane_count = 0;
2129         unsigned int prop_count = 0;
2130         struct pipe_arg *pipe_args = NULL;
2131         struct plane_arg *plane_args = NULL;
2132         struct property_arg *prop_args = NULL;
2133         unsigned int args = 0;
2134         int ret;
2135         char *dump_path = NULL;
2136
2137         memset(&dev, 0, sizeof dev);
2138
2139         opterr = 0;
2140         while ((c = getopt(argc, argv, optstr)) != -1) {
2141                 args++;
2142
2143                 switch (c) {
2144                 case 'a':
2145                         use_atomic = 1;
2146                         /* Preserve the default behaviour of dumping all information. */
2147                         args--;
2148                         break;
2149                 case 'c':
2150                         connectors = 1;
2151                         break;
2152                 case 'D':
2153                         device = optarg;
2154                         /* Preserve the default behaviour of dumping all information. */
2155                         args--;
2156                         break;
2157                 case 'd':
2158                         drop_master = 1;
2159                         break;
2160                 case 'e':
2161                         encoders = 1;
2162                         break;
2163                 case 'f':
2164                         framebuffers = 1;
2165                         break;
2166                 case 'F':
2167                         parse_fill_patterns(optarg);
2168                         break;
2169                 case 'M':
2170                         module = optarg;
2171                         /* Preserve the default behaviour of dumping all information. */
2172                         args--;
2173                         break;
2174                 case 'o':
2175                         dump_path = optarg;
2176                         break;
2177                 case 'P':
2178                         plane_args = realloc(plane_args,
2179                                              (plane_count + 1) * sizeof *plane_args);
2180                         if (plane_args == NULL) {
2181                                 fprintf(stderr, "memory allocation failed\n");
2182                                 return 1;
2183                         }
2184                         memset(&plane_args[plane_count], 0, sizeof(*plane_args));
2185
2186                         if (parse_plane(&plane_args[plane_count], optarg) < 0)
2187                                 usage(argv[0]);
2188
2189                         plane_count++;
2190                         break;
2191                 case 'p':
2192                         crtcs = 1;
2193                         planes = 1;
2194                         break;
2195                 case 's':
2196                         pipe_args = realloc(pipe_args,
2197                                             (count + 1) * sizeof *pipe_args);
2198                         if (pipe_args == NULL) {
2199                                 fprintf(stderr, "memory allocation failed\n");
2200                                 return 1;
2201                         }
2202                         memset(&pipe_args[count], 0, sizeof(*pipe_args));
2203
2204                         if (parse_connector(&pipe_args[count], optarg) < 0)
2205                                 usage(argv[0]);
2206
2207                         count++;
2208                         break;
2209                 case 'C':
2210                         test_cursor = 1;
2211                         break;
2212                 case 'v':
2213                         test_vsync = 1;
2214                         break;
2215                 case 'r':
2216                         set_preferred = 1;
2217                         break;
2218                 case 'w':
2219                         prop_args = realloc(prop_args,
2220                                            (prop_count + 1) * sizeof *prop_args);
2221                         if (prop_args == NULL) {
2222                                 fprintf(stderr, "memory allocation failed\n");
2223                                 return 1;
2224                         }
2225                         memset(&prop_args[prop_count], 0, sizeof(*prop_args));
2226
2227                         if (parse_property(&prop_args[prop_count], optarg) < 0)
2228                                 usage(argv[0]);
2229
2230                         prop_count++;
2231                         break;
2232                 default:
2233                         usage(argv[0]);
2234                         break;
2235                 }
2236         }
2237
2238         /* Dump all the details when no* arguments are provided. */
2239         if (!args)
2240                 encoders = connectors = crtcs = planes = framebuffers = 1;
2241
2242         if (test_vsync && !count) {
2243                 fprintf(stderr, "page flipping requires at least one -s option.\n");
2244                 return -1;
2245         }
2246         if (set_preferred && count) {
2247                 fprintf(stderr, "cannot use -r (preferred) when -s (mode) is set\n");
2248                 return -1;
2249         }
2250
2251         if (set_preferred && plane_count) {
2252                 fprintf(stderr, "cannot use -r (preferred) when -P (plane) is set\n");
2253                 return -1;
2254         }
2255
2256         dev.fd = util_open(device, module);
2257         if (dev.fd < 0)
2258                 return -1;
2259
2260         if (use_atomic) {
2261                 ret = drmSetClientCap(dev.fd, DRM_CLIENT_CAP_ATOMIC, 1);
2262                 drmSetClientCap(dev.fd, DRM_CLIENT_CAP_WRITEBACK_CONNECTORS, 1);
2263                 if (ret) {
2264                         fprintf(stderr, "no atomic modesetting support: %s\n", strerror(errno));
2265                         drmClose(dev.fd);
2266                         return -1;
2267                 }
2268         }
2269
2270         dev.use_atomic = use_atomic;
2271
2272         dev.resources = get_resources(&dev);
2273         if (!dev.resources) {
2274                 drmClose(dev.fd);
2275                 return 1;
2276         }
2277
2278 #define dump_resource(dev, res) if (res) dump_##res(dev)
2279
2280         dump_resource(&dev, encoders);
2281         dump_resource(&dev, connectors);
2282         dump_resource(&dev, crtcs);
2283         dump_resource(&dev, planes);
2284         dump_resource(&dev, framebuffers);
2285
2286         for (i = 0; i < prop_count; ++i)
2287                 set_property(&dev, &prop_args[i]);
2288
2289         if (dev.use_atomic) {
2290                 dev.req = drmModeAtomicAlloc();
2291
2292                 if (set_preferred || (count && plane_count)) {
2293                         uint64_t cap = 0;
2294
2295                         ret = drmGetCap(dev.fd, DRM_CAP_DUMB_BUFFER, &cap);
2296                         if (ret || cap == 0) {
2297                                 fprintf(stderr, "driver doesn't support the dumb buffer API\n");
2298                                 return 1;
2299                         }
2300
2301                         if (set_preferred || count)
2302                                 set_mode(&dev, pipe_args, count);
2303
2304                         if (dump_path) {
2305                                 if (!pipe_has_writeback_connector(&dev, pipe_args, count)) {
2306                                         fprintf(stderr, "No writeback connector found, can not dump.\n");
2307                                         return 1;
2308                                 }
2309
2310                                 writeback_config(&dev, pipe_args, count);
2311                         }
2312
2313                         if (plane_count)
2314                                 atomic_set_planes(&dev, plane_args, plane_count, false);
2315
2316                         ret = drmModeAtomicCommit(dev.fd, dev.req, DRM_MODE_ATOMIC_ALLOW_MODESET, NULL);
2317                         if (ret) {
2318                                 fprintf(stderr, "Atomic Commit failed [1]\n");
2319                                 return 1;
2320                         }
2321
2322                         /*
2323                          * Since only writeback connectors have an output fb, this should only be
2324                          * called for writeback.
2325                          */
2326                         if (dump_path) {
2327                                 ret = poll_writeback_fence(dev.writeback_fence_fd, 1000);
2328                                 if (ret)
2329                                         fprintf(stderr, "Poll for writeback error: %d. Skipping Dump.\n",
2330                                                         ret);
2331                                 dump_output_fb(&dev, pipe_args, dump_path, count);
2332                         }
2333
2334                         if (test_vsync)
2335                                 atomic_test_page_flip(&dev, pipe_args, plane_args, plane_count);
2336
2337                         if (drop_master)
2338                                 drmDropMaster(dev.fd);
2339
2340                         getchar();
2341
2342                         drmModeAtomicFree(dev.req);
2343                         dev.req = drmModeAtomicAlloc();
2344
2345                         /* XXX: properly teardown the preferred mode/plane state */
2346                         if (plane_count)
2347                                 atomic_clear_planes(&dev, plane_args, plane_count);
2348
2349                         if (count)
2350                                 atomic_clear_mode(&dev, pipe_args, count);
2351
2352                         ret = drmModeAtomicCommit(dev.fd, dev.req, DRM_MODE_ATOMIC_ALLOW_MODESET, NULL);
2353                         if (ret)
2354                                 fprintf(stderr, "Atomic Commit failed\n");
2355
2356                         if (plane_count)
2357                                 atomic_clear_FB(&dev, plane_args, plane_count);
2358                 }
2359
2360                 drmModeAtomicFree(dev.req);
2361         } else {
2362                 if (dump_path) {
2363                         fprintf(stderr, "writeback / dump is only supported in atomic mode\n");
2364                         return 1;
2365                 }
2366
2367                 if (set_preferred || count || plane_count) {
2368                         uint64_t cap = 0;
2369
2370                         ret = drmGetCap(dev.fd, DRM_CAP_DUMB_BUFFER, &cap);
2371                         if (ret || cap == 0) {
2372                                 fprintf(stderr, "driver doesn't support the dumb buffer API\n");
2373                                 return 1;
2374                         }
2375
2376                         if (set_preferred || count)
2377                                 set_mode(&dev, pipe_args, count);
2378
2379                         if (plane_count)
2380                                 set_planes(&dev, plane_args, plane_count);
2381
2382                         if (test_cursor)
2383                                 set_cursors(&dev, pipe_args, count);
2384
2385                         if (test_vsync)
2386                                 test_page_flip(&dev, pipe_args, count);
2387
2388                         if (drop_master)
2389                                 drmDropMaster(dev.fd);
2390
2391                         getchar();
2392
2393                         if (test_cursor)
2394                                 clear_cursors(&dev);
2395
2396                         if (plane_count)
2397                                 clear_planes(&dev, plane_args, plane_count);
2398
2399                         if (set_preferred || count)
2400                                 clear_mode(&dev);
2401                 }
2402         }
2403
2404         free_resources(dev.resources);
2405         drmClose(dev.fd);
2406
2407         return 0;
2408 }