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