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