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