xref: /netbsd-src/sys/external/bsd/drm2/dist/drm/drm_crtc.c (revision cef8759bd76c1b621f8eab8faa6f208faabc2e15)
1 /*	$NetBSD: drm_crtc.c,v 1.17 2020/06/27 13:39:05 jmcneill Exp $	*/
2 
3 /*
4  * Copyright (c) 2006-2008 Intel Corporation
5  * Copyright (c) 2007 Dave Airlie <airlied@linux.ie>
6  * Copyright (c) 2008 Red Hat Inc.
7  *
8  * DRM core CRTC related functions
9  *
10  * Permission to use, copy, modify, distribute, and sell this software and its
11  * documentation for any purpose is hereby granted without fee, provided that
12  * the above copyright notice appear in all copies and that both that copyright
13  * notice and this permission notice appear in supporting documentation, and
14  * that the name of the copyright holders not be used in advertising or
15  * publicity pertaining to distribution of the software without specific,
16  * written prior permission.  The copyright holders make no representations
17  * about the suitability of this software for any purpose.  It is provided "as
18  * is" without express or implied warranty.
19  *
20  * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
21  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
22  * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
23  * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
24  * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
25  * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
26  * OF THIS SOFTWARE.
27  *
28  * Authors:
29  *      Keith Packard
30  *	Eric Anholt <eric@anholt.net>
31  *      Dave Airlie <airlied@linux.ie>
32  *      Jesse Barnes <jesse.barnes@intel.com>
33  */
34 #include <sys/cdefs.h>
35 __KERNEL_RCSID(0, "$NetBSD: drm_crtc.c,v 1.17 2020/06/27 13:39:05 jmcneill Exp $");
36 
37 #include <linux/ctype.h>
38 #include <linux/list.h>
39 #include <linux/slab.h>
40 #include <linux/export.h>
41 #include <drm/drmP.h>
42 #include <drm/drm_crtc.h>
43 #include <drm/drm_edid.h>
44 #include <drm/drm_fourcc.h>
45 #include <drm/drm_modeset_lock.h>
46 #include <drm/drm_atomic.h>
47 
48 #include "drm_crtc_internal.h"
49 #include "drm_internal.h"
50 
51 #include <linux/nbsd-namespace.h>
52 
53 static struct drm_framebuffer *
54 internal_framebuffer_create(struct drm_device *dev,
55 			    struct drm_mode_fb_cmd2 *r,
56 			    struct drm_file *file_priv);
57 
58 /* Avoid boilerplate.  I'm tired of typing. */
59 #define DRM_ENUM_NAME_FN(fnname, list)				\
60 	const char *fnname(int val)				\
61 	{							\
62 		int i;						\
63 		for (i = 0; i < ARRAY_SIZE(list); i++) {	\
64 			if (list[i].type == val)		\
65 				return list[i].name;		\
66 		}						\
67 		return "(unknown)";				\
68 	}
69 
70 /*
71  * Global properties
72  */
73 static const struct drm_prop_enum_list drm_dpms_enum_list[] = {
74 	{ DRM_MODE_DPMS_ON, "On" },
75 	{ DRM_MODE_DPMS_STANDBY, "Standby" },
76 	{ DRM_MODE_DPMS_SUSPEND, "Suspend" },
77 	{ DRM_MODE_DPMS_OFF, "Off" }
78 };
79 
80 DRM_ENUM_NAME_FN(drm_get_dpms_name, drm_dpms_enum_list)
81 
82 static const struct drm_prop_enum_list drm_plane_type_enum_list[] = {
83 	{ DRM_PLANE_TYPE_OVERLAY, "Overlay" },
84 	{ DRM_PLANE_TYPE_PRIMARY, "Primary" },
85 	{ DRM_PLANE_TYPE_CURSOR, "Cursor" },
86 };
87 
88 /*
89  * Optional properties
90  */
91 static const struct drm_prop_enum_list drm_scaling_mode_enum_list[] = {
92 	{ DRM_MODE_SCALE_NONE, "None" },
93 	{ DRM_MODE_SCALE_FULLSCREEN, "Full" },
94 	{ DRM_MODE_SCALE_CENTER, "Center" },
95 	{ DRM_MODE_SCALE_ASPECT, "Full aspect" },
96 };
97 
98 static const struct drm_prop_enum_list drm_aspect_ratio_enum_list[] = {
99 	{ DRM_MODE_PICTURE_ASPECT_NONE, "Automatic" },
100 	{ DRM_MODE_PICTURE_ASPECT_4_3, "4:3" },
101 	{ DRM_MODE_PICTURE_ASPECT_16_9, "16:9" },
102 };
103 
104 /*
105  * Non-global properties, but "required" for certain connectors.
106  */
107 static const struct drm_prop_enum_list drm_dvi_i_select_enum_list[] = {
108 	{ DRM_MODE_SUBCONNECTOR_Automatic, "Automatic" }, /* DVI-I and TV-out */
109 	{ DRM_MODE_SUBCONNECTOR_DVID,      "DVI-D"     }, /* DVI-I  */
110 	{ DRM_MODE_SUBCONNECTOR_DVIA,      "DVI-A"     }, /* DVI-I  */
111 };
112 
113 DRM_ENUM_NAME_FN(drm_get_dvi_i_select_name, drm_dvi_i_select_enum_list)
114 
115 static const struct drm_prop_enum_list drm_dvi_i_subconnector_enum_list[] = {
116 	{ DRM_MODE_SUBCONNECTOR_Unknown,   "Unknown"   }, /* DVI-I and TV-out */
117 	{ DRM_MODE_SUBCONNECTOR_DVID,      "DVI-D"     }, /* DVI-I  */
118 	{ DRM_MODE_SUBCONNECTOR_DVIA,      "DVI-A"     }, /* DVI-I  */
119 };
120 
121 DRM_ENUM_NAME_FN(drm_get_dvi_i_subconnector_name,
122 		 drm_dvi_i_subconnector_enum_list)
123 
124 static const struct drm_prop_enum_list drm_tv_select_enum_list[] = {
125 	{ DRM_MODE_SUBCONNECTOR_Automatic, "Automatic" }, /* DVI-I and TV-out */
126 	{ DRM_MODE_SUBCONNECTOR_Composite, "Composite" }, /* TV-out */
127 	{ DRM_MODE_SUBCONNECTOR_SVIDEO,    "SVIDEO"    }, /* TV-out */
128 	{ DRM_MODE_SUBCONNECTOR_Component, "Component" }, /* TV-out */
129 	{ DRM_MODE_SUBCONNECTOR_SCART,     "SCART"     }, /* TV-out */
130 };
131 
132 DRM_ENUM_NAME_FN(drm_get_tv_select_name, drm_tv_select_enum_list)
133 
134 static const struct drm_prop_enum_list drm_tv_subconnector_enum_list[] = {
135 	{ DRM_MODE_SUBCONNECTOR_Unknown,   "Unknown"   }, /* DVI-I and TV-out */
136 	{ DRM_MODE_SUBCONNECTOR_Composite, "Composite" }, /* TV-out */
137 	{ DRM_MODE_SUBCONNECTOR_SVIDEO,    "SVIDEO"    }, /* TV-out */
138 	{ DRM_MODE_SUBCONNECTOR_Component, "Component" }, /* TV-out */
139 	{ DRM_MODE_SUBCONNECTOR_SCART,     "SCART"     }, /* TV-out */
140 };
141 
142 DRM_ENUM_NAME_FN(drm_get_tv_subconnector_name,
143 		 drm_tv_subconnector_enum_list)
144 
145 static const struct drm_prop_enum_list drm_dirty_info_enum_list[] = {
146 	{ DRM_MODE_DIRTY_OFF,      "Off"      },
147 	{ DRM_MODE_DIRTY_ON,       "On"       },
148 	{ DRM_MODE_DIRTY_ANNOTATE, "Annotate" },
149 };
150 
151 struct drm_conn_prop_enum_list {
152 	int type;
153 	const char *name;
154 	struct ida ida;
155 };
156 
157 /*
158  * Connector and encoder types.
159  */
160 static struct drm_conn_prop_enum_list drm_connector_enum_list[] = {
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, "SVIDEO" },
168 	{ DRM_MODE_CONNECTOR_LVDS, "LVDS" },
169 	{ DRM_MODE_CONNECTOR_Component, "Component" },
170 	{ DRM_MODE_CONNECTOR_9PinDIN, "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 
180 static const struct drm_prop_enum_list drm_encoder_enum_list[] = {
181 	{ DRM_MODE_ENCODER_NONE, "None" },
182 	{ DRM_MODE_ENCODER_DAC, "DAC" },
183 	{ DRM_MODE_ENCODER_TMDS, "TMDS" },
184 	{ DRM_MODE_ENCODER_LVDS, "LVDS" },
185 	{ DRM_MODE_ENCODER_TVDAC, "TV" },
186 	{ DRM_MODE_ENCODER_VIRTUAL, "Virtual" },
187 	{ DRM_MODE_ENCODER_DSI, "DSI" },
188 	{ DRM_MODE_ENCODER_DPMST, "DP MST" },
189 };
190 
191 static const struct drm_prop_enum_list drm_subpixel_enum_list[] = {
192 	{ SubPixelUnknown, "Unknown" },
193 	{ SubPixelHorizontalRGB, "Horizontal RGB" },
194 	{ SubPixelHorizontalBGR, "Horizontal BGR" },
195 	{ SubPixelVerticalRGB, "Vertical RGB" },
196 	{ SubPixelVerticalBGR, "Vertical BGR" },
197 	{ SubPixelNone, "None" },
198 };
199 
200 void drm_connector_ida_init(void)
201 {
202 	int i;
203 
204 	for (i = 0; i < ARRAY_SIZE(drm_connector_enum_list); i++)
205 		ida_init(&drm_connector_enum_list[i].ida);
206 }
207 
208 void drm_connector_ida_destroy(void)
209 {
210 	int i;
211 
212 	for (i = 0; i < ARRAY_SIZE(drm_connector_enum_list); i++)
213 		ida_destroy(&drm_connector_enum_list[i].ida);
214 }
215 
216 /**
217  * drm_get_connector_status_name - return a string for connector status
218  * @status: connector status to compute name of
219  *
220  * In contrast to the other drm_get_*_name functions this one here returns a
221  * const pointer and hence is threadsafe.
222  */
223 const char *drm_get_connector_status_name(enum drm_connector_status status)
224 {
225 	if (status == connector_status_connected)
226 		return "connected";
227 	else if (status == connector_status_disconnected)
228 		return "disconnected";
229 	else
230 		return "unknown";
231 }
232 EXPORT_SYMBOL(drm_get_connector_status_name);
233 
234 /**
235  * drm_get_subpixel_order_name - return a string for a given subpixel enum
236  * @order: enum of subpixel_order
237  *
238  * Note you could abuse this and return something out of bounds, but that
239  * would be a caller error.  No unscrubbed user data should make it here.
240  */
241 const char *drm_get_subpixel_order_name(enum subpixel_order order)
242 {
243 	return drm_subpixel_enum_list[order].name;
244 }
245 EXPORT_SYMBOL(drm_get_subpixel_order_name);
246 
247 static char printable_char(int c)
248 {
249 	return isascii(c) && isprint(c) ? c : '?';
250 }
251 
252 /**
253  * drm_get_format_name - return a string for drm fourcc format
254  * @format: format to compute name of
255  *
256  * Note that the buffer used by this function is globally shared and owned by
257  * the function itself.
258  *
259  * FIXME: This isn't really multithreading safe.
260  */
261 const char *drm_get_format_name(uint32_t format)
262 {
263 	static char buf[32];
264 
265 	snprintf(buf, sizeof(buf),
266 		 "%c%c%c%c %s-endian (0x%08x)",
267 		 printable_char(format & 0xff),
268 		 printable_char((format >> 8) & 0xff),
269 		 printable_char((format >> 16) & 0xff),
270 		 printable_char((format >> 24) & 0x7f),
271 		 format & DRM_FORMAT_BIG_ENDIAN ? "big" : "little",
272 		 format);
273 
274 	return buf;
275 }
276 EXPORT_SYMBOL(drm_get_format_name);
277 
278 /*
279  * Internal function to assign a slot in the object idr and optionally
280  * register the object into the idr.
281  */
282 static int drm_mode_object_get_reg(struct drm_device *dev,
283 				   struct drm_mode_object *obj,
284 				   uint32_t obj_type,
285 				   bool register_obj)
286 {
287 	int ret;
288 
289 	idr_preload(GFP_KERNEL);
290 	mutex_lock(&dev->mode_config.idr_mutex);
291 	ret = idr_alloc(&dev->mode_config.crtc_idr, register_obj ? obj : NULL, 1, 0, GFP_KERNEL);
292 	if (ret >= 0) {
293 		/*
294 		 * Set up the object linking under the protection of the idr
295 		 * lock so that other users can't see inconsistent state.
296 		 */
297 		obj->id = ret;
298 		obj->type = obj_type;
299 	}
300 	mutex_unlock(&dev->mode_config.idr_mutex);
301 	idr_preload_end();
302 
303 	return ret < 0 ? ret : 0;
304 }
305 
306 /**
307  * drm_mode_object_get - allocate a new modeset identifier
308  * @dev: DRM device
309  * @obj: object pointer, used to generate unique ID
310  * @obj_type: object type
311  *
312  * Create a unique identifier based on @ptr in @dev's identifier space.  Used
313  * for tracking modes, CRTCs and connectors. Note that despite the _get postfix
314  * modeset identifiers are _not_ reference counted. Hence don't use this for
315  * reference counted modeset objects like framebuffers.
316  *
317  * Returns:
318  * Zero on success, error code on failure.
319  */
320 int drm_mode_object_get(struct drm_device *dev,
321 			struct drm_mode_object *obj, uint32_t obj_type)
322 {
323 	return drm_mode_object_get_reg(dev, obj, obj_type, true);
324 }
325 
326 static void drm_mode_object_register(struct drm_device *dev,
327 				     struct drm_mode_object *obj)
328 {
329 	mutex_lock(&dev->mode_config.idr_mutex);
330 	idr_replace(&dev->mode_config.crtc_idr, obj, obj->id);
331 	mutex_unlock(&dev->mode_config.idr_mutex);
332 }
333 
334 /**
335  * drm_mode_object_put - free a modeset identifer
336  * @dev: DRM device
337  * @object: object to free
338  *
339  * Free @id from @dev's unique identifier pool. Note that despite the _get
340  * postfix modeset identifiers are _not_ reference counted. Hence don't use this
341  * for reference counted modeset objects like framebuffers.
342  */
343 void drm_mode_object_put(struct drm_device *dev,
344 			 struct drm_mode_object *object)
345 {
346 	mutex_lock(&dev->mode_config.idr_mutex);
347 	idr_remove(&dev->mode_config.crtc_idr, object->id);
348 	mutex_unlock(&dev->mode_config.idr_mutex);
349 }
350 
351 static struct drm_mode_object *_object_find(struct drm_device *dev,
352 		uint32_t id, uint32_t type)
353 {
354 	struct drm_mode_object *obj = NULL;
355 
356 	mutex_lock(&dev->mode_config.idr_mutex);
357 	obj = idr_find(&dev->mode_config.crtc_idr, id);
358 	if (obj && type != DRM_MODE_OBJECT_ANY && obj->type != type)
359 		obj = NULL;
360 	if (obj && obj->id != id)
361 		obj = NULL;
362 	/* don't leak out unref'd fb's */
363 	if (obj &&
364 	    (obj->type == DRM_MODE_OBJECT_FB ||
365 	     obj->type == DRM_MODE_OBJECT_BLOB))
366 		obj = NULL;
367 	mutex_unlock(&dev->mode_config.idr_mutex);
368 
369 	return obj;
370 }
371 
372 /**
373  * drm_mode_object_find - look up a drm object with static lifetime
374  * @dev: drm device
375  * @id: id of the mode object
376  * @type: type of the mode object
377  *
378  * Note that framebuffers cannot be looked up with this functions - since those
379  * are reference counted, they need special treatment.  Even with
380  * DRM_MODE_OBJECT_ANY (although that will simply return NULL
381  * rather than WARN_ON()).
382  */
383 struct drm_mode_object *drm_mode_object_find(struct drm_device *dev,
384 		uint32_t id, uint32_t type)
385 {
386 	struct drm_mode_object *obj = NULL;
387 
388 	/* Framebuffers are reference counted and need their own lookup
389 	 * function.*/
390 	WARN_ON(type == DRM_MODE_OBJECT_FB || type == DRM_MODE_OBJECT_BLOB);
391 	obj = _object_find(dev, id, type);
392 	return obj;
393 }
394 EXPORT_SYMBOL(drm_mode_object_find);
395 
396 /**
397  * drm_framebuffer_init - initialize a framebuffer
398  * @dev: DRM device
399  * @fb: framebuffer to be initialized
400  * @funcs: ... with these functions
401  *
402  * Allocates an ID for the framebuffer's parent mode object, sets its mode
403  * functions & device file and adds it to the master fd list.
404  *
405  * IMPORTANT:
406  * This functions publishes the fb and makes it available for concurrent access
407  * by other users. Which means by this point the fb _must_ be fully set up -
408  * since all the fb attributes are invariant over its lifetime, no further
409  * locking but only correct reference counting is required.
410  *
411  * Returns:
412  * Zero on success, error code on failure.
413  */
414 int drm_framebuffer_init(struct drm_device *dev, struct drm_framebuffer *fb,
415 			 const struct drm_framebuffer_funcs *funcs)
416 {
417 	int ret;
418 
419 	mutex_lock(&dev->mode_config.fb_lock);
420 	kref_init(&fb->refcount);
421 	INIT_LIST_HEAD(&fb->filp_head);
422 	fb->dev = dev;
423 	fb->funcs = funcs;
424 
425 	ret = drm_mode_object_get(dev, &fb->base, DRM_MODE_OBJECT_FB);
426 	if (ret)
427 		goto out;
428 
429 	dev->mode_config.num_fb++;
430 	list_add(&fb->head, &dev->mode_config.fb_list);
431 out:
432 	mutex_unlock(&dev->mode_config.fb_lock);
433 
434 	return ret;
435 }
436 EXPORT_SYMBOL(drm_framebuffer_init);
437 
438 /* dev->mode_config.fb_lock must be held! */
439 static void __drm_framebuffer_unregister(struct drm_device *dev,
440 					 struct drm_framebuffer *fb)
441 {
442 	mutex_lock(&dev->mode_config.idr_mutex);
443 	idr_remove(&dev->mode_config.crtc_idr, fb->base.id);
444 	mutex_unlock(&dev->mode_config.idr_mutex);
445 
446 	fb->base.id = 0;
447 }
448 
449 static void drm_framebuffer_free(struct kref *kref)
450 {
451 	struct drm_framebuffer *fb =
452 			container_of(kref, struct drm_framebuffer, refcount);
453 	struct drm_device *dev = fb->dev;
454 
455 	/*
456 	 * The lookup idr holds a weak reference, which has not necessarily been
457 	 * removed at this point. Check for that.
458 	 */
459 	mutex_lock(&dev->mode_config.fb_lock);
460 	if (fb->base.id) {
461 		/* Mark fb as reaped and drop idr ref. */
462 		__drm_framebuffer_unregister(dev, fb);
463 	}
464 	mutex_unlock(&dev->mode_config.fb_lock);
465 
466 	fb->funcs->destroy(fb);
467 }
468 
469 static struct drm_framebuffer *__drm_framebuffer_lookup(struct drm_device *dev,
470 							uint32_t id)
471 {
472 	struct drm_mode_object *obj = NULL;
473 	struct drm_framebuffer *fb;
474 
475 	mutex_lock(&dev->mode_config.idr_mutex);
476 	obj = idr_find(&dev->mode_config.crtc_idr, id);
477 	if (!obj || (obj->type != DRM_MODE_OBJECT_FB) || (obj->id != id))
478 		fb = NULL;
479 	else
480 		fb = obj_to_fb(obj);
481 	mutex_unlock(&dev->mode_config.idr_mutex);
482 
483 	return fb;
484 }
485 
486 /**
487  * drm_framebuffer_lookup - look up a drm framebuffer and grab a reference
488  * @dev: drm device
489  * @id: id of the fb object
490  *
491  * If successful, this grabs an additional reference to the framebuffer -
492  * callers need to make sure to eventually unreference the returned framebuffer
493  * again, using @drm_framebuffer_unreference.
494  */
495 struct drm_framebuffer *drm_framebuffer_lookup(struct drm_device *dev,
496 					       uint32_t id)
497 {
498 	struct drm_framebuffer *fb;
499 
500 	mutex_lock(&dev->mode_config.fb_lock);
501 	fb = __drm_framebuffer_lookup(dev, id);
502 	if (fb) {
503 		if (!kref_get_unless_zero(&fb->refcount))
504 			fb = NULL;
505 	}
506 	mutex_unlock(&dev->mode_config.fb_lock);
507 
508 	return fb;
509 }
510 EXPORT_SYMBOL(drm_framebuffer_lookup);
511 
512 /**
513  * drm_framebuffer_unreference - unref a framebuffer
514  * @fb: framebuffer to unref
515  *
516  * This functions decrements the fb's refcount and frees it if it drops to zero.
517  */
518 void drm_framebuffer_unreference(struct drm_framebuffer *fb)
519 {
520 	DRM_DEBUG("%p: FB ID: %d (%d)\n", fb, fb->base.id, fb->refcount.kr_count);
521 	kref_put(&fb->refcount, drm_framebuffer_free);
522 }
523 EXPORT_SYMBOL(drm_framebuffer_unreference);
524 
525 /**
526  * drm_framebuffer_reference - incr the fb refcnt
527  * @fb: framebuffer
528  *
529  * This functions increments the fb's refcount.
530  */
531 void drm_framebuffer_reference(struct drm_framebuffer *fb)
532 {
533 	DRM_DEBUG("%p: FB ID: %d (%d)\n", fb, fb->base.id, fb->refcount.kr_count);
534 	kref_get(&fb->refcount);
535 }
536 EXPORT_SYMBOL(drm_framebuffer_reference);
537 
538 /**
539  * drm_framebuffer_unregister_private - unregister a private fb from the lookup idr
540  * @fb: fb to unregister
541  *
542  * Drivers need to call this when cleaning up driver-private framebuffers, e.g.
543  * those used for fbdev. Note that the caller must hold a reference of it's own,
544  * i.e. the object may not be destroyed through this call (since it'll lead to a
545  * locking inversion).
546  */
547 void drm_framebuffer_unregister_private(struct drm_framebuffer *fb)
548 {
549 	struct drm_device *dev;
550 
551 	if (!fb)
552 		return;
553 
554 	dev = fb->dev;
555 
556 	mutex_lock(&dev->mode_config.fb_lock);
557 	/* Mark fb as reaped and drop idr ref. */
558 	__drm_framebuffer_unregister(dev, fb);
559 	mutex_unlock(&dev->mode_config.fb_lock);
560 }
561 EXPORT_SYMBOL(drm_framebuffer_unregister_private);
562 
563 /**
564  * drm_framebuffer_cleanup - remove a framebuffer object
565  * @fb: framebuffer to remove
566  *
567  * Cleanup framebuffer. This function is intended to be used from the drivers
568  * ->destroy callback. It can also be used to clean up driver private
569  *  framebuffers embedded into a larger structure.
570  *
571  * Note that this function does not remove the fb from active usuage - if it is
572  * still used anywhere, hilarity can ensue since userspace could call getfb on
573  * the id and get back -EINVAL. Obviously no concern at driver unload time.
574  *
575  * Also, the framebuffer will not be removed from the lookup idr - for
576  * user-created framebuffers this will happen in in the rmfb ioctl. For
577  * driver-private objects (e.g. for fbdev) drivers need to explicitly call
578  * drm_framebuffer_unregister_private.
579  */
580 void drm_framebuffer_cleanup(struct drm_framebuffer *fb)
581 {
582 	struct drm_device *dev = fb->dev;
583 
584 	mutex_lock(&dev->mode_config.fb_lock);
585 	list_del(&fb->head);
586 	dev->mode_config.num_fb--;
587 	mutex_unlock(&dev->mode_config.fb_lock);
588 }
589 EXPORT_SYMBOL(drm_framebuffer_cleanup);
590 
591 /**
592  * drm_framebuffer_remove - remove and unreference a framebuffer object
593  * @fb: framebuffer to remove
594  *
595  * Scans all the CRTCs and planes in @dev's mode_config.  If they're
596  * using @fb, removes it, setting it to NULL. Then drops the reference to the
597  * passed-in framebuffer. Might take the modeset locks.
598  *
599  * Note that this function optimizes the cleanup away if the caller holds the
600  * last reference to the framebuffer. It is also guaranteed to not take the
601  * modeset locks in this case.
602  */
603 void drm_framebuffer_remove(struct drm_framebuffer *fb)
604 {
605 	struct drm_device *dev;
606 	struct drm_crtc *crtc;
607 	struct drm_plane *plane;
608 	struct drm_mode_set set;
609 	int ret;
610 
611 	if (!fb)
612 		return;
613 
614 	dev = fb->dev;
615 
616 	WARN_ON(!list_empty(&fb->filp_head));
617 
618 	/*
619 	 * drm ABI mandates that we remove any deleted framebuffers from active
620 	 * useage. But since most sane clients only remove framebuffers they no
621 	 * longer need, try to optimize this away.
622 	 *
623 	 * Since we're holding a reference ourselves, observing a refcount of 1
624 	 * means that we're the last holder and can skip it. Also, the refcount
625 	 * can never increase from 1 again, so we don't need any barriers or
626 	 * locks.
627 	 *
628 	 * Note that userspace could try to race with use and instate a new
629 	 * usage _after_ we've cleared all current ones. End result will be an
630 	 * in-use fb with fb-id == 0. Userspace is allowed to shoot its own foot
631 	 * in this manner.
632 	 */
633 	if (!kref_exclusive_p(&fb->refcount)) {
634 		drm_modeset_lock_all(dev);
635 		/* remove from any CRTC */
636 		drm_for_each_crtc(crtc, dev) {
637 			if (crtc->primary->fb == fb) {
638 				/* should turn off the crtc */
639 				memset(&set, 0, sizeof(struct drm_mode_set));
640 				set.crtc = crtc;
641 				set.fb = NULL;
642 				ret = drm_mode_set_config_internal(&set);
643 				if (ret)
644 					DRM_ERROR("failed to reset crtc %p when fb was deleted\n", crtc);
645 			}
646 		}
647 
648 		drm_for_each_plane(plane, dev) {
649 			if (plane->fb == fb)
650 				drm_plane_force_disable(plane);
651 		}
652 		drm_modeset_unlock_all(dev);
653 	}
654 
655 	drm_framebuffer_unreference(fb);
656 }
657 EXPORT_SYMBOL(drm_framebuffer_remove);
658 
659 DEFINE_WW_CLASS(crtc_ww_class);
660 
661 /**
662  * drm_crtc_init_with_planes - Initialise a new CRTC object with
663  *    specified primary and cursor planes.
664  * @dev: DRM device
665  * @crtc: CRTC object to init
666  * @primary: Primary plane for CRTC
667  * @cursor: Cursor plane for CRTC
668  * @funcs: callbacks for the new CRTC
669  *
670  * Inits a new object created as base part of a driver crtc object.
671  *
672  * Returns:
673  * Zero on success, error code on failure.
674  */
675 int drm_crtc_init_with_planes(struct drm_device *dev, struct drm_crtc *crtc,
676 			      struct drm_plane *primary,
677 			      struct drm_plane *cursor,
678 			      const struct drm_crtc_funcs *funcs)
679 {
680 	struct drm_mode_config *config = &dev->mode_config;
681 	int ret;
682 
683 	WARN_ON(primary && primary->type != DRM_PLANE_TYPE_PRIMARY);
684 	WARN_ON(cursor && cursor->type != DRM_PLANE_TYPE_CURSOR);
685 
686 	crtc->dev = dev;
687 	crtc->funcs = funcs;
688 
689 	drm_modeset_lock_init(&crtc->mutex);
690 	ret = drm_mode_object_get(dev, &crtc->base, DRM_MODE_OBJECT_CRTC);
691 	if (ret)
692 		return ret;
693 
694 	crtc->base.properties = &crtc->properties;
695 
696 	list_add_tail(&crtc->head, &config->crtc_list);
697 	config->num_crtc++;
698 
699 	crtc->primary = primary;
700 	crtc->cursor = cursor;
701 	if (primary)
702 		primary->possible_crtcs = 1 << drm_crtc_index(crtc);
703 	if (cursor)
704 		cursor->possible_crtcs = 1 << drm_crtc_index(crtc);
705 
706 	if (drm_core_check_feature(dev, DRIVER_ATOMIC)) {
707 		drm_object_attach_property(&crtc->base, config->prop_active, 0);
708 		drm_object_attach_property(&crtc->base, config->prop_mode_id, 0);
709 	}
710 
711 	return 0;
712 }
713 EXPORT_SYMBOL(drm_crtc_init_with_planes);
714 
715 /**
716  * drm_crtc_cleanup - Clean up the core crtc usage
717  * @crtc: CRTC to cleanup
718  *
719  * This function cleans up @crtc and removes it from the DRM mode setting
720  * core. Note that the function does *not* free the crtc structure itself,
721  * this is the responsibility of the caller.
722  */
723 void drm_crtc_cleanup(struct drm_crtc *crtc)
724 {
725 	struct drm_device *dev = crtc->dev;
726 
727 	kfree(crtc->gamma_store);
728 	crtc->gamma_store = NULL;
729 
730 	drm_modeset_lock_fini(&crtc->mutex);
731 
732 	drm_mode_object_put(dev, &crtc->base);
733 	list_del(&crtc->head);
734 	dev->mode_config.num_crtc--;
735 
736 	WARN_ON(crtc->state && !crtc->funcs->atomic_destroy_state);
737 	if (crtc->state && crtc->funcs->atomic_destroy_state)
738 		crtc->funcs->atomic_destroy_state(crtc, crtc->state);
739 
740 	memset(crtc, 0, sizeof(*crtc));
741 }
742 EXPORT_SYMBOL(drm_crtc_cleanup);
743 
744 /**
745  * drm_crtc_index - find the index of a registered CRTC
746  * @crtc: CRTC to find index for
747  *
748  * Given a registered CRTC, return the index of that CRTC within a DRM
749  * device's list of CRTCs.
750  */
751 unsigned int drm_crtc_index(struct drm_crtc *crtc)
752 {
753 	unsigned int index = 0;
754 	struct drm_crtc *tmp;
755 
756 	drm_for_each_crtc(tmp, crtc->dev) {
757 		if (tmp == crtc)
758 			return index;
759 
760 		index++;
761 	}
762 
763 	BUG();
764 }
765 EXPORT_SYMBOL(drm_crtc_index);
766 
767 /*
768  * drm_mode_remove - remove and free a mode
769  * @connector: connector list to modify
770  * @mode: mode to remove
771  *
772  * Remove @mode from @connector's mode list, then free it.
773  */
774 static void drm_mode_remove(struct drm_connector *connector,
775 			    struct drm_display_mode *mode)
776 {
777 	list_del(&mode->head);
778 	drm_mode_destroy(connector->dev, mode);
779 }
780 
781 /**
782  * drm_display_info_set_bus_formats - set the supported bus formats
783  * @info: display info to store bus formats in
784  * @formats: array containing the supported bus formats
785  * @num_formats: the number of entries in the fmts array
786  *
787  * Store the supported bus formats in display info structure.
788  * See MEDIA_BUS_FMT_* definitions in include/uapi/linux/media-bus-format.h for
789  * a full list of available formats.
790  */
791 int drm_display_info_set_bus_formats(struct drm_display_info *info,
792 				     const u32 *formats,
793 				     unsigned int num_formats)
794 {
795 	u32 *fmts = NULL;
796 
797 	if (!formats && num_formats)
798 		return -EINVAL;
799 
800 	if (formats && num_formats) {
801 		fmts = kmemdup(formats, sizeof(*formats) * num_formats,
802 			       GFP_KERNEL);
803 		if (!fmts)
804 			return -ENOMEM;
805 	}
806 
807 	kfree(info->bus_formats);
808 	info->bus_formats = fmts;
809 	info->num_bus_formats = num_formats;
810 
811 	return 0;
812 }
813 EXPORT_SYMBOL(drm_display_info_set_bus_formats);
814 
815 /**
816  * drm_connector_get_cmdline_mode - reads the user's cmdline mode
817  * @connector: connector to quwery
818  *
819  * The kernel supports per-connector configration of its consoles through
820  * use of the video= parameter. This function parses that option and
821  * extracts the user's specified mode (or enable/disable status) for a
822  * particular connector. This is typically only used during the early fbdev
823  * setup.
824  */
825 static void drm_connector_get_cmdline_mode(struct drm_connector *connector)
826 {
827 	struct drm_cmdline_mode *mode = &connector->cmdline_mode;
828 
829 #ifdef __NetBSD__
830 	const char *option;
831 	prop_dictionary_t prop = device_properties(connector->dev->dev);
832 	if (!prop_dictionary_get_string(prop, connector->name, &option))
833 		return;
834 #else
835 	char *option = NULL;
836 	if (fb_get_options(connector->name, &option))
837 		return;
838 #endif
839 
840 	if (!drm_mode_parse_command_line_for_connector(option,
841 						       connector,
842 						       mode))
843 		return;
844 
845 	if (mode->force) {
846 		const char *s;
847 
848 		switch (mode->force) {
849 		case DRM_FORCE_OFF:
850 			s = "OFF";
851 			break;
852 		case DRM_FORCE_ON_DIGITAL:
853 			s = "ON - dig";
854 			break;
855 		default:
856 		case DRM_FORCE_ON:
857 			s = "ON";
858 			break;
859 		}
860 
861 		DRM_INFO("forcing %s connector %s\n", connector->name, s);
862 		connector->force = mode->force;
863 	}
864 
865 	DRM_DEBUG_KMS("cmdline mode for connector %s %dx%d@%dHz%s%s%s\n",
866 		      connector->name,
867 		      mode->xres, mode->yres,
868 		      mode->refresh_specified ? mode->refresh : 60,
869 		      mode->rb ? " reduced blanking" : "",
870 		      mode->margins ? " with margins" : "",
871 		      mode->interlace ?  " interlaced" : "");
872 }
873 
874 /**
875  * drm_connector_init - Init a preallocated connector
876  * @dev: DRM device
877  * @connector: the connector to init
878  * @funcs: callbacks for this connector
879  * @connector_type: user visible type of the connector
880  *
881  * Initialises a preallocated connector. Connectors should be
882  * subclassed as part of driver connector objects.
883  *
884  * Returns:
885  * Zero on success, error code on failure.
886  */
887 int drm_connector_init(struct drm_device *dev,
888 		       struct drm_connector *connector,
889 		       const struct drm_connector_funcs *funcs,
890 		       int connector_type)
891 {
892 	struct drm_mode_config *config = &dev->mode_config;
893 	int ret;
894 	struct ida *connector_ida =
895 		&drm_connector_enum_list[connector_type].ida;
896 
897 	drm_modeset_lock_all(dev);
898 
899 	ret = drm_mode_object_get_reg(dev, &connector->base, DRM_MODE_OBJECT_CONNECTOR, false);
900 	if (ret)
901 		goto out_unlock;
902 
903 	connector->base.properties = &connector->properties;
904 	connector->dev = dev;
905 	connector->kdev = dev->dev;
906 	connector->funcs = funcs;
907 	connector->connector_type = connector_type;
908 	connector->connector_type_id =
909 		ida_simple_get(connector_ida, 1, 0, GFP_KERNEL);
910 	if (connector->connector_type_id < 0) {
911 		ret = connector->connector_type_id;
912 		goto out_put;
913 	}
914 	connector->name =
915 		kasprintf(GFP_KERNEL, "%s-%d",
916 			  drm_connector_enum_list[connector_type].name,
917 			  connector->connector_type_id);
918 	if (!connector->name) {
919 		ret = -ENOMEM;
920 		goto out_put;
921 	}
922 
923 	INIT_LIST_HEAD(&connector->probed_modes);
924 	INIT_LIST_HEAD(&connector->modes);
925 	connector->edid_blob_ptr = NULL;
926 	connector->status = connector_status_unknown;
927 
928 	drm_connector_get_cmdline_mode(connector);
929 
930 	/* We should add connectors at the end to avoid upsetting the connector
931 	 * index too much. */
932 	list_add_tail(&connector->head, &config->connector_list);
933 	config->num_connector++;
934 
935 	if (connector_type != DRM_MODE_CONNECTOR_VIRTUAL)
936 		drm_object_attach_property(&connector->base,
937 					      config->edid_property,
938 					      0);
939 
940 	drm_object_attach_property(&connector->base,
941 				      config->dpms_property, 0);
942 
943 	if (drm_core_check_feature(dev, DRIVER_ATOMIC)) {
944 		drm_object_attach_property(&connector->base, config->prop_crtc_id, 0);
945 	}
946 
947 	connector->debugfs_entry = NULL;
948 
949 out_put:
950 	if (ret)
951 		drm_mode_object_put(dev, &connector->base);
952 
953 out_unlock:
954 	drm_modeset_unlock_all(dev);
955 
956 	return ret;
957 }
958 EXPORT_SYMBOL(drm_connector_init);
959 
960 /**
961  * drm_connector_cleanup - cleans up an initialised connector
962  * @connector: connector to cleanup
963  *
964  * Cleans up the connector but doesn't free the object.
965  */
966 void drm_connector_cleanup(struct drm_connector *connector)
967 {
968 	struct drm_device *dev = connector->dev;
969 	struct drm_display_mode *mode, *t;
970 
971 	if (connector->tile_group) {
972 		drm_mode_put_tile_group(dev, connector->tile_group);
973 		connector->tile_group = NULL;
974 	}
975 
976 	list_for_each_entry_safe(mode, t, &connector->probed_modes, head)
977 		drm_mode_remove(connector, mode);
978 
979 	list_for_each_entry_safe(mode, t, &connector->modes, head)
980 		drm_mode_remove(connector, mode);
981 
982 	ida_remove(&drm_connector_enum_list[connector->connector_type].ida,
983 		   connector->connector_type_id);
984 
985 	kfree(connector->display_info.bus_formats);
986 	drm_mode_object_put(dev, &connector->base);
987 	kfree(connector->name);
988 	connector->name = NULL;
989 	list_del(&connector->head);
990 	dev->mode_config.num_connector--;
991 
992 	WARN_ON(connector->state && !connector->funcs->atomic_destroy_state);
993 	if (connector->state && connector->funcs->atomic_destroy_state)
994 		connector->funcs->atomic_destroy_state(connector,
995 						       connector->state);
996 
997 	memset(connector, 0, sizeof(*connector));
998 }
999 EXPORT_SYMBOL(drm_connector_cleanup);
1000 
1001 /**
1002  * drm_connector_index - find the index of a registered connector
1003  * @connector: connector to find index for
1004  *
1005  * Given a registered connector, return the index of that connector within a DRM
1006  * device's list of connectors.
1007  */
1008 unsigned int drm_connector_index(struct drm_connector *connector)
1009 {
1010 	unsigned int index = 0;
1011 	struct drm_connector *tmp;
1012 	struct drm_mode_config *config = &connector->dev->mode_config;
1013 
1014 	WARN_ON(!drm_modeset_is_locked(&config->connection_mutex));
1015 
1016 	drm_for_each_connector(tmp, connector->dev) {
1017 		if (tmp == connector)
1018 			return index;
1019 
1020 		index++;
1021 	}
1022 
1023 	BUG();
1024 }
1025 EXPORT_SYMBOL(drm_connector_index);
1026 
1027 /**
1028  * drm_connector_register - register a connector
1029  * @connector: the connector to register
1030  *
1031  * Register userspace interfaces for a connector
1032  *
1033  * Returns:
1034  * Zero on success, error code on failure.
1035  */
1036 int drm_connector_register(struct drm_connector *connector)
1037 {
1038 #ifndef __NetBSD__		/* XXX sysfs, debugfs */
1039 	int ret;
1040 #endif
1041 
1042 	drm_mode_object_register(connector->dev, &connector->base);
1043 
1044 #ifndef __NetBSD__		/* XXX sysfs, debugfs */
1045 	ret = drm_sysfs_connector_add(connector);
1046 	if (ret)
1047 		return ret;
1048 
1049 	ret = drm_debugfs_connector_add(connector);
1050 	if (ret) {
1051 		drm_sysfs_connector_remove(connector);
1052 		return ret;
1053 	}
1054 #endif
1055 
1056 	return 0;
1057 }
1058 EXPORT_SYMBOL(drm_connector_register);
1059 
1060 /**
1061  * drm_connector_unregister - unregister a connector
1062  * @connector: the connector to unregister
1063  *
1064  * Unregister userspace interfaces for a connector
1065  */
1066 void drm_connector_unregister(struct drm_connector *connector)
1067 {
1068 #ifndef __NetBSD__		/* XXX sysfs, debugfs */
1069 	drm_sysfs_connector_remove(connector);
1070 	drm_debugfs_connector_remove(connector);
1071 #endif
1072 }
1073 EXPORT_SYMBOL(drm_connector_unregister);
1074 
1075 
1076 /**
1077  * drm_connector_unplug_all - unregister connector userspace interfaces
1078  * @dev: drm device
1079  *
1080  * This function unregisters all connector userspace interfaces in sysfs. Should
1081  * be call when the device is disconnected, e.g. from an usb driver's
1082  * ->disconnect callback.
1083  */
1084 void drm_connector_unplug_all(struct drm_device *dev)
1085 {
1086 	struct drm_connector *connector;
1087 
1088 	/* FIXME: taking the mode config mutex ends up in a clash with sysfs */
1089 	list_for_each_entry(connector, &dev->mode_config.connector_list, head)
1090 		drm_connector_unregister(connector);
1091 
1092 }
1093 EXPORT_SYMBOL(drm_connector_unplug_all);
1094 
1095 /**
1096  * drm_encoder_init - Init a preallocated encoder
1097  * @dev: drm device
1098  * @encoder: the encoder to init
1099  * @funcs: callbacks for this encoder
1100  * @encoder_type: user visible type of the encoder
1101  *
1102  * Initialises a preallocated encoder. Encoder should be
1103  * subclassed as part of driver encoder objects.
1104  *
1105  * Returns:
1106  * Zero on success, error code on failure.
1107  */
1108 int drm_encoder_init(struct drm_device *dev,
1109 		      struct drm_encoder *encoder,
1110 		      const struct drm_encoder_funcs *funcs,
1111 		      int encoder_type)
1112 {
1113 	int ret;
1114 
1115 	drm_modeset_lock_all(dev);
1116 
1117 	ret = drm_mode_object_get(dev, &encoder->base, DRM_MODE_OBJECT_ENCODER);
1118 	if (ret)
1119 		goto out_unlock;
1120 
1121 	encoder->dev = dev;
1122 	encoder->encoder_type = encoder_type;
1123 	encoder->funcs = funcs;
1124 	encoder->name = kasprintf(GFP_KERNEL, "%s-%d",
1125 				  drm_encoder_enum_list[encoder_type].name,
1126 				  encoder->base.id);
1127 	if (!encoder->name) {
1128 		ret = -ENOMEM;
1129 		goto out_put;
1130 	}
1131 
1132 	list_add_tail(&encoder->head, &dev->mode_config.encoder_list);
1133 	dev->mode_config.num_encoder++;
1134 
1135 out_put:
1136 	if (ret)
1137 		drm_mode_object_put(dev, &encoder->base);
1138 
1139 out_unlock:
1140 	drm_modeset_unlock_all(dev);
1141 
1142 	return ret;
1143 }
1144 EXPORT_SYMBOL(drm_encoder_init);
1145 
1146 /**
1147  * drm_encoder_cleanup - cleans up an initialised encoder
1148  * @encoder: encoder to cleanup
1149  *
1150  * Cleans up the encoder but doesn't free the object.
1151  */
1152 void drm_encoder_cleanup(struct drm_encoder *encoder)
1153 {
1154 	struct drm_device *dev = encoder->dev;
1155 
1156 	drm_modeset_lock_all(dev);
1157 	drm_mode_object_put(dev, &encoder->base);
1158 	kfree(encoder->name);
1159 	list_del(&encoder->head);
1160 	dev->mode_config.num_encoder--;
1161 	drm_modeset_unlock_all(dev);
1162 
1163 	memset(encoder, 0, sizeof(*encoder));
1164 }
1165 EXPORT_SYMBOL(drm_encoder_cleanup);
1166 
1167 /**
1168  * drm_universal_plane_init - Initialize a new universal plane object
1169  * @dev: DRM device
1170  * @plane: plane object to init
1171  * @possible_crtcs: bitmask of possible CRTCs
1172  * @funcs: callbacks for the new plane
1173  * @formats: array of supported formats (%DRM_FORMAT_*)
1174  * @format_count: number of elements in @formats
1175  * @type: type of plane (overlay, primary, cursor)
1176  *
1177  * Initializes a plane object of type @type.
1178  *
1179  * Returns:
1180  * Zero on success, error code on failure.
1181  */
1182 int drm_universal_plane_init(struct drm_device *dev, struct drm_plane *plane,
1183 			     unsigned long possible_crtcs,
1184 			     const struct drm_plane_funcs *funcs,
1185 			     const uint32_t *formats, unsigned int format_count,
1186 			     enum drm_plane_type type)
1187 {
1188 	struct drm_mode_config *config = &dev->mode_config;
1189 	int ret;
1190 
1191 	ret = drm_mode_object_get(dev, &plane->base, DRM_MODE_OBJECT_PLANE);
1192 	if (ret)
1193 		return ret;
1194 
1195 	drm_modeset_lock_init(&plane->mutex);
1196 
1197 	plane->base.properties = &plane->properties;
1198 	plane->dev = dev;
1199 	plane->funcs = funcs;
1200 	plane->format_types = kmalloc_array(format_count, sizeof(uint32_t),
1201 					    GFP_KERNEL);
1202 	if (!plane->format_types) {
1203 		DRM_DEBUG_KMS("out of memory when allocating plane\n");
1204 		drm_mode_object_put(dev, &plane->base);
1205 		return -ENOMEM;
1206 	}
1207 
1208 	memcpy(plane->format_types, formats, format_count * sizeof(uint32_t));
1209 	plane->format_count = format_count;
1210 	plane->possible_crtcs = possible_crtcs;
1211 	plane->type = type;
1212 
1213 	list_add_tail(&plane->head, &config->plane_list);
1214 	config->num_total_plane++;
1215 	if (plane->type == DRM_PLANE_TYPE_OVERLAY)
1216 		config->num_overlay_plane++;
1217 
1218 	drm_object_attach_property(&plane->base,
1219 				   config->plane_type_property,
1220 				   plane->type);
1221 
1222 	if (drm_core_check_feature(dev, DRIVER_ATOMIC)) {
1223 		drm_object_attach_property(&plane->base, config->prop_fb_id, 0);
1224 		drm_object_attach_property(&plane->base, config->prop_crtc_id, 0);
1225 		drm_object_attach_property(&plane->base, config->prop_crtc_x, 0);
1226 		drm_object_attach_property(&plane->base, config->prop_crtc_y, 0);
1227 		drm_object_attach_property(&plane->base, config->prop_crtc_w, 0);
1228 		drm_object_attach_property(&plane->base, config->prop_crtc_h, 0);
1229 		drm_object_attach_property(&plane->base, config->prop_src_x, 0);
1230 		drm_object_attach_property(&plane->base, config->prop_src_y, 0);
1231 		drm_object_attach_property(&plane->base, config->prop_src_w, 0);
1232 		drm_object_attach_property(&plane->base, config->prop_src_h, 0);
1233 	}
1234 
1235 	return 0;
1236 }
1237 EXPORT_SYMBOL(drm_universal_plane_init);
1238 
1239 /**
1240  * drm_plane_init - Initialize a legacy plane
1241  * @dev: DRM device
1242  * @plane: plane object to init
1243  * @possible_crtcs: bitmask of possible CRTCs
1244  * @funcs: callbacks for the new plane
1245  * @formats: array of supported formats (%DRM_FORMAT_*)
1246  * @format_count: number of elements in @formats
1247  * @is_primary: plane type (primary vs overlay)
1248  *
1249  * Legacy API to initialize a DRM plane.
1250  *
1251  * New drivers should call drm_universal_plane_init() instead.
1252  *
1253  * Returns:
1254  * Zero on success, error code on failure.
1255  */
1256 int drm_plane_init(struct drm_device *dev, struct drm_plane *plane,
1257 		   unsigned long possible_crtcs,
1258 		   const struct drm_plane_funcs *funcs,
1259 		   const uint32_t *formats, unsigned int format_count,
1260 		   bool is_primary)
1261 {
1262 	enum drm_plane_type type;
1263 
1264 	type = is_primary ? DRM_PLANE_TYPE_PRIMARY : DRM_PLANE_TYPE_OVERLAY;
1265 	return drm_universal_plane_init(dev, plane, possible_crtcs, funcs,
1266 					formats, format_count, type);
1267 }
1268 EXPORT_SYMBOL(drm_plane_init);
1269 
1270 /**
1271  * drm_plane_cleanup - Clean up the core plane usage
1272  * @plane: plane to cleanup
1273  *
1274  * This function cleans up @plane and removes it from the DRM mode setting
1275  * core. Note that the function does *not* free the plane structure itself,
1276  * this is the responsibility of the caller.
1277  */
1278 void drm_plane_cleanup(struct drm_plane *plane)
1279 {
1280 	struct drm_device *dev = plane->dev;
1281 
1282 	drm_modeset_lock_all(dev);
1283 	kfree(plane->format_types);
1284 	drm_mode_object_put(dev, &plane->base);
1285 
1286 	BUG_ON(list_empty(&plane->head));
1287 
1288 	list_del(&plane->head);
1289 	dev->mode_config.num_total_plane--;
1290 	if (plane->type == DRM_PLANE_TYPE_OVERLAY)
1291 		dev->mode_config.num_overlay_plane--;
1292 	drm_modeset_unlock_all(dev);
1293 
1294 	WARN_ON(plane->state && !plane->funcs->atomic_destroy_state);
1295 	if (plane->state && plane->funcs->atomic_destroy_state)
1296 		plane->funcs->atomic_destroy_state(plane, plane->state);
1297 	drm_modeset_lock_fini(&plane->mutex);
1298 
1299 	memset(plane, 0, sizeof(*plane));
1300 }
1301 EXPORT_SYMBOL(drm_plane_cleanup);
1302 
1303 /**
1304  * drm_plane_index - find the index of a registered plane
1305  * @plane: plane to find index for
1306  *
1307  * Given a registered plane, return the index of that CRTC within a DRM
1308  * device's list of planes.
1309  */
1310 unsigned int drm_plane_index(struct drm_plane *plane)
1311 {
1312 	unsigned int index = 0;
1313 	struct drm_plane *tmp;
1314 
1315 	drm_for_each_plane(tmp, plane->dev) {
1316 		if (tmp == plane)
1317 			return index;
1318 
1319 		index++;
1320 	}
1321 
1322 	BUG();
1323 }
1324 EXPORT_SYMBOL(drm_plane_index);
1325 
1326 /**
1327  * drm_plane_from_index - find the registered plane at an index
1328  * @dev: DRM device
1329  * @idx: index of registered plane to find for
1330  *
1331  * Given a plane index, return the registered plane from DRM device's
1332  * list of planes with matching index.
1333  */
1334 struct drm_plane *
1335 drm_plane_from_index(struct drm_device *dev, int idx)
1336 {
1337 	struct drm_plane *plane;
1338 	unsigned int i = 0;
1339 
1340 	drm_for_each_plane(plane, dev) {
1341 		if (i == idx)
1342 			return plane;
1343 		i++;
1344 	}
1345 	return NULL;
1346 }
1347 EXPORT_SYMBOL(drm_plane_from_index);
1348 
1349 /**
1350  * drm_plane_force_disable - Forcibly disable a plane
1351  * @plane: plane to disable
1352  *
1353  * Forces the plane to be disabled.
1354  *
1355  * Used when the plane's current framebuffer is destroyed,
1356  * and when restoring fbdev mode.
1357  */
1358 void drm_plane_force_disable(struct drm_plane *plane)
1359 {
1360 	int ret;
1361 
1362 	if (!plane->fb)
1363 		return;
1364 
1365 	plane->old_fb = plane->fb;
1366 	ret = plane->funcs->disable_plane(plane);
1367 	if (ret) {
1368 		DRM_ERROR("failed to disable plane with busy fb\n");
1369 		plane->old_fb = NULL;
1370 		return;
1371 	}
1372 	/* disconnect the plane from the fb and crtc: */
1373 	drm_framebuffer_unreference(plane->old_fb);
1374 	plane->old_fb = NULL;
1375 	plane->fb = NULL;
1376 	plane->crtc = NULL;
1377 }
1378 EXPORT_SYMBOL(drm_plane_force_disable);
1379 
1380 static int drm_mode_create_standard_properties(struct drm_device *dev)
1381 {
1382 	struct drm_property *prop;
1383 
1384 	/*
1385 	 * Standard properties (apply to all connectors)
1386 	 */
1387 	prop = drm_property_create(dev, DRM_MODE_PROP_BLOB |
1388 				   DRM_MODE_PROP_IMMUTABLE,
1389 				   "EDID", 0);
1390 	if (!prop)
1391 		return -ENOMEM;
1392 	dev->mode_config.edid_property = prop;
1393 
1394 	prop = drm_property_create_enum(dev, 0,
1395 				   "DPMS", drm_dpms_enum_list,
1396 				   ARRAY_SIZE(drm_dpms_enum_list));
1397 	if (!prop)
1398 		return -ENOMEM;
1399 	dev->mode_config.dpms_property = prop;
1400 
1401 	prop = drm_property_create(dev,
1402 				   DRM_MODE_PROP_BLOB |
1403 				   DRM_MODE_PROP_IMMUTABLE,
1404 				   "PATH", 0);
1405 	if (!prop)
1406 		return -ENOMEM;
1407 	dev->mode_config.path_property = prop;
1408 
1409 	prop = drm_property_create(dev,
1410 				   DRM_MODE_PROP_BLOB |
1411 				   DRM_MODE_PROP_IMMUTABLE,
1412 				   "TILE", 0);
1413 	if (!prop)
1414 		return -ENOMEM;
1415 	dev->mode_config.tile_property = prop;
1416 
1417 	prop = drm_property_create_enum(dev, DRM_MODE_PROP_IMMUTABLE,
1418 					"type", drm_plane_type_enum_list,
1419 					ARRAY_SIZE(drm_plane_type_enum_list));
1420 	if (!prop)
1421 		return -ENOMEM;
1422 	dev->mode_config.plane_type_property = prop;
1423 
1424 	prop = drm_property_create_range(dev, DRM_MODE_PROP_ATOMIC,
1425 			"SRC_X", 0, UINT_MAX);
1426 	if (!prop)
1427 		return -ENOMEM;
1428 	dev->mode_config.prop_src_x = prop;
1429 
1430 	prop = drm_property_create_range(dev, DRM_MODE_PROP_ATOMIC,
1431 			"SRC_Y", 0, UINT_MAX);
1432 	if (!prop)
1433 		return -ENOMEM;
1434 	dev->mode_config.prop_src_y = prop;
1435 
1436 	prop = drm_property_create_range(dev, DRM_MODE_PROP_ATOMIC,
1437 			"SRC_W", 0, UINT_MAX);
1438 	if (!prop)
1439 		return -ENOMEM;
1440 	dev->mode_config.prop_src_w = prop;
1441 
1442 	prop = drm_property_create_range(dev, DRM_MODE_PROP_ATOMIC,
1443 			"SRC_H", 0, UINT_MAX);
1444 	if (!prop)
1445 		return -ENOMEM;
1446 	dev->mode_config.prop_src_h = prop;
1447 
1448 	prop = drm_property_create_signed_range(dev, DRM_MODE_PROP_ATOMIC,
1449 			"CRTC_X", INT_MIN, INT_MAX);
1450 	if (!prop)
1451 		return -ENOMEM;
1452 	dev->mode_config.prop_crtc_x = prop;
1453 
1454 	prop = drm_property_create_signed_range(dev, DRM_MODE_PROP_ATOMIC,
1455 			"CRTC_Y", INT_MIN, INT_MAX);
1456 	if (!prop)
1457 		return -ENOMEM;
1458 	dev->mode_config.prop_crtc_y = prop;
1459 
1460 	prop = drm_property_create_range(dev, DRM_MODE_PROP_ATOMIC,
1461 			"CRTC_W", 0, INT_MAX);
1462 	if (!prop)
1463 		return -ENOMEM;
1464 	dev->mode_config.prop_crtc_w = prop;
1465 
1466 	prop = drm_property_create_range(dev, DRM_MODE_PROP_ATOMIC,
1467 			"CRTC_H", 0, INT_MAX);
1468 	if (!prop)
1469 		return -ENOMEM;
1470 	dev->mode_config.prop_crtc_h = prop;
1471 
1472 	prop = drm_property_create_object(dev, DRM_MODE_PROP_ATOMIC,
1473 			"FB_ID", DRM_MODE_OBJECT_FB);
1474 	if (!prop)
1475 		return -ENOMEM;
1476 	dev->mode_config.prop_fb_id = prop;
1477 
1478 	prop = drm_property_create_object(dev, DRM_MODE_PROP_ATOMIC,
1479 			"CRTC_ID", DRM_MODE_OBJECT_CRTC);
1480 	if (!prop)
1481 		return -ENOMEM;
1482 	dev->mode_config.prop_crtc_id = prop;
1483 
1484 	prop = drm_property_create_bool(dev, DRM_MODE_PROP_ATOMIC,
1485 			"ACTIVE");
1486 	if (!prop)
1487 		return -ENOMEM;
1488 	dev->mode_config.prop_active = prop;
1489 
1490 	prop = drm_property_create(dev,
1491 			DRM_MODE_PROP_ATOMIC | DRM_MODE_PROP_BLOB,
1492 			"MODE_ID", 0);
1493 	if (!prop)
1494 		return -ENOMEM;
1495 	dev->mode_config.prop_mode_id = prop;
1496 
1497 	return 0;
1498 }
1499 
1500 /**
1501  * drm_mode_create_dvi_i_properties - create DVI-I specific connector properties
1502  * @dev: DRM device
1503  *
1504  * Called by a driver the first time a DVI-I connector is made.
1505  */
1506 int drm_mode_create_dvi_i_properties(struct drm_device *dev)
1507 {
1508 	struct drm_property *dvi_i_selector;
1509 	struct drm_property *dvi_i_subconnector;
1510 
1511 	if (dev->mode_config.dvi_i_select_subconnector_property)
1512 		return 0;
1513 
1514 	dvi_i_selector =
1515 		drm_property_create_enum(dev, 0,
1516 				    "select subconnector",
1517 				    drm_dvi_i_select_enum_list,
1518 				    ARRAY_SIZE(drm_dvi_i_select_enum_list));
1519 	dev->mode_config.dvi_i_select_subconnector_property = dvi_i_selector;
1520 
1521 	dvi_i_subconnector = drm_property_create_enum(dev, DRM_MODE_PROP_IMMUTABLE,
1522 				    "subconnector",
1523 				    drm_dvi_i_subconnector_enum_list,
1524 				    ARRAY_SIZE(drm_dvi_i_subconnector_enum_list));
1525 	dev->mode_config.dvi_i_subconnector_property = dvi_i_subconnector;
1526 
1527 	return 0;
1528 }
1529 EXPORT_SYMBOL(drm_mode_create_dvi_i_properties);
1530 
1531 /**
1532  * drm_create_tv_properties - create TV specific connector properties
1533  * @dev: DRM device
1534  * @num_modes: number of different TV formats (modes) supported
1535  * @modes: array of pointers to strings containing name of each format
1536  *
1537  * Called by a driver's TV initialization routine, this function creates
1538  * the TV specific connector properties for a given device.  Caller is
1539  * responsible for allocating a list of format names and passing them to
1540  * this routine.
1541  */
1542 int drm_mode_create_tv_properties(struct drm_device *dev,
1543 				  unsigned int num_modes,
1544 				  const char * const modes[])
1545 {
1546 	struct drm_property *tv_selector;
1547 	struct drm_property *tv_subconnector;
1548 	unsigned int i;
1549 
1550 	if (dev->mode_config.tv_select_subconnector_property)
1551 		return 0;
1552 
1553 	/*
1554 	 * Basic connector properties
1555 	 */
1556 	tv_selector = drm_property_create_enum(dev, 0,
1557 					  "select subconnector",
1558 					  drm_tv_select_enum_list,
1559 					  ARRAY_SIZE(drm_tv_select_enum_list));
1560 	if (!tv_selector)
1561 		goto nomem;
1562 
1563 	dev->mode_config.tv_select_subconnector_property = tv_selector;
1564 
1565 	tv_subconnector =
1566 		drm_property_create_enum(dev, DRM_MODE_PROP_IMMUTABLE,
1567 				    "subconnector",
1568 				    drm_tv_subconnector_enum_list,
1569 				    ARRAY_SIZE(drm_tv_subconnector_enum_list));
1570 	if (!tv_subconnector)
1571 		goto nomem;
1572 	dev->mode_config.tv_subconnector_property = tv_subconnector;
1573 
1574 	/*
1575 	 * Other, TV specific properties: margins & TV modes.
1576 	 */
1577 	dev->mode_config.tv_left_margin_property =
1578 		drm_property_create_range(dev, 0, "left margin", 0, 100);
1579 	if (!dev->mode_config.tv_left_margin_property)
1580 		goto nomem;
1581 
1582 	dev->mode_config.tv_right_margin_property =
1583 		drm_property_create_range(dev, 0, "right margin", 0, 100);
1584 	if (!dev->mode_config.tv_right_margin_property)
1585 		goto nomem;
1586 
1587 	dev->mode_config.tv_top_margin_property =
1588 		drm_property_create_range(dev, 0, "top margin", 0, 100);
1589 	if (!dev->mode_config.tv_top_margin_property)
1590 		goto nomem;
1591 
1592 	dev->mode_config.tv_bottom_margin_property =
1593 		drm_property_create_range(dev, 0, "bottom margin", 0, 100);
1594 	if (!dev->mode_config.tv_bottom_margin_property)
1595 		goto nomem;
1596 
1597 	dev->mode_config.tv_mode_property =
1598 		drm_property_create(dev, DRM_MODE_PROP_ENUM,
1599 				    "mode", num_modes);
1600 	if (!dev->mode_config.tv_mode_property)
1601 		goto nomem;
1602 
1603 	for (i = 0; i < num_modes; i++)
1604 		drm_property_add_enum(dev->mode_config.tv_mode_property, i,
1605 				      i, modes[i]);
1606 
1607 	dev->mode_config.tv_brightness_property =
1608 		drm_property_create_range(dev, 0, "brightness", 0, 100);
1609 	if (!dev->mode_config.tv_brightness_property)
1610 		goto nomem;
1611 
1612 	dev->mode_config.tv_contrast_property =
1613 		drm_property_create_range(dev, 0, "contrast", 0, 100);
1614 	if (!dev->mode_config.tv_contrast_property)
1615 		goto nomem;
1616 
1617 	dev->mode_config.tv_flicker_reduction_property =
1618 		drm_property_create_range(dev, 0, "flicker reduction", 0, 100);
1619 	if (!dev->mode_config.tv_flicker_reduction_property)
1620 		goto nomem;
1621 
1622 	dev->mode_config.tv_overscan_property =
1623 		drm_property_create_range(dev, 0, "overscan", 0, 100);
1624 	if (!dev->mode_config.tv_overscan_property)
1625 		goto nomem;
1626 
1627 	dev->mode_config.tv_saturation_property =
1628 		drm_property_create_range(dev, 0, "saturation", 0, 100);
1629 	if (!dev->mode_config.tv_saturation_property)
1630 		goto nomem;
1631 
1632 	dev->mode_config.tv_hue_property =
1633 		drm_property_create_range(dev, 0, "hue", 0, 100);
1634 	if (!dev->mode_config.tv_hue_property)
1635 		goto nomem;
1636 
1637 	return 0;
1638 nomem:
1639 	return -ENOMEM;
1640 }
1641 EXPORT_SYMBOL(drm_mode_create_tv_properties);
1642 
1643 /**
1644  * drm_mode_create_scaling_mode_property - create scaling mode property
1645  * @dev: DRM device
1646  *
1647  * Called by a driver the first time it's needed, must be attached to desired
1648  * connectors.
1649  */
1650 int drm_mode_create_scaling_mode_property(struct drm_device *dev)
1651 {
1652 	struct drm_property *scaling_mode;
1653 
1654 	if (dev->mode_config.scaling_mode_property)
1655 		return 0;
1656 
1657 	scaling_mode =
1658 		drm_property_create_enum(dev, 0, "scaling mode",
1659 				drm_scaling_mode_enum_list,
1660 				    ARRAY_SIZE(drm_scaling_mode_enum_list));
1661 
1662 	dev->mode_config.scaling_mode_property = scaling_mode;
1663 
1664 	return 0;
1665 }
1666 EXPORT_SYMBOL(drm_mode_create_scaling_mode_property);
1667 
1668 /**
1669  * drm_mode_create_aspect_ratio_property - create aspect ratio property
1670  * @dev: DRM device
1671  *
1672  * Called by a driver the first time it's needed, must be attached to desired
1673  * connectors.
1674  *
1675  * Returns:
1676  * Zero on success, negative errno on failure.
1677  */
1678 int drm_mode_create_aspect_ratio_property(struct drm_device *dev)
1679 {
1680 	if (dev->mode_config.aspect_ratio_property)
1681 		return 0;
1682 
1683 	dev->mode_config.aspect_ratio_property =
1684 		drm_property_create_enum(dev, 0, "aspect ratio",
1685 				drm_aspect_ratio_enum_list,
1686 				ARRAY_SIZE(drm_aspect_ratio_enum_list));
1687 
1688 	if (dev->mode_config.aspect_ratio_property == NULL)
1689 		return -ENOMEM;
1690 
1691 	return 0;
1692 }
1693 EXPORT_SYMBOL(drm_mode_create_aspect_ratio_property);
1694 
1695 /**
1696  * drm_mode_create_dirty_property - create dirty property
1697  * @dev: DRM device
1698  *
1699  * Called by a driver the first time it's needed, must be attached to desired
1700  * connectors.
1701  */
1702 int drm_mode_create_dirty_info_property(struct drm_device *dev)
1703 {
1704 	struct drm_property *dirty_info;
1705 
1706 	if (dev->mode_config.dirty_info_property)
1707 		return 0;
1708 
1709 	dirty_info =
1710 		drm_property_create_enum(dev, DRM_MODE_PROP_IMMUTABLE,
1711 				    "dirty",
1712 				    drm_dirty_info_enum_list,
1713 				    ARRAY_SIZE(drm_dirty_info_enum_list));
1714 	dev->mode_config.dirty_info_property = dirty_info;
1715 
1716 	return 0;
1717 }
1718 EXPORT_SYMBOL(drm_mode_create_dirty_info_property);
1719 
1720 /**
1721  * drm_mode_create_suggested_offset_properties - create suggests offset properties
1722  * @dev: DRM device
1723  *
1724  * Create the the suggested x/y offset property for connectors.
1725  */
1726 int drm_mode_create_suggested_offset_properties(struct drm_device *dev)
1727 {
1728 	if (dev->mode_config.suggested_x_property && dev->mode_config.suggested_y_property)
1729 		return 0;
1730 
1731 	dev->mode_config.suggested_x_property =
1732 		drm_property_create_range(dev, DRM_MODE_PROP_IMMUTABLE, "suggested X", 0, 0xffffffff);
1733 
1734 	dev->mode_config.suggested_y_property =
1735 		drm_property_create_range(dev, DRM_MODE_PROP_IMMUTABLE, "suggested Y", 0, 0xffffffff);
1736 
1737 	if (dev->mode_config.suggested_x_property == NULL ||
1738 	    dev->mode_config.suggested_y_property == NULL)
1739 		return -ENOMEM;
1740 	return 0;
1741 }
1742 EXPORT_SYMBOL(drm_mode_create_suggested_offset_properties);
1743 
1744 /**
1745  * drm_mode_getresources - get graphics configuration
1746  * @dev: drm device for the ioctl
1747  * @data: data pointer for the ioctl
1748  * @file_priv: drm file for the ioctl call
1749  *
1750  * Construct a set of configuration description structures and return
1751  * them to the user, including CRTC, connector and framebuffer configuration.
1752  *
1753  * Called by the user via ioctl.
1754  *
1755  * Returns:
1756  * Zero on success, negative errno on failure.
1757  */
1758 int drm_mode_getresources(struct drm_device *dev, void *data,
1759 			  struct drm_file *file_priv)
1760 {
1761 	struct drm_mode_card_res *card_res = data;
1762 	struct list_head *lh;
1763 	struct drm_framebuffer *fb;
1764 	struct drm_connector *connector;
1765 	struct drm_crtc *crtc;
1766 	struct drm_encoder *encoder;
1767 	int ret = 0;
1768 	int connector_count = 0;
1769 	int crtc_count = 0;
1770 	int fb_count = 0;
1771 	int encoder_count = 0;
1772 	int copied = 0;
1773 	uint32_t __user *fb_id;
1774 	uint32_t __user *crtc_id;
1775 	uint32_t __user *connector_id;
1776 	uint32_t __user *encoder_id;
1777 
1778 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
1779 		return -EINVAL;
1780 
1781 
1782 	mutex_lock(&file_priv->fbs_lock);
1783 	/*
1784 	 * For the non-control nodes we need to limit the list of resources
1785 	 * by IDs in the group list for this node
1786 	 */
1787 	list_for_each(lh, &file_priv->fbs)
1788 		fb_count++;
1789 
1790 	/* handle this in 4 parts */
1791 	/* FBs */
1792 	if (card_res->count_fbs >= fb_count) {
1793 		copied = 0;
1794 		fb_id = (uint32_t __user *)(unsigned long)card_res->fb_id_ptr;
1795 		list_for_each_entry(fb, &file_priv->fbs, filp_head) {
1796 			if (put_user(fb->base.id, fb_id + copied)) {
1797 				mutex_unlock(&file_priv->fbs_lock);
1798 				return -EFAULT;
1799 			}
1800 			copied++;
1801 		}
1802 	}
1803 	card_res->count_fbs = fb_count;
1804 	mutex_unlock(&file_priv->fbs_lock);
1805 
1806 	/* mode_config.mutex protects the connector list against e.g. DP MST
1807 	 * connector hot-adding. CRTC/Plane lists are invariant. */
1808 	mutex_lock(&dev->mode_config.mutex);
1809 	drm_for_each_crtc(crtc, dev)
1810 		crtc_count++;
1811 
1812 	drm_for_each_connector(connector, dev)
1813 		connector_count++;
1814 
1815 	drm_for_each_encoder(encoder, dev)
1816 		encoder_count++;
1817 
1818 	card_res->max_height = dev->mode_config.max_height;
1819 	card_res->min_height = dev->mode_config.min_height;
1820 	card_res->max_width = dev->mode_config.max_width;
1821 	card_res->min_width = dev->mode_config.min_width;
1822 
1823 	/* CRTCs */
1824 	if (card_res->count_crtcs >= crtc_count) {
1825 		copied = 0;
1826 		crtc_id = (uint32_t __user *)(unsigned long)card_res->crtc_id_ptr;
1827 		drm_for_each_crtc(crtc, dev) {
1828 			DRM_DEBUG_KMS("[CRTC:%d]\n", crtc->base.id);
1829 			if (put_user(crtc->base.id, crtc_id + copied)) {
1830 				ret = -EFAULT;
1831 				goto out;
1832 			}
1833 			copied++;
1834 		}
1835 	}
1836 	card_res->count_crtcs = crtc_count;
1837 
1838 	/* Encoders */
1839 	if (card_res->count_encoders >= encoder_count) {
1840 		copied = 0;
1841 		encoder_id = (uint32_t __user *)(unsigned long)card_res->encoder_id_ptr;
1842 		drm_for_each_encoder(encoder, dev) {
1843 			DRM_DEBUG_KMS("[ENCODER:%d:%s]\n", encoder->base.id,
1844 					encoder->name);
1845 			if (put_user(encoder->base.id, encoder_id +
1846 				     copied)) {
1847 				ret = -EFAULT;
1848 				goto out;
1849 			}
1850 			copied++;
1851 		}
1852 	}
1853 	card_res->count_encoders = encoder_count;
1854 
1855 	/* Connectors */
1856 	if (card_res->count_connectors >= connector_count) {
1857 		copied = 0;
1858 		connector_id = (uint32_t __user *)(unsigned long)card_res->connector_id_ptr;
1859 		drm_for_each_connector(connector, dev) {
1860 			DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
1861 				connector->base.id,
1862 				connector->name);
1863 			if (put_user(connector->base.id,
1864 				     connector_id + copied)) {
1865 				ret = -EFAULT;
1866 				goto out;
1867 			}
1868 			copied++;
1869 		}
1870 	}
1871 	card_res->count_connectors = connector_count;
1872 
1873 	DRM_DEBUG_KMS("CRTC[%d] CONNECTORS[%d] ENCODERS[%d]\n", card_res->count_crtcs,
1874 		  card_res->count_connectors, card_res->count_encoders);
1875 
1876 out:
1877 	mutex_unlock(&dev->mode_config.mutex);
1878 	return ret;
1879 }
1880 
1881 /**
1882  * drm_mode_getcrtc - get CRTC configuration
1883  * @dev: drm device for the ioctl
1884  * @data: data pointer for the ioctl
1885  * @file_priv: drm file for the ioctl call
1886  *
1887  * Construct a CRTC configuration structure to return to the user.
1888  *
1889  * Called by the user via ioctl.
1890  *
1891  * Returns:
1892  * Zero on success, negative errno on failure.
1893  */
1894 int drm_mode_getcrtc(struct drm_device *dev,
1895 		     void *data, struct drm_file *file_priv)
1896 {
1897 	struct drm_mode_crtc *crtc_resp = data;
1898 	struct drm_crtc *crtc;
1899 
1900 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
1901 		return -EINVAL;
1902 
1903 	crtc = drm_crtc_find(dev, crtc_resp->crtc_id);
1904 	if (!crtc)
1905 		return -ENOENT;
1906 
1907 	drm_modeset_lock_crtc(crtc, crtc->primary);
1908 	crtc_resp->gamma_size = crtc->gamma_size;
1909 	if (crtc->primary->fb)
1910 		crtc_resp->fb_id = crtc->primary->fb->base.id;
1911 	else
1912 		crtc_resp->fb_id = 0;
1913 
1914 	if (crtc->state) {
1915 		crtc_resp->x = crtc->primary->state->src_x >> 16;
1916 		crtc_resp->y = crtc->primary->state->src_y >> 16;
1917 		if (crtc->state->enable) {
1918 			drm_mode_convert_to_umode(&crtc_resp->mode, &crtc->state->mode);
1919 			crtc_resp->mode_valid = 1;
1920 
1921 		} else {
1922 			crtc_resp->mode_valid = 0;
1923 		}
1924 	} else {
1925 		crtc_resp->x = crtc->x;
1926 		crtc_resp->y = crtc->y;
1927 		if (crtc->enabled) {
1928 			drm_mode_convert_to_umode(&crtc_resp->mode, &crtc->mode);
1929 			crtc_resp->mode_valid = 1;
1930 
1931 		} else {
1932 			crtc_resp->mode_valid = 0;
1933 		}
1934 	}
1935 	drm_modeset_unlock_crtc(crtc);
1936 
1937 	return 0;
1938 }
1939 
1940 static bool drm_mode_expose_to_userspace(const struct drm_display_mode *mode,
1941 					 const struct drm_file *file_priv)
1942 {
1943 	/*
1944 	 * If user-space hasn't configured the driver to expose the stereo 3D
1945 	 * modes, don't expose them.
1946 	 */
1947 	if (!file_priv->stereo_allowed && drm_mode_is_stereo(mode))
1948 		return false;
1949 
1950 	return true;
1951 }
1952 
1953 static struct drm_encoder *drm_connector_get_encoder(struct drm_connector *connector)
1954 {
1955 	/* For atomic drivers only state objects are synchronously updated and
1956 	 * protected by modeset locks, so check those first. */
1957 	if (connector->state)
1958 		return connector->state->best_encoder;
1959 	return connector->encoder;
1960 }
1961 
1962 /* helper for getconnector and getproperties ioctls */
1963 static int get_properties(struct drm_mode_object *obj, bool atomic,
1964 		uint32_t __user *prop_ptr, uint64_t __user *prop_values,
1965 		uint32_t *arg_count_props)
1966 {
1967 	int props_count;
1968 	int i, ret, copied;
1969 
1970 	props_count = obj->properties->count;
1971 	if (!atomic)
1972 		props_count -= obj->properties->atomic_count;
1973 
1974 	if ((*arg_count_props >= props_count) && props_count) {
1975 		for (i = 0, copied = 0; copied < props_count; i++) {
1976 			struct drm_property *prop = obj->properties->properties[i];
1977 			uint64_t val;
1978 
1979 			if ((prop->flags & DRM_MODE_PROP_ATOMIC) && !atomic)
1980 				continue;
1981 
1982 			ret = drm_object_property_get_value(obj, prop, &val);
1983 			if (ret)
1984 				return ret;
1985 
1986 			if (put_user(prop->base.id, prop_ptr + copied))
1987 				return -EFAULT;
1988 
1989 			if (put_user(val, prop_values + copied))
1990 				return -EFAULT;
1991 
1992 			copied++;
1993 		}
1994 	}
1995 	*arg_count_props = props_count;
1996 
1997 	return 0;
1998 }
1999 
2000 /**
2001  * drm_mode_getconnector - get connector configuration
2002  * @dev: drm device for the ioctl
2003  * @data: data pointer for the ioctl
2004  * @file_priv: drm file for the ioctl call
2005  *
2006  * Construct a connector configuration structure to return to the user.
2007  *
2008  * Called by the user via ioctl.
2009  *
2010  * Returns:
2011  * Zero on success, negative errno on failure.
2012  */
2013 int drm_mode_getconnector(struct drm_device *dev, void *data,
2014 			  struct drm_file *file_priv)
2015 {
2016 	struct drm_mode_get_connector *out_resp = data;
2017 	struct drm_connector *connector;
2018 	struct drm_encoder *encoder;
2019 	struct drm_display_mode *mode;
2020 	int mode_count = 0;
2021 	int encoders_count = 0;
2022 	int ret = 0;
2023 	int copied = 0;
2024 	int i;
2025 	struct drm_mode_modeinfo u_mode;
2026 	struct drm_mode_modeinfo __user *mode_ptr;
2027 	uint32_t __user *encoder_ptr;
2028 
2029 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
2030 		return -EINVAL;
2031 
2032 	memset(&u_mode, 0, sizeof(struct drm_mode_modeinfo));
2033 
2034 	DRM_DEBUG_KMS("[CONNECTOR:%d:?]\n", out_resp->connector_id);
2035 
2036 	mutex_lock(&dev->mode_config.mutex);
2037 
2038 	connector = drm_connector_find(dev, out_resp->connector_id);
2039 	if (!connector) {
2040 		ret = -ENOENT;
2041 		goto out_unlock;
2042 	}
2043 
2044 	for (i = 0; i < DRM_CONNECTOR_MAX_ENCODER; i++)
2045 		if (connector->encoder_ids[i] != 0)
2046 			encoders_count++;
2047 
2048 	if (out_resp->count_modes == 0) {
2049 		connector->funcs->fill_modes(connector,
2050 					     dev->mode_config.max_width,
2051 					     dev->mode_config.max_height);
2052 	}
2053 
2054 	/* delayed so we get modes regardless of pre-fill_modes state */
2055 	list_for_each_entry(mode, &connector->modes, head)
2056 		if (drm_mode_expose_to_userspace(mode, file_priv))
2057 			mode_count++;
2058 
2059 	out_resp->connector_id = connector->base.id;
2060 	out_resp->connector_type = connector->connector_type;
2061 	out_resp->connector_type_id = connector->connector_type_id;
2062 	out_resp->mm_width = connector->display_info.width_mm;
2063 	out_resp->mm_height = connector->display_info.height_mm;
2064 	out_resp->subpixel = connector->display_info.subpixel_order;
2065 	out_resp->connection = connector->status;
2066 
2067 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
2068 	encoder = drm_connector_get_encoder(connector);
2069 	if (encoder)
2070 		out_resp->encoder_id = encoder->base.id;
2071 	else
2072 		out_resp->encoder_id = 0;
2073 
2074 	/*
2075 	 * This ioctl is called twice, once to determine how much space is
2076 	 * needed, and the 2nd time to fill it.
2077 	 */
2078 	if ((out_resp->count_modes >= mode_count) && mode_count) {
2079 		copied = 0;
2080 		mode_ptr = (struct drm_mode_modeinfo __user *)(unsigned long)out_resp->modes_ptr;
2081 		list_for_each_entry(mode, &connector->modes, head) {
2082 			if (!drm_mode_expose_to_userspace(mode, file_priv))
2083 				continue;
2084 
2085 			drm_mode_convert_to_umode(&u_mode, mode);
2086 			if (copy_to_user(mode_ptr + copied,
2087 					 &u_mode, sizeof(u_mode))) {
2088 				ret = -EFAULT;
2089 				goto out;
2090 			}
2091 			copied++;
2092 		}
2093 	}
2094 	out_resp->count_modes = mode_count;
2095 
2096 	ret = get_properties(&connector->base, file_priv->atomic,
2097 			(uint32_t __user *)(unsigned long)(out_resp->props_ptr),
2098 			(uint64_t __user *)(unsigned long)(out_resp->prop_values_ptr),
2099 			&out_resp->count_props);
2100 	if (ret)
2101 		goto out;
2102 
2103 	if ((out_resp->count_encoders >= encoders_count) && encoders_count) {
2104 		copied = 0;
2105 		encoder_ptr = (uint32_t __user *)(unsigned long)(out_resp->encoders_ptr);
2106 		for (i = 0; i < DRM_CONNECTOR_MAX_ENCODER; i++) {
2107 			if (connector->encoder_ids[i] != 0) {
2108 				if (put_user(connector->encoder_ids[i],
2109 					     encoder_ptr + copied)) {
2110 					ret = -EFAULT;
2111 					goto out;
2112 				}
2113 				copied++;
2114 			}
2115 		}
2116 	}
2117 	out_resp->count_encoders = encoders_count;
2118 
2119 out:
2120 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
2121 
2122 out_unlock:
2123 	mutex_unlock(&dev->mode_config.mutex);
2124 
2125 	return ret;
2126 }
2127 
2128 static struct drm_crtc *drm_encoder_get_crtc(struct drm_encoder *encoder)
2129 {
2130 	struct drm_connector *connector;
2131 	struct drm_device *dev = encoder->dev;
2132 	bool uses_atomic = false;
2133 
2134 	/* For atomic drivers only state objects are synchronously updated and
2135 	 * protected by modeset locks, so check those first. */
2136 	drm_for_each_connector(connector, dev) {
2137 		if (!connector->state)
2138 			continue;
2139 
2140 		uses_atomic = true;
2141 
2142 		if (connector->state->best_encoder != encoder)
2143 			continue;
2144 
2145 		return connector->state->crtc;
2146 	}
2147 
2148 	/* Don't return stale data (e.g. pending async disable). */
2149 	if (uses_atomic)
2150 		return NULL;
2151 
2152 	return encoder->crtc;
2153 }
2154 
2155 /**
2156  * drm_mode_getencoder - get encoder configuration
2157  * @dev: drm device for the ioctl
2158  * @data: data pointer for the ioctl
2159  * @file_priv: drm file for the ioctl call
2160  *
2161  * Construct a encoder configuration structure to return to the user.
2162  *
2163  * Called by the user via ioctl.
2164  *
2165  * Returns:
2166  * Zero on success, negative errno on failure.
2167  */
2168 int drm_mode_getencoder(struct drm_device *dev, void *data,
2169 			struct drm_file *file_priv)
2170 {
2171 	struct drm_mode_get_encoder *enc_resp = data;
2172 	struct drm_encoder *encoder;
2173 	struct drm_crtc *crtc;
2174 
2175 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
2176 		return -EINVAL;
2177 
2178 	encoder = drm_encoder_find(dev, enc_resp->encoder_id);
2179 	if (!encoder)
2180 		return -ENOENT;
2181 
2182 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
2183 	crtc = drm_encoder_get_crtc(encoder);
2184 	if (crtc)
2185 		enc_resp->crtc_id = crtc->base.id;
2186 	else
2187 		enc_resp->crtc_id = 0;
2188 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
2189 
2190 	enc_resp->encoder_type = encoder->encoder_type;
2191 	enc_resp->encoder_id = encoder->base.id;
2192 	enc_resp->possible_crtcs = encoder->possible_crtcs;
2193 	enc_resp->possible_clones = encoder->possible_clones;
2194 
2195 	return 0;
2196 }
2197 
2198 /**
2199  * drm_mode_getplane_res - enumerate all plane resources
2200  * @dev: DRM device
2201  * @data: ioctl data
2202  * @file_priv: DRM file info
2203  *
2204  * Construct a list of plane ids to return to the user.
2205  *
2206  * Called by the user via ioctl.
2207  *
2208  * Returns:
2209  * Zero on success, negative errno on failure.
2210  */
2211 int drm_mode_getplane_res(struct drm_device *dev, void *data,
2212 			  struct drm_file *file_priv)
2213 {
2214 	struct drm_mode_get_plane_res *plane_resp = data;
2215 	struct drm_mode_config *config;
2216 	struct drm_plane *plane;
2217 	uint32_t __user *plane_ptr;
2218 	int copied = 0;
2219 	unsigned num_planes;
2220 
2221 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
2222 		return -EINVAL;
2223 
2224 	config = &dev->mode_config;
2225 
2226 	if (file_priv->universal_planes)
2227 		num_planes = config->num_total_plane;
2228 	else
2229 		num_planes = config->num_overlay_plane;
2230 
2231 	/*
2232 	 * This ioctl is called twice, once to determine how much space is
2233 	 * needed, and the 2nd time to fill it.
2234 	 */
2235 	if (num_planes &&
2236 	    (plane_resp->count_planes >= num_planes)) {
2237 		plane_ptr = (uint32_t __user *)(unsigned long)plane_resp->plane_id_ptr;
2238 
2239 		/* Plane lists are invariant, no locking needed. */
2240 		drm_for_each_plane(plane, dev) {
2241 			/*
2242 			 * Unless userspace set the 'universal planes'
2243 			 * capability bit, only advertise overlays.
2244 			 */
2245 			if (plane->type != DRM_PLANE_TYPE_OVERLAY &&
2246 			    !file_priv->universal_planes)
2247 				continue;
2248 
2249 			if (put_user(plane->base.id, plane_ptr + copied))
2250 				return -EFAULT;
2251 			copied++;
2252 		}
2253 	}
2254 	plane_resp->count_planes = num_planes;
2255 
2256 	return 0;
2257 }
2258 
2259 /**
2260  * drm_mode_getplane - get plane configuration
2261  * @dev: DRM device
2262  * @data: ioctl data
2263  * @file_priv: DRM file info
2264  *
2265  * Construct a plane configuration structure to return to the user.
2266  *
2267  * Called by the user via ioctl.
2268  *
2269  * Returns:
2270  * Zero on success, negative errno on failure.
2271  */
2272 int drm_mode_getplane(struct drm_device *dev, void *data,
2273 		      struct drm_file *file_priv)
2274 {
2275 	struct drm_mode_get_plane *plane_resp = data;
2276 	struct drm_plane *plane;
2277 	uint32_t __user *format_ptr;
2278 
2279 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
2280 		return -EINVAL;
2281 
2282 	plane = drm_plane_find(dev, plane_resp->plane_id);
2283 	if (!plane)
2284 		return -ENOENT;
2285 
2286 	drm_modeset_lock(&plane->mutex, NULL);
2287 	if (plane->crtc)
2288 		plane_resp->crtc_id = plane->crtc->base.id;
2289 	else
2290 		plane_resp->crtc_id = 0;
2291 
2292 	if (plane->fb)
2293 		plane_resp->fb_id = plane->fb->base.id;
2294 	else
2295 		plane_resp->fb_id = 0;
2296 	drm_modeset_unlock(&plane->mutex);
2297 
2298 	plane_resp->plane_id = plane->base.id;
2299 	plane_resp->possible_crtcs = plane->possible_crtcs;
2300 	plane_resp->gamma_size = 0;
2301 
2302 	/*
2303 	 * This ioctl is called twice, once to determine how much space is
2304 	 * needed, and the 2nd time to fill it.
2305 	 */
2306 	if (plane->format_count &&
2307 	    (plane_resp->count_format_types >= plane->format_count)) {
2308 		format_ptr = (uint32_t __user *)(unsigned long)plane_resp->format_type_ptr;
2309 		if (copy_to_user(format_ptr,
2310 				 plane->format_types,
2311 				 sizeof(uint32_t) * plane->format_count)) {
2312 			return -EFAULT;
2313 		}
2314 	}
2315 	plane_resp->count_format_types = plane->format_count;
2316 
2317 	return 0;
2318 }
2319 
2320 /**
2321  * drm_plane_check_pixel_format - Check if the plane supports the pixel format
2322  * @plane: plane to check for format support
2323  * @format: the pixel format
2324  *
2325  * Returns:
2326  * Zero of @plane has @format in its list of supported pixel formats, -EINVAL
2327  * otherwise.
2328  */
2329 int drm_plane_check_pixel_format(const struct drm_plane *plane, u32 format)
2330 {
2331 	unsigned int i;
2332 
2333 	for (i = 0; i < plane->format_count; i++) {
2334 		if (format == plane->format_types[i])
2335 			return 0;
2336 	}
2337 
2338 	return -EINVAL;
2339 }
2340 
2341 static int check_src_coords(uint32_t src_x, uint32_t src_y,
2342 			    uint32_t src_w, uint32_t src_h,
2343 			    const struct drm_framebuffer *fb)
2344 {
2345 	unsigned int fb_width, fb_height;
2346 
2347 	fb_width = fb->width << 16;
2348 	fb_height = fb->height << 16;
2349 
2350 	/* Make sure source coordinates are inside the fb. */
2351 	if (src_w > fb_width ||
2352 	    src_x > fb_width - src_w ||
2353 	    src_h > fb_height ||
2354 	    src_y > fb_height - src_h) {
2355 		DRM_DEBUG_KMS("Invalid source coordinates "
2356 			      "%u.%06ux%u.%06u+%u.%06u+%u.%06u\n",
2357 			      src_w >> 16, ((src_w & 0xffff) * 15625) >> 10,
2358 			      src_h >> 16, ((src_h & 0xffff) * 15625) >> 10,
2359 			      src_x >> 16, ((src_x & 0xffff) * 15625) >> 10,
2360 			      src_y >> 16, ((src_y & 0xffff) * 15625) >> 10);
2361 		return -ENOSPC;
2362 	}
2363 
2364 	return 0;
2365 }
2366 
2367 /*
2368  * setplane_internal - setplane handler for internal callers
2369  *
2370  * Note that we assume an extra reference has already been taken on fb.  If the
2371  * update fails, this reference will be dropped before return; if it succeeds,
2372  * the previous framebuffer (if any) will be unreferenced instead.
2373  *
2374  * src_{x,y,w,h} are provided in 16.16 fixed point format
2375  */
2376 static int __setplane_internal(struct drm_plane *plane,
2377 			       struct drm_crtc *crtc,
2378 			       struct drm_framebuffer *fb,
2379 			       int32_t crtc_x, int32_t crtc_y,
2380 			       uint32_t crtc_w, uint32_t crtc_h,
2381 			       /* src_{x,y,w,h} values are 16.16 fixed point */
2382 			       uint32_t src_x, uint32_t src_y,
2383 			       uint32_t src_w, uint32_t src_h)
2384 {
2385 	int ret = 0;
2386 
2387 	/* No fb means shut it down */
2388 	if (!fb) {
2389 		plane->old_fb = plane->fb;
2390 		ret = plane->funcs->disable_plane(plane);
2391 		if (!ret) {
2392 			plane->crtc = NULL;
2393 			plane->fb = NULL;
2394 		} else {
2395 			plane->old_fb = NULL;
2396 		}
2397 		goto out;
2398 	}
2399 
2400 	/* Check whether this plane is usable on this CRTC */
2401 	if (!(plane->possible_crtcs & drm_crtc_mask(crtc))) {
2402 		DRM_DEBUG_KMS("Invalid crtc for plane\n");
2403 		ret = -EINVAL;
2404 		goto out;
2405 	}
2406 
2407 	/* Check whether this plane supports the fb pixel format. */
2408 	ret = drm_plane_check_pixel_format(plane, fb->pixel_format);
2409 	if (ret) {
2410 		DRM_DEBUG_KMS("Invalid pixel format %s\n",
2411 			      drm_get_format_name(fb->pixel_format));
2412 		goto out;
2413 	}
2414 
2415 	/* Give drivers some help against integer overflows */
2416 	if (crtc_w > INT_MAX ||
2417 	    crtc_x > INT_MAX - (int32_t) crtc_w ||
2418 	    crtc_h > INT_MAX ||
2419 	    crtc_y > INT_MAX - (int32_t) crtc_h) {
2420 		DRM_DEBUG_KMS("Invalid CRTC coordinates %ux%u+%d+%d\n",
2421 			      crtc_w, crtc_h, crtc_x, crtc_y);
2422 		ret = -ERANGE;
2423 		goto out;
2424 	}
2425 
2426 	ret = check_src_coords(src_x, src_y, src_w, src_h, fb);
2427 	if (ret)
2428 		goto out;
2429 
2430 	plane->old_fb = plane->fb;
2431 	ret = plane->funcs->update_plane(plane, crtc, fb,
2432 					 crtc_x, crtc_y, crtc_w, crtc_h,
2433 					 src_x, src_y, src_w, src_h);
2434 	if (!ret) {
2435 		plane->crtc = crtc;
2436 		plane->fb = fb;
2437 		fb = NULL;
2438 	} else {
2439 		plane->old_fb = NULL;
2440 	}
2441 
2442 out:
2443 	if (fb)
2444 		drm_framebuffer_unreference(fb);
2445 	if (plane->old_fb)
2446 		drm_framebuffer_unreference(plane->old_fb);
2447 	plane->old_fb = NULL;
2448 
2449 	return ret;
2450 }
2451 
2452 static int setplane_internal(struct drm_plane *plane,
2453 			     struct drm_crtc *crtc,
2454 			     struct drm_framebuffer *fb,
2455 			     int32_t crtc_x, int32_t crtc_y,
2456 			     uint32_t crtc_w, uint32_t crtc_h,
2457 			     /* src_{x,y,w,h} values are 16.16 fixed point */
2458 			     uint32_t src_x, uint32_t src_y,
2459 			     uint32_t src_w, uint32_t src_h)
2460 {
2461 	int ret;
2462 
2463 	drm_modeset_lock_all(plane->dev);
2464 	ret = __setplane_internal(plane, crtc, fb,
2465 				  crtc_x, crtc_y, crtc_w, crtc_h,
2466 				  src_x, src_y, src_w, src_h);
2467 	drm_modeset_unlock_all(plane->dev);
2468 
2469 	return ret;
2470 }
2471 
2472 /**
2473  * drm_mode_setplane - configure a plane's configuration
2474  * @dev: DRM device
2475  * @data: ioctl data*
2476  * @file_priv: DRM file info
2477  *
2478  * Set plane configuration, including placement, fb, scaling, and other factors.
2479  * Or pass a NULL fb to disable (planes may be disabled without providing a
2480  * valid crtc).
2481  *
2482  * Returns:
2483  * Zero on success, negative errno on failure.
2484  */
2485 int drm_mode_setplane(struct drm_device *dev, void *data,
2486 		      struct drm_file *file_priv)
2487 {
2488 	struct drm_mode_set_plane *plane_req = data;
2489 	struct drm_plane *plane;
2490 	struct drm_crtc *crtc = NULL;
2491 	struct drm_framebuffer *fb = NULL;
2492 
2493 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
2494 		return -EINVAL;
2495 
2496 	/*
2497 	 * First, find the plane, crtc, and fb objects.  If not available,
2498 	 * we don't bother to call the driver.
2499 	 */
2500 	plane = drm_plane_find(dev, plane_req->plane_id);
2501 	if (!plane) {
2502 		DRM_DEBUG_KMS("Unknown plane ID %d\n",
2503 			      plane_req->plane_id);
2504 		return -ENOENT;
2505 	}
2506 
2507 	if (plane_req->fb_id) {
2508 		fb = drm_framebuffer_lookup(dev, plane_req->fb_id);
2509 		if (!fb) {
2510 			DRM_DEBUG_KMS("Unknown framebuffer ID %d\n",
2511 				      plane_req->fb_id);
2512 			return -ENOENT;
2513 		}
2514 
2515 		crtc = drm_crtc_find(dev, plane_req->crtc_id);
2516 		if (!crtc) {
2517 			DRM_DEBUG_KMS("Unknown crtc ID %d\n",
2518 				      plane_req->crtc_id);
2519 			return -ENOENT;
2520 		}
2521 	}
2522 
2523 	/*
2524 	 * setplane_internal will take care of deref'ing either the old or new
2525 	 * framebuffer depending on success.
2526 	 */
2527 	return setplane_internal(plane, crtc, fb,
2528 				 plane_req->crtc_x, plane_req->crtc_y,
2529 				 plane_req->crtc_w, plane_req->crtc_h,
2530 				 plane_req->src_x, plane_req->src_y,
2531 				 plane_req->src_w, plane_req->src_h);
2532 }
2533 
2534 /**
2535  * drm_mode_set_config_internal - helper to call ->set_config
2536  * @set: modeset config to set
2537  *
2538  * This is a little helper to wrap internal calls to the ->set_config driver
2539  * interface. The only thing it adds is correct refcounting dance.
2540  *
2541  * Returns:
2542  * Zero on success, negative errno on failure.
2543  */
2544 int drm_mode_set_config_internal(struct drm_mode_set *set)
2545 {
2546 	struct drm_crtc *crtc = set->crtc;
2547 	struct drm_framebuffer *fb;
2548 	struct drm_crtc *tmp;
2549 	int ret;
2550 
2551 	/*
2552 	 * NOTE: ->set_config can also disable other crtcs (if we steal all
2553 	 * connectors from it), hence we need to refcount the fbs across all
2554 	 * crtcs. Atomic modeset will have saner semantics ...
2555 	 */
2556 	drm_for_each_crtc(tmp, crtc->dev)
2557 		tmp->primary->old_fb = tmp->primary->fb;
2558 
2559 	fb = set->fb;
2560 
2561 	ret = crtc->funcs->set_config(set);
2562 	if (ret == 0) {
2563 		crtc->primary->crtc = crtc;
2564 		crtc->primary->fb = fb;
2565 	}
2566 
2567 	drm_for_each_crtc(tmp, crtc->dev) {
2568 		if (tmp->primary->fb)
2569 			drm_framebuffer_reference(tmp->primary->fb);
2570 		if (tmp->primary->old_fb)
2571 			drm_framebuffer_unreference(tmp->primary->old_fb);
2572 		tmp->primary->old_fb = NULL;
2573 	}
2574 
2575 	return ret;
2576 }
2577 EXPORT_SYMBOL(drm_mode_set_config_internal);
2578 
2579 /**
2580  * drm_crtc_get_hv_timing - Fetches hdisplay/vdisplay for given mode
2581  * @mode: mode to query
2582  * @hdisplay: hdisplay value to fill in
2583  * @vdisplay: vdisplay value to fill in
2584  *
2585  * The vdisplay value will be doubled if the specified mode is a stereo mode of
2586  * the appropriate layout.
2587  */
2588 void drm_crtc_get_hv_timing(const struct drm_display_mode *mode,
2589 			    int *hdisplay, int *vdisplay)
2590 {
2591 	struct drm_display_mode adjusted;
2592 
2593 	drm_mode_copy(&adjusted, mode);
2594 	drm_mode_set_crtcinfo(&adjusted, CRTC_STEREO_DOUBLE_ONLY);
2595 	*hdisplay = adjusted.crtc_hdisplay;
2596 	*vdisplay = adjusted.crtc_vdisplay;
2597 }
2598 EXPORT_SYMBOL(drm_crtc_get_hv_timing);
2599 
2600 /**
2601  * drm_crtc_check_viewport - Checks that a framebuffer is big enough for the
2602  *     CRTC viewport
2603  * @crtc: CRTC that framebuffer will be displayed on
2604  * @x: x panning
2605  * @y: y panning
2606  * @mode: mode that framebuffer will be displayed under
2607  * @fb: framebuffer to check size of
2608  */
2609 int drm_crtc_check_viewport(const struct drm_crtc *crtc,
2610 			    int x, int y,
2611 			    const struct drm_display_mode *mode,
2612 			    const struct drm_framebuffer *fb)
2613 
2614 {
2615 	int hdisplay, vdisplay;
2616 
2617 	drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
2618 
2619 	if (crtc->state &&
2620 	    crtc->primary->state->rotation & (BIT(DRM_ROTATE_90) |
2621 					      BIT(DRM_ROTATE_270)))
2622 		swap(hdisplay, vdisplay);
2623 
2624 	return check_src_coords(x << 16, y << 16,
2625 				hdisplay << 16, vdisplay << 16, fb);
2626 }
2627 EXPORT_SYMBOL(drm_crtc_check_viewport);
2628 
2629 /**
2630  * drm_mode_setcrtc - set CRTC configuration
2631  * @dev: drm device for the ioctl
2632  * @data: data pointer for the ioctl
2633  * @file_priv: drm file for the ioctl call
2634  *
2635  * Build a new CRTC configuration based on user request.
2636  *
2637  * Called by the user via ioctl.
2638  *
2639  * Returns:
2640  * Zero on success, negative errno on failure.
2641  */
2642 int drm_mode_setcrtc(struct drm_device *dev, void *data,
2643 		     struct drm_file *file_priv)
2644 {
2645 	struct drm_mode_config *config = &dev->mode_config;
2646 	struct drm_mode_crtc *crtc_req = data;
2647 	struct drm_crtc *crtc;
2648 	struct drm_connector **connector_set = NULL, *connector;
2649 	struct drm_framebuffer *fb = NULL;
2650 	struct drm_display_mode *mode = NULL;
2651 	struct drm_mode_set set;
2652 	uint32_t __user *set_connectors_ptr;
2653 	int ret;
2654 	int i;
2655 
2656 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
2657 		return -EINVAL;
2658 
2659 	/*
2660 	 * Universal plane src offsets are only 16.16, prevent havoc for
2661 	 * drivers using universal plane code internally.
2662 	 */
2663 	if (crtc_req->x & 0xffff0000 || crtc_req->y & 0xffff0000)
2664 		return -ERANGE;
2665 
2666 	drm_modeset_lock_all(dev);
2667 	crtc = drm_crtc_find(dev, crtc_req->crtc_id);
2668 	if (!crtc) {
2669 		DRM_DEBUG_KMS("Unknown CRTC ID %d\n", crtc_req->crtc_id);
2670 		ret = -ENOENT;
2671 		goto out;
2672 	}
2673 	DRM_DEBUG_KMS("[CRTC:%d]\n", crtc->base.id);
2674 
2675 	if (crtc_req->mode_valid) {
2676 		/* If we have a mode we need a framebuffer. */
2677 		/* If we pass -1, set the mode with the currently bound fb */
2678 		if (crtc_req->fb_id == -1) {
2679 			if (!crtc->primary->fb) {
2680 				DRM_DEBUG_KMS("CRTC doesn't have current FB\n");
2681 				ret = -EINVAL;
2682 				goto out;
2683 			}
2684 			fb = crtc->primary->fb;
2685 			/* Make refcounting symmetric with the lookup path. */
2686 			drm_framebuffer_reference(fb);
2687 		} else {
2688 			fb = drm_framebuffer_lookup(dev, crtc_req->fb_id);
2689 			if (!fb) {
2690 				DRM_DEBUG_KMS("Unknown FB ID%d\n",
2691 						crtc_req->fb_id);
2692 				ret = -ENOENT;
2693 				goto out;
2694 			}
2695 		}
2696 
2697 		mode = drm_mode_create(dev);
2698 		if (!mode) {
2699 			ret = -ENOMEM;
2700 			goto out;
2701 		}
2702 
2703 		ret = drm_mode_convert_umode(mode, &crtc_req->mode);
2704 		if (ret) {
2705 			DRM_DEBUG_KMS("Invalid mode\n");
2706 			goto out;
2707 		}
2708 
2709 		/*
2710 		 * Check whether the primary plane supports the fb pixel format.
2711 		 * Drivers not implementing the universal planes API use a
2712 		 * default formats list provided by the DRM core which doesn't
2713 		 * match real hardware capabilities. Skip the check in that
2714 		 * case.
2715 		 */
2716 		if (!crtc->primary->format_default) {
2717 			ret = drm_plane_check_pixel_format(crtc->primary,
2718 							   fb->pixel_format);
2719 			if (ret) {
2720 				DRM_DEBUG_KMS("Invalid pixel format %s\n",
2721 					drm_get_format_name(fb->pixel_format));
2722 				goto out;
2723 			}
2724 		}
2725 
2726 		ret = drm_crtc_check_viewport(crtc, crtc_req->x, crtc_req->y,
2727 					      mode, fb);
2728 		if (ret)
2729 			goto out;
2730 
2731 	}
2732 
2733 	if (crtc_req->count_connectors == 0 && mode) {
2734 		DRM_DEBUG_KMS("Count connectors is 0 but mode set\n");
2735 		ret = -EINVAL;
2736 		goto out;
2737 	}
2738 
2739 	if (crtc_req->count_connectors > 0 && (!mode || !fb)) {
2740 		DRM_DEBUG_KMS("Count connectors is %d but no mode or fb set\n",
2741 			  crtc_req->count_connectors);
2742 		ret = -EINVAL;
2743 		goto out;
2744 	}
2745 
2746 	if (crtc_req->count_connectors > 0) {
2747 		u32 out_id;
2748 
2749 		/* Avoid unbounded kernel memory allocation */
2750 		if (crtc_req->count_connectors > config->num_connector) {
2751 			ret = -EINVAL;
2752 			goto out;
2753 		}
2754 
2755 		connector_set = kmalloc_array(crtc_req->count_connectors,
2756 					      sizeof(struct drm_connector *),
2757 					      GFP_KERNEL);
2758 		if (!connector_set) {
2759 			ret = -ENOMEM;
2760 			goto out;
2761 		}
2762 
2763 		for (i = 0; i < crtc_req->count_connectors; i++) {
2764 			set_connectors_ptr = (uint32_t __user *)(unsigned long)crtc_req->set_connectors_ptr;
2765 			if (get_user(out_id, &set_connectors_ptr[i])) {
2766 				ret = -EFAULT;
2767 				goto out;
2768 			}
2769 
2770 			connector = drm_connector_find(dev, out_id);
2771 			if (!connector) {
2772 				DRM_DEBUG_KMS("Connector id %d unknown\n",
2773 						out_id);
2774 				ret = -ENOENT;
2775 				goto out;
2776 			}
2777 			DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
2778 					connector->base.id,
2779 					connector->name);
2780 
2781 			connector_set[i] = connector;
2782 		}
2783 	}
2784 
2785 	set.crtc = crtc;
2786 	set.x = crtc_req->x;
2787 	set.y = crtc_req->y;
2788 	set.mode = mode;
2789 	set.connectors = connector_set;
2790 	set.num_connectors = crtc_req->count_connectors;
2791 	set.fb = fb;
2792 	ret = drm_mode_set_config_internal(&set);
2793 
2794 out:
2795 	if (fb)
2796 		drm_framebuffer_unreference(fb);
2797 
2798 	kfree(connector_set);
2799 	drm_mode_destroy(dev, mode);
2800 	drm_modeset_unlock_all(dev);
2801 	return ret;
2802 }
2803 
2804 /**
2805  * drm_mode_cursor_universal - translate legacy cursor ioctl call into a
2806  *     universal plane handler call
2807  * @crtc: crtc to update cursor for
2808  * @req: data pointer for the ioctl
2809  * @file_priv: drm file for the ioctl call
2810  *
2811  * Legacy cursor ioctl's work directly with driver buffer handles.  To
2812  * translate legacy ioctl calls into universal plane handler calls, we need to
2813  * wrap the native buffer handle in a drm_framebuffer.
2814  *
2815  * Note that we assume any handle passed to the legacy ioctls was a 32-bit ARGB
2816  * buffer with a pitch of 4*width; the universal plane interface should be used
2817  * directly in cases where the hardware can support other buffer settings and
2818  * userspace wants to make use of these capabilities.
2819  *
2820  * Returns:
2821  * Zero on success, negative errno on failure.
2822  */
2823 static int drm_mode_cursor_universal(struct drm_crtc *crtc,
2824 				     struct drm_mode_cursor2 *req,
2825 				     struct drm_file *file_priv)
2826 {
2827 	struct drm_device *dev = crtc->dev;
2828 	struct drm_framebuffer *fb = NULL;
2829 	struct drm_mode_fb_cmd2 fbreq = {
2830 		.width = req->width,
2831 		.height = req->height,
2832 		.pixel_format = DRM_FORMAT_ARGB8888,
2833 		.pitches = { req->width * 4 },
2834 		.handles = { req->handle },
2835 	};
2836 	int32_t crtc_x, crtc_y;
2837 	uint32_t crtc_w = 0, crtc_h = 0;
2838 	uint32_t src_w = 0, src_h = 0;
2839 	int ret = 0;
2840 
2841 	BUG_ON(!crtc->cursor);
2842 	WARN_ON(crtc->cursor->crtc != crtc && crtc->cursor->crtc != NULL);
2843 
2844 	/*
2845 	 * Obtain fb we'll be using (either new or existing) and take an extra
2846 	 * reference to it if fb != null.  setplane will take care of dropping
2847 	 * the reference if the plane update fails.
2848 	 */
2849 	if (req->flags & DRM_MODE_CURSOR_BO) {
2850 		if (req->handle) {
2851 			fb = internal_framebuffer_create(dev, &fbreq, file_priv);
2852 			if (IS_ERR(fb)) {
2853 				DRM_DEBUG_KMS("failed to wrap cursor buffer in drm framebuffer\n");
2854 				return PTR_ERR(fb);
2855 			}
2856 		} else {
2857 			fb = NULL;
2858 		}
2859 	} else {
2860 		fb = crtc->cursor->fb;
2861 		if (fb)
2862 			drm_framebuffer_reference(fb);
2863 	}
2864 
2865 	if (req->flags & DRM_MODE_CURSOR_MOVE) {
2866 		crtc_x = req->x;
2867 		crtc_y = req->y;
2868 	} else {
2869 		crtc_x = crtc->cursor_x;
2870 		crtc_y = crtc->cursor_y;
2871 	}
2872 
2873 	if (fb) {
2874 		crtc_w = fb->width;
2875 		crtc_h = fb->height;
2876 		src_w = fb->width << 16;
2877 		src_h = fb->height << 16;
2878 	}
2879 
2880 	/*
2881 	 * setplane_internal will take care of deref'ing either the old or new
2882 	 * framebuffer depending on success.
2883 	 */
2884 	ret = __setplane_internal(crtc->cursor, crtc, fb,
2885 				crtc_x, crtc_y, crtc_w, crtc_h,
2886 				0, 0, src_w, src_h);
2887 
2888 	/* Update successful; save new cursor position, if necessary */
2889 	if (ret == 0 && req->flags & DRM_MODE_CURSOR_MOVE) {
2890 		crtc->cursor_x = req->x;
2891 		crtc->cursor_y = req->y;
2892 	}
2893 
2894 	return ret;
2895 }
2896 
2897 static int drm_mode_cursor_common(struct drm_device *dev,
2898 				  struct drm_mode_cursor2 *req,
2899 				  struct drm_file *file_priv)
2900 {
2901 	struct drm_crtc *crtc;
2902 	int ret = 0;
2903 
2904 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
2905 		return -EINVAL;
2906 
2907 	if (!req->flags || (~DRM_MODE_CURSOR_FLAGS & req->flags))
2908 		return -EINVAL;
2909 
2910 	crtc = drm_crtc_find(dev, req->crtc_id);
2911 	if (!crtc) {
2912 		DRM_DEBUG_KMS("Unknown CRTC ID %d\n", req->crtc_id);
2913 		return -ENOENT;
2914 	}
2915 
2916 	/*
2917 	 * If this crtc has a universal cursor plane, call that plane's update
2918 	 * handler rather than using legacy cursor handlers.
2919 	 */
2920 	drm_modeset_lock_crtc(crtc, crtc->cursor);
2921 	if (crtc->cursor) {
2922 		ret = drm_mode_cursor_universal(crtc, req, file_priv);
2923 		goto out;
2924 	}
2925 
2926 	if (req->flags & DRM_MODE_CURSOR_BO) {
2927 		if (!crtc->funcs->cursor_set && !crtc->funcs->cursor_set2) {
2928 			ret = -ENXIO;
2929 			goto out;
2930 		}
2931 		/* Turns off the cursor if handle is 0 */
2932 		if (crtc->funcs->cursor_set2)
2933 			ret = crtc->funcs->cursor_set2(crtc, file_priv, req->handle,
2934 						      req->width, req->height, req->hot_x, req->hot_y);
2935 		else
2936 			ret = crtc->funcs->cursor_set(crtc, file_priv, req->handle,
2937 						      req->width, req->height);
2938 	}
2939 
2940 	if (req->flags & DRM_MODE_CURSOR_MOVE) {
2941 		if (crtc->funcs->cursor_move) {
2942 			ret = crtc->funcs->cursor_move(crtc, req->x, req->y);
2943 		} else {
2944 			ret = -EFAULT;
2945 			goto out;
2946 		}
2947 	}
2948 out:
2949 	drm_modeset_unlock_crtc(crtc);
2950 
2951 	return ret;
2952 
2953 }
2954 
2955 
2956 /**
2957  * drm_mode_cursor_ioctl - set CRTC's cursor configuration
2958  * @dev: drm device for the ioctl
2959  * @data: data pointer for the ioctl
2960  * @file_priv: drm file for the ioctl call
2961  *
2962  * Set the cursor configuration based on user request.
2963  *
2964  * Called by the user via ioctl.
2965  *
2966  * Returns:
2967  * Zero on success, negative errno on failure.
2968  */
2969 int drm_mode_cursor_ioctl(struct drm_device *dev,
2970 			  void *data, struct drm_file *file_priv)
2971 {
2972 	struct drm_mode_cursor *req = data;
2973 	struct drm_mode_cursor2 new_req;
2974 
2975 	memcpy(&new_req, req, sizeof(struct drm_mode_cursor));
2976 	new_req.hot_x = new_req.hot_y = 0;
2977 
2978 	return drm_mode_cursor_common(dev, &new_req, file_priv);
2979 }
2980 
2981 /**
2982  * drm_mode_cursor2_ioctl - set CRTC's cursor configuration
2983  * @dev: drm device for the ioctl
2984  * @data: data pointer for the ioctl
2985  * @file_priv: drm file for the ioctl call
2986  *
2987  * Set the cursor configuration based on user request. This implements the 2nd
2988  * version of the cursor ioctl, which allows userspace to additionally specify
2989  * the hotspot of the pointer.
2990  *
2991  * Called by the user via ioctl.
2992  *
2993  * Returns:
2994  * Zero on success, negative errno on failure.
2995  */
2996 int drm_mode_cursor2_ioctl(struct drm_device *dev,
2997 			   void *data, struct drm_file *file_priv)
2998 {
2999 	struct drm_mode_cursor2 *req = data;
3000 
3001 	return drm_mode_cursor_common(dev, req, file_priv);
3002 }
3003 
3004 /**
3005  * drm_mode_legacy_fb_format - compute drm fourcc code from legacy description
3006  * @bpp: bits per pixels
3007  * @depth: bit depth per pixel
3008  *
3009  * Computes a drm fourcc pixel format code for the given @bpp/@depth values.
3010  * Useful in fbdev emulation code, since that deals in those values.
3011  */
3012 uint32_t drm_mode_legacy_fb_format(uint32_t bpp, uint32_t depth)
3013 {
3014 	uint32_t fmt;
3015 
3016 	switch (bpp) {
3017 	case 8:
3018 		fmt = DRM_FORMAT_C8;
3019 		break;
3020 	case 16:
3021 		if (depth == 15)
3022 			fmt = DRM_FORMAT_XRGB1555;
3023 		else
3024 			fmt = DRM_FORMAT_RGB565;
3025 		break;
3026 	case 24:
3027 		fmt = DRM_FORMAT_RGB888;
3028 		break;
3029 	case 32:
3030 		if (depth == 24)
3031 			fmt = DRM_FORMAT_XRGB8888;
3032 		else if (depth == 30)
3033 			fmt = DRM_FORMAT_XRGB2101010;
3034 		else
3035 			fmt = DRM_FORMAT_ARGB8888;
3036 		break;
3037 	default:
3038 		DRM_ERROR("bad bpp, assuming x8r8g8b8 pixel format\n");
3039 		fmt = DRM_FORMAT_XRGB8888;
3040 		break;
3041 	}
3042 
3043 	return fmt;
3044 }
3045 EXPORT_SYMBOL(drm_mode_legacy_fb_format);
3046 
3047 /**
3048  * drm_mode_addfb - add an FB to the graphics configuration
3049  * @dev: drm device for the ioctl
3050  * @data: data pointer for the ioctl
3051  * @file_priv: drm file for the ioctl call
3052  *
3053  * Add a new FB to the specified CRTC, given a user request. This is the
3054  * original addfb ioctl which only supported RGB formats.
3055  *
3056  * Called by the user via ioctl.
3057  *
3058  * Returns:
3059  * Zero on success, negative errno on failure.
3060  */
3061 int drm_mode_addfb(struct drm_device *dev,
3062 		   void *data, struct drm_file *file_priv)
3063 {
3064 	struct drm_mode_fb_cmd *or = data;
3065 	struct drm_mode_fb_cmd2 r = {};
3066 	int ret;
3067 
3068 	/* convert to new format and call new ioctl */
3069 	r.fb_id = or->fb_id;
3070 	r.width = or->width;
3071 	r.height = or->height;
3072 	r.pitches[0] = or->pitch;
3073 	r.pixel_format = drm_mode_legacy_fb_format(or->bpp, or->depth);
3074 	r.handles[0] = or->handle;
3075 
3076 	ret = drm_mode_addfb2(dev, &r, file_priv);
3077 	if (ret)
3078 		return ret;
3079 
3080 	or->fb_id = r.fb_id;
3081 
3082 	return 0;
3083 }
3084 
3085 static int format_check(const struct drm_mode_fb_cmd2 *r)
3086 {
3087 	uint32_t format = r->pixel_format & ~DRM_FORMAT_BIG_ENDIAN;
3088 
3089 	switch (format) {
3090 	case DRM_FORMAT_C8:
3091 	case DRM_FORMAT_RGB332:
3092 	case DRM_FORMAT_BGR233:
3093 	case DRM_FORMAT_XRGB4444:
3094 	case DRM_FORMAT_XBGR4444:
3095 	case DRM_FORMAT_RGBX4444:
3096 	case DRM_FORMAT_BGRX4444:
3097 	case DRM_FORMAT_ARGB4444:
3098 	case DRM_FORMAT_ABGR4444:
3099 	case DRM_FORMAT_RGBA4444:
3100 	case DRM_FORMAT_BGRA4444:
3101 	case DRM_FORMAT_XRGB1555:
3102 	case DRM_FORMAT_XBGR1555:
3103 	case DRM_FORMAT_RGBX5551:
3104 	case DRM_FORMAT_BGRX5551:
3105 	case DRM_FORMAT_ARGB1555:
3106 	case DRM_FORMAT_ABGR1555:
3107 	case DRM_FORMAT_RGBA5551:
3108 	case DRM_FORMAT_BGRA5551:
3109 	case DRM_FORMAT_RGB565:
3110 	case DRM_FORMAT_BGR565:
3111 	case DRM_FORMAT_RGB888:
3112 	case DRM_FORMAT_BGR888:
3113 	case DRM_FORMAT_XRGB8888:
3114 	case DRM_FORMAT_XBGR8888:
3115 	case DRM_FORMAT_RGBX8888:
3116 	case DRM_FORMAT_BGRX8888:
3117 	case DRM_FORMAT_ARGB8888:
3118 	case DRM_FORMAT_ABGR8888:
3119 	case DRM_FORMAT_RGBA8888:
3120 	case DRM_FORMAT_BGRA8888:
3121 	case DRM_FORMAT_XRGB2101010:
3122 	case DRM_FORMAT_XBGR2101010:
3123 	case DRM_FORMAT_RGBX1010102:
3124 	case DRM_FORMAT_BGRX1010102:
3125 	case DRM_FORMAT_ARGB2101010:
3126 	case DRM_FORMAT_ABGR2101010:
3127 	case DRM_FORMAT_RGBA1010102:
3128 	case DRM_FORMAT_BGRA1010102:
3129 	case DRM_FORMAT_YUYV:
3130 	case DRM_FORMAT_YVYU:
3131 	case DRM_FORMAT_UYVY:
3132 	case DRM_FORMAT_VYUY:
3133 	case DRM_FORMAT_AYUV:
3134 	case DRM_FORMAT_NV12:
3135 	case DRM_FORMAT_NV21:
3136 	case DRM_FORMAT_NV16:
3137 	case DRM_FORMAT_NV61:
3138 	case DRM_FORMAT_NV24:
3139 	case DRM_FORMAT_NV42:
3140 	case DRM_FORMAT_YUV410:
3141 	case DRM_FORMAT_YVU410:
3142 	case DRM_FORMAT_YUV411:
3143 	case DRM_FORMAT_YVU411:
3144 	case DRM_FORMAT_YUV420:
3145 	case DRM_FORMAT_YVU420:
3146 	case DRM_FORMAT_YUV422:
3147 	case DRM_FORMAT_YVU422:
3148 	case DRM_FORMAT_YUV444:
3149 	case DRM_FORMAT_YVU444:
3150 		return 0;
3151 	default:
3152 		DRM_DEBUG_KMS("invalid pixel format %s\n",
3153 			      drm_get_format_name(r->pixel_format));
3154 		return -EINVAL;
3155 	}
3156 }
3157 
3158 static int framebuffer_check(const struct drm_mode_fb_cmd2 *r)
3159 {
3160 	int ret, hsub, vsub, num_planes, i;
3161 
3162 	ret = format_check(r);
3163 	if (ret) {
3164 		DRM_DEBUG_KMS("bad framebuffer format %s\n",
3165 			      drm_get_format_name(r->pixel_format));
3166 		return ret;
3167 	}
3168 
3169 	hsub = drm_format_horz_chroma_subsampling(r->pixel_format);
3170 	vsub = drm_format_vert_chroma_subsampling(r->pixel_format);
3171 	num_planes = drm_format_num_planes(r->pixel_format);
3172 
3173 	if (r->width == 0 || r->width % hsub) {
3174 		DRM_DEBUG_KMS("bad framebuffer width %u\n", r->width);
3175 		return -EINVAL;
3176 	}
3177 
3178 	if (r->height == 0 || r->height % vsub) {
3179 		DRM_DEBUG_KMS("bad framebuffer height %u\n", r->height);
3180 		return -EINVAL;
3181 	}
3182 
3183 	for (i = 0; i < num_planes; i++) {
3184 		unsigned int width = r->width / (i != 0 ? hsub : 1);
3185 		unsigned int height = r->height / (i != 0 ? vsub : 1);
3186 		unsigned int cpp = drm_format_plane_cpp(r->pixel_format, i);
3187 
3188 		if (!r->handles[i]) {
3189 			DRM_DEBUG_KMS("no buffer object handle for plane %d\n", i);
3190 			return -EINVAL;
3191 		}
3192 
3193 		if ((uint64_t) width * cpp > UINT_MAX)
3194 			return -ERANGE;
3195 
3196 		if ((uint64_t) height * r->pitches[i] + r->offsets[i] > UINT_MAX)
3197 			return -ERANGE;
3198 
3199 		if (r->pitches[i] < width * cpp) {
3200 			DRM_DEBUG_KMS("bad pitch %u for plane %d\n", r->pitches[i], i);
3201 			return -EINVAL;
3202 		}
3203 
3204 		if (r->modifier[i] && !(r->flags & DRM_MODE_FB_MODIFIERS)) {
3205 			DRM_DEBUG_KMS("bad fb modifier %"PRIu64" for plane %d\n",
3206 				      r->modifier[i], i);
3207 			return -EINVAL;
3208 		}
3209 
3210 		/* modifier specific checks: */
3211 		switch (r->modifier[i]) {
3212 		case DRM_FORMAT_MOD_SAMSUNG_64_32_TILE:
3213 			/* NOTE: the pitch restriction may be lifted later if it turns
3214 			 * out that no hw has this restriction:
3215 			 */
3216 			if (r->pixel_format != DRM_FORMAT_NV12 ||
3217 					width % 128 || height % 32 ||
3218 					r->pitches[i] % 128) {
3219 				DRM_DEBUG_KMS("bad modifier data for plane %d\n", i);
3220 				return -EINVAL;
3221 			}
3222 			break;
3223 
3224 		default:
3225 			break;
3226 		}
3227 	}
3228 
3229 	for (i = num_planes; i < 4; i++) {
3230 		if (r->modifier[i]) {
3231 			DRM_DEBUG_KMS("non-zero modifier for unused plane %d\n", i);
3232 			return -EINVAL;
3233 		}
3234 
3235 		/* Pre-FB_MODIFIERS userspace didn't clear the structs properly. */
3236 		if (!(r->flags & DRM_MODE_FB_MODIFIERS))
3237 			continue;
3238 
3239 		if (r->handles[i]) {
3240 			DRM_DEBUG_KMS("buffer object handle for unused plane %d\n", i);
3241 			return -EINVAL;
3242 		}
3243 
3244 		if (r->pitches[i]) {
3245 			DRM_DEBUG_KMS("non-zero pitch for unused plane %d\n", i);
3246 			return -EINVAL;
3247 		}
3248 
3249 		if (r->offsets[i]) {
3250 			DRM_DEBUG_KMS("non-zero offset for unused plane %d\n", i);
3251 			return -EINVAL;
3252 		}
3253 	}
3254 
3255 	return 0;
3256 }
3257 
3258 static struct drm_framebuffer *
3259 internal_framebuffer_create(struct drm_device *dev,
3260 			    struct drm_mode_fb_cmd2 *r,
3261 			    struct drm_file *file_priv)
3262 {
3263 	struct drm_mode_config *config = &dev->mode_config;
3264 	struct drm_framebuffer *fb;
3265 	int ret;
3266 
3267 	if (r->flags & ~(DRM_MODE_FB_INTERLACED | DRM_MODE_FB_MODIFIERS)) {
3268 		DRM_DEBUG_KMS("bad framebuffer flags 0x%08x\n", r->flags);
3269 		return ERR_PTR(-EINVAL);
3270 	}
3271 
3272 	if ((config->min_width > r->width) || (r->width > config->max_width)) {
3273 		DRM_DEBUG_KMS("bad framebuffer width %d, should be >= %d && <= %d\n",
3274 			  r->width, config->min_width, config->max_width);
3275 		return ERR_PTR(-EINVAL);
3276 	}
3277 	if ((config->min_height > r->height) || (r->height > config->max_height)) {
3278 		DRM_DEBUG_KMS("bad framebuffer height %d, should be >= %d && <= %d\n",
3279 			  r->height, config->min_height, config->max_height);
3280 		return ERR_PTR(-EINVAL);
3281 	}
3282 
3283 	if (r->flags & DRM_MODE_FB_MODIFIERS &&
3284 	    !dev->mode_config.allow_fb_modifiers) {
3285 		DRM_DEBUG_KMS("driver does not support fb modifiers\n");
3286 		return ERR_PTR(-EINVAL);
3287 	}
3288 
3289 	ret = framebuffer_check(r);
3290 	if (ret)
3291 		return ERR_PTR(ret);
3292 
3293 	fb = dev->mode_config.funcs->fb_create(dev, file_priv, r);
3294 	if (IS_ERR(fb)) {
3295 		DRM_DEBUG_KMS("could not create framebuffer\n");
3296 		return fb;
3297 	}
3298 
3299 	return fb;
3300 }
3301 
3302 /**
3303  * drm_mode_addfb2 - add an FB to the graphics configuration
3304  * @dev: drm device for the ioctl
3305  * @data: data pointer for the ioctl
3306  * @file_priv: drm file for the ioctl call
3307  *
3308  * Add a new FB to the specified CRTC, given a user request with format. This is
3309  * the 2nd version of the addfb ioctl, which supports multi-planar framebuffers
3310  * and uses fourcc codes as pixel format specifiers.
3311  *
3312  * Called by the user via ioctl.
3313  *
3314  * Returns:
3315  * Zero on success, negative errno on failure.
3316  */
3317 int drm_mode_addfb2(struct drm_device *dev,
3318 		    void *data, struct drm_file *file_priv)
3319 {
3320 	struct drm_mode_fb_cmd2 *r = data;
3321 	struct drm_framebuffer *fb;
3322 
3323 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
3324 		return -EINVAL;
3325 
3326 	fb = internal_framebuffer_create(dev, r, file_priv);
3327 	if (IS_ERR(fb))
3328 		return PTR_ERR(fb);
3329 
3330 	/* Transfer ownership to the filp for reaping on close */
3331 
3332 	DRM_DEBUG_KMS("[FB:%d]\n", fb->base.id);
3333 	mutex_lock(&file_priv->fbs_lock);
3334 	r->fb_id = fb->base.id;
3335 	list_add(&fb->filp_head, &file_priv->fbs);
3336 	mutex_unlock(&file_priv->fbs_lock);
3337 
3338 	return 0;
3339 }
3340 
3341 struct drm_mode_rmfb_work {
3342 	struct work_struct work;
3343 	struct list_head fbs;
3344 };
3345 
3346 static void drm_mode_rmfb_work_fn(struct work_struct *w)
3347 {
3348 	struct drm_mode_rmfb_work *arg = container_of(w, typeof(*arg), work);
3349 
3350 	while (!list_empty(&arg->fbs)) {
3351 		struct drm_framebuffer *fb =
3352 			list_first_entry(&arg->fbs, typeof(*fb), filp_head);
3353 
3354 		list_del_init(&fb->filp_head);
3355 		drm_framebuffer_remove(fb);
3356 	}
3357 }
3358 
3359 /**
3360  * drm_mode_rmfb - remove an FB from the configuration
3361  * @dev: drm device for the ioctl
3362  * @data: data pointer for the ioctl
3363  * @file_priv: drm file for the ioctl call
3364  *
3365  * Remove the FB specified by the user.
3366  *
3367  * Called by the user via ioctl.
3368  *
3369  * Returns:
3370  * Zero on success, negative errno on failure.
3371  */
3372 int drm_mode_rmfb(struct drm_device *dev,
3373 		   void *data, struct drm_file *file_priv)
3374 {
3375 	struct drm_framebuffer *fb = NULL;
3376 	struct drm_framebuffer *fbl = NULL;
3377 	uint32_t *id = data;
3378 	int found = 0;
3379 
3380 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
3381 		return -EINVAL;
3382 
3383 	mutex_lock(&file_priv->fbs_lock);
3384 	mutex_lock(&dev->mode_config.fb_lock);
3385 	fb = __drm_framebuffer_lookup(dev, *id);
3386 	if (!fb)
3387 		goto fail_lookup;
3388 
3389 	list_for_each_entry(fbl, &file_priv->fbs, filp_head)
3390 		if (fb == fbl)
3391 			found = 1;
3392 	if (!found)
3393 		goto fail_lookup;
3394 
3395 	list_del_init(&fb->filp_head);
3396 	mutex_unlock(&dev->mode_config.fb_lock);
3397 	mutex_unlock(&file_priv->fbs_lock);
3398 
3399 	/*
3400 	 * we now own the reference that was stored in the fbs list
3401 	 *
3402 	 * drm_framebuffer_remove may fail with -EINTR on pending signals,
3403 	 * so run this in a separate stack as there's no way to correctly
3404 	 * handle this after the fb is already removed from the lookup table.
3405 	 */
3406 	if (!kref_exclusive_p(&fb->refcount)) {
3407 		struct drm_mode_rmfb_work arg;
3408 
3409 		INIT_WORK_ONSTACK(&arg.work, drm_mode_rmfb_work_fn);
3410 		INIT_LIST_HEAD(&arg.fbs);
3411 		list_add_tail(&fb->filp_head, &arg.fbs);
3412 
3413 		schedule_work(&arg.work);
3414 		flush_work(&arg.work);
3415 		destroy_work_on_stack(&arg.work);
3416 	} else
3417 		drm_framebuffer_unreference(fb);
3418 
3419 	return 0;
3420 
3421 fail_lookup:
3422 	mutex_unlock(&dev->mode_config.fb_lock);
3423 	mutex_unlock(&file_priv->fbs_lock);
3424 
3425 	return -ENOENT;
3426 }
3427 
3428 /**
3429  * drm_mode_getfb - get FB info
3430  * @dev: drm device for the ioctl
3431  * @data: data pointer for the ioctl
3432  * @file_priv: drm file for the ioctl call
3433  *
3434  * Lookup the FB given its ID and return info about it.
3435  *
3436  * Called by the user via ioctl.
3437  *
3438  * Returns:
3439  * Zero on success, negative errno on failure.
3440  */
3441 int drm_mode_getfb(struct drm_device *dev,
3442 		   void *data, struct drm_file *file_priv)
3443 {
3444 	struct drm_mode_fb_cmd *r = data;
3445 	struct drm_framebuffer *fb;
3446 	int ret;
3447 
3448 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
3449 		return -EINVAL;
3450 
3451 	fb = drm_framebuffer_lookup(dev, r->fb_id);
3452 	if (!fb)
3453 		return -ENOENT;
3454 
3455 	r->height = fb->height;
3456 	r->width = fb->width;
3457 	r->depth = fb->depth;
3458 	r->bpp = fb->bits_per_pixel;
3459 	r->pitch = fb->pitches[0];
3460 	if (fb->funcs->create_handle) {
3461 		if (file_priv->is_master || capable(CAP_SYS_ADMIN) ||
3462 		    drm_is_control_client(file_priv)) {
3463 			ret = fb->funcs->create_handle(fb, file_priv,
3464 						       &r->handle);
3465 		} else {
3466 			/* GET_FB() is an unprivileged ioctl so we must not
3467 			 * return a buffer-handle to non-master processes! For
3468 			 * backwards-compatibility reasons, we cannot make
3469 			 * GET_FB() privileged, so just return an invalid handle
3470 			 * for non-masters. */
3471 			r->handle = 0;
3472 			ret = 0;
3473 		}
3474 	} else {
3475 		ret = -ENODEV;
3476 	}
3477 
3478 	drm_framebuffer_unreference(fb);
3479 
3480 	return ret;
3481 }
3482 
3483 /**
3484  * drm_mode_dirtyfb_ioctl - flush frontbuffer rendering on an FB
3485  * @dev: drm device for the ioctl
3486  * @data: data pointer for the ioctl
3487  * @file_priv: drm file for the ioctl call
3488  *
3489  * Lookup the FB and flush out the damaged area supplied by userspace as a clip
3490  * rectangle list. Generic userspace which does frontbuffer rendering must call
3491  * this ioctl to flush out the changes on manual-update display outputs, e.g.
3492  * usb display-link, mipi manual update panels or edp panel self refresh modes.
3493  *
3494  * Modesetting drivers which always update the frontbuffer do not need to
3495  * implement the corresponding ->dirty framebuffer callback.
3496  *
3497  * Called by the user via ioctl.
3498  *
3499  * Returns:
3500  * Zero on success, negative errno on failure.
3501  */
3502 int drm_mode_dirtyfb_ioctl(struct drm_device *dev,
3503 			   void *data, struct drm_file *file_priv)
3504 {
3505 	struct drm_clip_rect __user *clips_ptr;
3506 	struct drm_clip_rect *clips = NULL;
3507 	struct drm_mode_fb_dirty_cmd *r = data;
3508 	struct drm_framebuffer *fb;
3509 	unsigned flags;
3510 	int num_clips;
3511 	int ret;
3512 
3513 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
3514 		return -EINVAL;
3515 
3516 	fb = drm_framebuffer_lookup(dev, r->fb_id);
3517 	if (!fb)
3518 		return -ENOENT;
3519 
3520 	num_clips = r->num_clips;
3521 	clips_ptr = (struct drm_clip_rect __user *)(unsigned long)r->clips_ptr;
3522 
3523 	if (!num_clips != !clips_ptr) {
3524 		ret = -EINVAL;
3525 		goto out_err1;
3526 	}
3527 
3528 	flags = DRM_MODE_FB_DIRTY_FLAGS & r->flags;
3529 
3530 	/* If userspace annotates copy, clips must come in pairs */
3531 	if (flags & DRM_MODE_FB_DIRTY_ANNOTATE_COPY && (num_clips % 2)) {
3532 		ret = -EINVAL;
3533 		goto out_err1;
3534 	}
3535 
3536 	if (num_clips && clips_ptr) {
3537 		if (num_clips < 0 || num_clips > DRM_MODE_FB_DIRTY_MAX_CLIPS) {
3538 			ret = -EINVAL;
3539 			goto out_err1;
3540 		}
3541 		clips = kcalloc(num_clips, sizeof(*clips), GFP_KERNEL);
3542 		if (!clips) {
3543 			ret = -ENOMEM;
3544 			goto out_err1;
3545 		}
3546 
3547 		ret = copy_from_user(clips, clips_ptr,
3548 				     num_clips * sizeof(*clips));
3549 		if (ret) {
3550 			ret = -EFAULT;
3551 			goto out_err2;
3552 		}
3553 	}
3554 
3555 	if (fb->funcs->dirty) {
3556 		ret = fb->funcs->dirty(fb, file_priv, flags, r->color,
3557 				       clips, num_clips);
3558 	} else {
3559 		ret = -ENOSYS;
3560 	}
3561 
3562 out_err2:
3563 	kfree(clips);
3564 out_err1:
3565 	drm_framebuffer_unreference(fb);
3566 
3567 	return ret;
3568 }
3569 
3570 /**
3571  * drm_fb_release - remove and free the FBs on this file
3572  * @priv: drm file for the ioctl
3573  *
3574  * Destroy all the FBs associated with @filp.
3575  *
3576  * Called by the user via ioctl.
3577  *
3578  * Returns:
3579  * Zero on success, negative errno on failure.
3580  */
3581 void drm_fb_release(struct drm_file *priv)
3582 {
3583 	struct drm_framebuffer *fb, *tfb;
3584 	struct drm_mode_rmfb_work arg;
3585 
3586 	INIT_LIST_HEAD(&arg.fbs);
3587 
3588 	/*
3589 	 * When the file gets released that means no one else can access the fb
3590 	 * list any more, so no need to grab fpriv->fbs_lock. And we need to
3591 	 * avoid upsetting lockdep since the universal cursor code adds a
3592 	 * framebuffer while holding mutex locks.
3593 	 *
3594 	 * Note that a real deadlock between fpriv->fbs_lock and the modeset
3595 	 * locks is impossible here since no one else but this function can get
3596 	 * at it any more.
3597 	 */
3598 	list_for_each_entry_safe(fb, tfb, &priv->fbs, filp_head) {
3599 		if (!kref_exclusive_p(&fb->refcount)) {
3600 			list_move_tail(&fb->filp_head, &arg.fbs);
3601 		} else {
3602 			list_del_init(&fb->filp_head);
3603 
3604 			/* This drops the fpriv->fbs reference. */
3605 			drm_framebuffer_unreference(fb);
3606 		}
3607 	}
3608 
3609 	if (!list_empty(&arg.fbs)) {
3610 		INIT_WORK_ONSTACK(&arg.work, drm_mode_rmfb_work_fn);
3611 
3612 		schedule_work(&arg.work);
3613 		flush_work(&arg.work);
3614 		destroy_work_on_stack(&arg.work);
3615 	}
3616 }
3617 
3618 /**
3619  * drm_property_create - create a new property type
3620  * @dev: drm device
3621  * @flags: flags specifying the property type
3622  * @name: name of the property
3623  * @num_values: number of pre-defined values
3624  *
3625  * This creates a new generic drm property which can then be attached to a drm
3626  * object with drm_object_attach_property. The returned property object must be
3627  * freed with drm_property_destroy.
3628  *
3629  * Note that the DRM core keeps a per-device list of properties and that, if
3630  * drm_mode_config_cleanup() is called, it will destroy all properties created
3631  * by the driver.
3632  *
3633  * Returns:
3634  * A pointer to the newly created property on success, NULL on failure.
3635  */
3636 struct drm_property *drm_property_create(struct drm_device *dev, int flags,
3637 					 const char *name, int num_values)
3638 {
3639 	struct drm_property *property = NULL;
3640 	int ret;
3641 
3642 	property = kzalloc(sizeof(struct drm_property), GFP_KERNEL);
3643 	if (!property)
3644 		return NULL;
3645 
3646 	property->dev = dev;
3647 
3648 	if (num_values) {
3649 		property->values = kcalloc(num_values, sizeof(uint64_t),
3650 					   GFP_KERNEL);
3651 		if (!property->values)
3652 			goto fail;
3653 	}
3654 
3655 	ret = drm_mode_object_get(dev, &property->base, DRM_MODE_OBJECT_PROPERTY);
3656 	if (ret)
3657 		goto fail;
3658 
3659 	property->flags = flags;
3660 	property->num_values = num_values;
3661 	INIT_LIST_HEAD(&property->enum_list);
3662 
3663 	if (name) {
3664 		strncpy(property->name, name, DRM_PROP_NAME_LEN);
3665 		property->name[DRM_PROP_NAME_LEN-1] = '\0';
3666 	}
3667 
3668 	list_add_tail(&property->head, &dev->mode_config.property_list);
3669 
3670 	WARN_ON(!drm_property_type_valid(property));
3671 
3672 	return property;
3673 fail:
3674 	kfree(property->values);
3675 	kfree(property);
3676 	return NULL;
3677 }
3678 EXPORT_SYMBOL(drm_property_create);
3679 
3680 /**
3681  * drm_property_create_enum - create a new enumeration property type
3682  * @dev: drm device
3683  * @flags: flags specifying the property type
3684  * @name: name of the property
3685  * @props: enumeration lists with property values
3686  * @num_values: number of pre-defined values
3687  *
3688  * This creates a new generic drm property which can then be attached to a drm
3689  * object with drm_object_attach_property. The returned property object must be
3690  * freed with drm_property_destroy.
3691  *
3692  * Userspace is only allowed to set one of the predefined values for enumeration
3693  * properties.
3694  *
3695  * Returns:
3696  * A pointer to the newly created property on success, NULL on failure.
3697  */
3698 struct drm_property *drm_property_create_enum(struct drm_device *dev, int flags,
3699 					 const char *name,
3700 					 const struct drm_prop_enum_list *props,
3701 					 int num_values)
3702 {
3703 	struct drm_property *property;
3704 	int i, ret;
3705 
3706 	flags |= DRM_MODE_PROP_ENUM;
3707 
3708 	property = drm_property_create(dev, flags, name, num_values);
3709 	if (!property)
3710 		return NULL;
3711 
3712 	for (i = 0; i < num_values; i++) {
3713 		ret = drm_property_add_enum(property, i,
3714 				      props[i].type,
3715 				      props[i].name);
3716 		if (ret) {
3717 			drm_property_destroy(dev, property);
3718 			return NULL;
3719 		}
3720 	}
3721 
3722 	return property;
3723 }
3724 EXPORT_SYMBOL(drm_property_create_enum);
3725 
3726 /**
3727  * drm_property_create_bitmask - create a new bitmask property type
3728  * @dev: drm device
3729  * @flags: flags specifying the property type
3730  * @name: name of the property
3731  * @props: enumeration lists with property bitflags
3732  * @num_props: size of the @props array
3733  * @supported_bits: bitmask of all supported enumeration values
3734  *
3735  * This creates a new bitmask drm property which can then be attached to a drm
3736  * object with drm_object_attach_property. The returned property object must be
3737  * freed with drm_property_destroy.
3738  *
3739  * Compared to plain enumeration properties userspace is allowed to set any
3740  * or'ed together combination of the predefined property bitflag values
3741  *
3742  * Returns:
3743  * A pointer to the newly created property on success, NULL on failure.
3744  */
3745 struct drm_property *drm_property_create_bitmask(struct drm_device *dev,
3746 					 int flags, const char *name,
3747 					 const struct drm_prop_enum_list *props,
3748 					 int num_props,
3749 					 uint64_t supported_bits)
3750 {
3751 	struct drm_property *property;
3752 	int i, ret, index = 0;
3753 	int num_values = hweight64(supported_bits);
3754 
3755 	flags |= DRM_MODE_PROP_BITMASK;
3756 
3757 	property = drm_property_create(dev, flags, name, num_values);
3758 	if (!property)
3759 		return NULL;
3760 	for (i = 0; i < num_props; i++) {
3761 		if (!(supported_bits & (1ULL << props[i].type)))
3762 			continue;
3763 
3764 		if (WARN_ON(index >= num_values)) {
3765 			drm_property_destroy(dev, property);
3766 			return NULL;
3767 		}
3768 
3769 		ret = drm_property_add_enum(property, index++,
3770 				      props[i].type,
3771 				      props[i].name);
3772 		if (ret) {
3773 			drm_property_destroy(dev, property);
3774 			return NULL;
3775 		}
3776 	}
3777 
3778 	return property;
3779 }
3780 EXPORT_SYMBOL(drm_property_create_bitmask);
3781 
3782 static struct drm_property *property_create_range(struct drm_device *dev,
3783 					 int flags, const char *name,
3784 					 uint64_t min, uint64_t max)
3785 {
3786 	struct drm_property *property;
3787 
3788 	property = drm_property_create(dev, flags, name, 2);
3789 	if (!property)
3790 		return NULL;
3791 
3792 	property->values[0] = min;
3793 	property->values[1] = max;
3794 
3795 	return property;
3796 }
3797 
3798 /**
3799  * drm_property_create_range - create a new unsigned ranged property type
3800  * @dev: drm device
3801  * @flags: flags specifying the property type
3802  * @name: name of the property
3803  * @min: minimum value of the property
3804  * @max: maximum value of the property
3805  *
3806  * This creates a new generic drm property which can then be attached to a drm
3807  * object with drm_object_attach_property. The returned property object must be
3808  * freed with drm_property_destroy.
3809  *
3810  * Userspace is allowed to set any unsigned integer value in the (min, max)
3811  * range inclusive.
3812  *
3813  * Returns:
3814  * A pointer to the newly created property on success, NULL on failure.
3815  */
3816 struct drm_property *drm_property_create_range(struct drm_device *dev, int flags,
3817 					 const char *name,
3818 					 uint64_t min, uint64_t max)
3819 {
3820 	return property_create_range(dev, DRM_MODE_PROP_RANGE | flags,
3821 			name, min, max);
3822 }
3823 EXPORT_SYMBOL(drm_property_create_range);
3824 
3825 /**
3826  * drm_property_create_signed_range - create a new signed ranged property type
3827  * @dev: drm device
3828  * @flags: flags specifying the property type
3829  * @name: name of the property
3830  * @min: minimum value of the property
3831  * @max: maximum value of the property
3832  *
3833  * This creates a new generic drm property which can then be attached to a drm
3834  * object with drm_object_attach_property. The returned property object must be
3835  * freed with drm_property_destroy.
3836  *
3837  * Userspace is allowed to set any signed integer value in the (min, max)
3838  * range inclusive.
3839  *
3840  * Returns:
3841  * A pointer to the newly created property on success, NULL on failure.
3842  */
3843 struct drm_property *drm_property_create_signed_range(struct drm_device *dev,
3844 					 int flags, const char *name,
3845 					 int64_t min, int64_t max)
3846 {
3847 	return property_create_range(dev, DRM_MODE_PROP_SIGNED_RANGE | flags,
3848 			name, I642U64(min), I642U64(max));
3849 }
3850 EXPORT_SYMBOL(drm_property_create_signed_range);
3851 
3852 /**
3853  * drm_property_create_object - create a new object property type
3854  * @dev: drm device
3855  * @flags: flags specifying the property type
3856  * @name: name of the property
3857  * @type: object type from DRM_MODE_OBJECT_* defines
3858  *
3859  * This creates a new generic drm property which can then be attached to a drm
3860  * object with drm_object_attach_property. The returned property object must be
3861  * freed with drm_property_destroy.
3862  *
3863  * Userspace is only allowed to set this to any property value of the given
3864  * @type. Only useful for atomic properties, which is enforced.
3865  *
3866  * Returns:
3867  * A pointer to the newly created property on success, NULL on failure.
3868  */
3869 struct drm_property *drm_property_create_object(struct drm_device *dev,
3870 					 int flags, const char *name, uint32_t type)
3871 {
3872 	struct drm_property *property;
3873 
3874 	flags |= DRM_MODE_PROP_OBJECT;
3875 
3876 	if (WARN_ON(!(flags & DRM_MODE_PROP_ATOMIC)))
3877 		return NULL;
3878 
3879 	property = drm_property_create(dev, flags, name, 1);
3880 	if (!property)
3881 		return NULL;
3882 
3883 	property->values[0] = type;
3884 
3885 	return property;
3886 }
3887 EXPORT_SYMBOL(drm_property_create_object);
3888 
3889 /**
3890  * drm_property_create_bool - create a new boolean property type
3891  * @dev: drm device
3892  * @flags: flags specifying the property type
3893  * @name: name of the property
3894  *
3895  * This creates a new generic drm property which can then be attached to a drm
3896  * object with drm_object_attach_property. The returned property object must be
3897  * freed with drm_property_destroy.
3898  *
3899  * This is implemented as a ranged property with only {0, 1} as valid values.
3900  *
3901  * Returns:
3902  * A pointer to the newly created property on success, NULL on failure.
3903  */
3904 struct drm_property *drm_property_create_bool(struct drm_device *dev, int flags,
3905 					 const char *name)
3906 {
3907 	return drm_property_create_range(dev, flags, name, 0, 1);
3908 }
3909 EXPORT_SYMBOL(drm_property_create_bool);
3910 
3911 /**
3912  * drm_property_add_enum - add a possible value to an enumeration property
3913  * @property: enumeration property to change
3914  * @index: index of the new enumeration
3915  * @value: value of the new enumeration
3916  * @name: symbolic name of the new enumeration
3917  *
3918  * This functions adds enumerations to a property.
3919  *
3920  * It's use is deprecated, drivers should use one of the more specific helpers
3921  * to directly create the property with all enumerations already attached.
3922  *
3923  * Returns:
3924  * Zero on success, error code on failure.
3925  */
3926 int drm_property_add_enum(struct drm_property *property, int index,
3927 			  uint64_t value, const char *name)
3928 {
3929 	struct drm_property_enum *prop_enum;
3930 
3931 	if (!(drm_property_type_is(property, DRM_MODE_PROP_ENUM) ||
3932 			drm_property_type_is(property, DRM_MODE_PROP_BITMASK)))
3933 		return -EINVAL;
3934 
3935 	/*
3936 	 * Bitmask enum properties have the additional constraint of values
3937 	 * from 0 to 63
3938 	 */
3939 	if (drm_property_type_is(property, DRM_MODE_PROP_BITMASK) &&
3940 			(value > 63))
3941 		return -EINVAL;
3942 
3943 	if (!list_empty(&property->enum_list)) {
3944 		list_for_each_entry(prop_enum, &property->enum_list, head) {
3945 			if (prop_enum->value == value) {
3946 				strncpy(prop_enum->name, name, DRM_PROP_NAME_LEN);
3947 				prop_enum->name[DRM_PROP_NAME_LEN-1] = '\0';
3948 				return 0;
3949 			}
3950 		}
3951 	}
3952 
3953 	prop_enum = kzalloc(sizeof(struct drm_property_enum), GFP_KERNEL);
3954 	if (!prop_enum)
3955 		return -ENOMEM;
3956 
3957 	strncpy(prop_enum->name, name, DRM_PROP_NAME_LEN);
3958 	prop_enum->name[DRM_PROP_NAME_LEN-1] = '\0';
3959 	prop_enum->value = value;
3960 
3961 	property->values[index] = value;
3962 	list_add_tail(&prop_enum->head, &property->enum_list);
3963 	return 0;
3964 }
3965 EXPORT_SYMBOL(drm_property_add_enum);
3966 
3967 /**
3968  * drm_property_destroy - destroy a drm property
3969  * @dev: drm device
3970  * @property: property to destry
3971  *
3972  * This function frees a property including any attached resources like
3973  * enumeration values.
3974  */
3975 void drm_property_destroy(struct drm_device *dev, struct drm_property *property)
3976 {
3977 	struct drm_property_enum *prop_enum, *pt;
3978 
3979 	list_for_each_entry_safe(prop_enum, pt, &property->enum_list, head) {
3980 		list_del(&prop_enum->head);
3981 		kfree(prop_enum);
3982 	}
3983 
3984 	if (property->num_values)
3985 		kfree(property->values);
3986 	drm_mode_object_put(dev, &property->base);
3987 	list_del(&property->head);
3988 	kfree(property);
3989 }
3990 EXPORT_SYMBOL(drm_property_destroy);
3991 
3992 /**
3993  * drm_object_attach_property - attach a property to a modeset object
3994  * @obj: drm modeset object
3995  * @property: property to attach
3996  * @init_val: initial value of the property
3997  *
3998  * This attaches the given property to the modeset object with the given initial
3999  * value. Currently this function cannot fail since the properties are stored in
4000  * a statically sized array.
4001  */
4002 void drm_object_attach_property(struct drm_mode_object *obj,
4003 				struct drm_property *property,
4004 				uint64_t init_val)
4005 {
4006 	int count = obj->properties->count;
4007 
4008 	if (count == DRM_OBJECT_MAX_PROPERTY) {
4009 		WARN(1, "Failed to attach object property (type: 0x%x). Please "
4010 			"increase DRM_OBJECT_MAX_PROPERTY by 1 for each time "
4011 			"you see this message on the same object type.\n",
4012 			obj->type);
4013 		return;
4014 	}
4015 
4016 	obj->properties->properties[count] = property;
4017 	obj->properties->values[count] = init_val;
4018 	obj->properties->count++;
4019 	if (property->flags & DRM_MODE_PROP_ATOMIC)
4020 		obj->properties->atomic_count++;
4021 }
4022 EXPORT_SYMBOL(drm_object_attach_property);
4023 
4024 /**
4025  * drm_object_property_set_value - set the value of a property
4026  * @obj: drm mode object to set property value for
4027  * @property: property to set
4028  * @val: value the property should be set to
4029  *
4030  * This functions sets a given property on a given object. This function only
4031  * changes the software state of the property, it does not call into the
4032  * driver's ->set_property callback.
4033  *
4034  * Returns:
4035  * Zero on success, error code on failure.
4036  */
4037 int drm_object_property_set_value(struct drm_mode_object *obj,
4038 				  struct drm_property *property, uint64_t val)
4039 {
4040 	int i;
4041 
4042 	for (i = 0; i < obj->properties->count; i++) {
4043 		if (obj->properties->properties[i] == property) {
4044 			obj->properties->values[i] = val;
4045 			return 0;
4046 		}
4047 	}
4048 
4049 	return -EINVAL;
4050 }
4051 EXPORT_SYMBOL(drm_object_property_set_value);
4052 
4053 /**
4054  * drm_object_property_get_value - retrieve the value of a property
4055  * @obj: drm mode object to get property value from
4056  * @property: property to retrieve
4057  * @val: storage for the property value
4058  *
4059  * This function retrieves the softare state of the given property for the given
4060  * property. Since there is no driver callback to retrieve the current property
4061  * value this might be out of sync with the hardware, depending upon the driver
4062  * and property.
4063  *
4064  * Returns:
4065  * Zero on success, error code on failure.
4066  */
4067 int drm_object_property_get_value(struct drm_mode_object *obj,
4068 				  struct drm_property *property, uint64_t *val)
4069 {
4070 	int i;
4071 
4072 	/* read-only properties bypass atomic mechanism and still store
4073 	 * their value in obj->properties->values[].. mostly to avoid
4074 	 * having to deal w/ EDID and similar props in atomic paths:
4075 	 */
4076 	if (drm_core_check_feature(property->dev, DRIVER_ATOMIC) &&
4077 			!(property->flags & DRM_MODE_PROP_IMMUTABLE))
4078 		return drm_atomic_get_property(obj, property, val);
4079 
4080 	for (i = 0; i < obj->properties->count; i++) {
4081 		if (obj->properties->properties[i] == property) {
4082 			*val = obj->properties->values[i];
4083 			return 0;
4084 		}
4085 	}
4086 
4087 	return -EINVAL;
4088 }
4089 EXPORT_SYMBOL(drm_object_property_get_value);
4090 
4091 /**
4092  * drm_mode_getproperty_ioctl - get the property metadata
4093  * @dev: DRM device
4094  * @data: ioctl data
4095  * @file_priv: DRM file info
4096  *
4097  * This function retrieves the metadata for a given property, like the different
4098  * possible values for an enum property or the limits for a range property.
4099  *
4100  * Blob properties are special
4101  *
4102  * Called by the user via ioctl.
4103  *
4104  * Returns:
4105  * Zero on success, negative errno on failure.
4106  */
4107 int drm_mode_getproperty_ioctl(struct drm_device *dev,
4108 			       void *data, struct drm_file *file_priv)
4109 {
4110 	struct drm_mode_get_property *out_resp = data;
4111 	struct drm_property *property;
4112 	int enum_count = 0;
4113 	int value_count = 0;
4114 	int ret = 0, i;
4115 	int copied;
4116 	struct drm_property_enum *prop_enum;
4117 	struct drm_mode_property_enum __user *enum_ptr;
4118 	uint64_t __user *values_ptr;
4119 
4120 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
4121 		return -EINVAL;
4122 
4123 	drm_modeset_lock_all(dev);
4124 	property = drm_property_find(dev, out_resp->prop_id);
4125 	if (!property) {
4126 		ret = -ENOENT;
4127 		goto done;
4128 	}
4129 
4130 	if (drm_property_type_is(property, DRM_MODE_PROP_ENUM) ||
4131 			drm_property_type_is(property, DRM_MODE_PROP_BITMASK)) {
4132 		list_for_each_entry(prop_enum, &property->enum_list, head)
4133 			enum_count++;
4134 	}
4135 
4136 	value_count = property->num_values;
4137 
4138 	strncpy(out_resp->name, property->name, DRM_PROP_NAME_LEN);
4139 	out_resp->name[DRM_PROP_NAME_LEN-1] = 0;
4140 	out_resp->flags = property->flags;
4141 
4142 	if ((out_resp->count_values >= value_count) && value_count) {
4143 		values_ptr = (uint64_t __user *)(unsigned long)out_resp->values_ptr;
4144 		for (i = 0; i < value_count; i++) {
4145 			if (copy_to_user(values_ptr + i, &property->values[i], sizeof(uint64_t))) {
4146 				ret = -EFAULT;
4147 				goto done;
4148 			}
4149 		}
4150 	}
4151 	out_resp->count_values = value_count;
4152 
4153 	if (drm_property_type_is(property, DRM_MODE_PROP_ENUM) ||
4154 			drm_property_type_is(property, DRM_MODE_PROP_BITMASK)) {
4155 		if ((out_resp->count_enum_blobs >= enum_count) && enum_count) {
4156 			copied = 0;
4157 			enum_ptr = (struct drm_mode_property_enum __user *)(unsigned long)out_resp->enum_blob_ptr;
4158 			list_for_each_entry(prop_enum, &property->enum_list, head) {
4159 
4160 				if (copy_to_user(&enum_ptr[copied].value, &prop_enum->value, sizeof(uint64_t))) {
4161 					ret = -EFAULT;
4162 					goto done;
4163 				}
4164 
4165 				if (copy_to_user(&enum_ptr[copied].name,
4166 						 &prop_enum->name, DRM_PROP_NAME_LEN)) {
4167 					ret = -EFAULT;
4168 					goto done;
4169 				}
4170 				copied++;
4171 			}
4172 		}
4173 		out_resp->count_enum_blobs = enum_count;
4174 	}
4175 
4176 	/*
4177 	 * NOTE: The idea seems to have been to use this to read all the blob
4178 	 * property values. But nothing ever added them to the corresponding
4179 	 * list, userspace always used the special-purpose get_blob ioctl to
4180 	 * read the value for a blob property. It also doesn't make a lot of
4181 	 * sense to return values here when everything else is just metadata for
4182 	 * the property itself.
4183 	 */
4184 	if (drm_property_type_is(property, DRM_MODE_PROP_BLOB))
4185 		out_resp->count_enum_blobs = 0;
4186 done:
4187 	drm_modeset_unlock_all(dev);
4188 	return ret;
4189 }
4190 
4191 /**
4192  * drm_property_create_blob - Create new blob property
4193  *
4194  * Creates a new blob property for a specified DRM device, optionally
4195  * copying data.
4196  *
4197  * @dev: DRM device to create property for
4198  * @length: Length to allocate for blob data
4199  * @data: If specified, copies data into blob
4200  *
4201  * Returns:
4202  * New blob property with a single reference on success, or an ERR_PTR
4203  * value on failure.
4204  */
4205 struct drm_property_blob *
4206 drm_property_create_blob(struct drm_device *dev, size_t length,
4207 			 const void *data)
4208 {
4209 	struct drm_property_blob *blob;
4210 	int ret;
4211 
4212 	if (!length || length > ULONG_MAX - sizeof(struct drm_property_blob))
4213 		return ERR_PTR(-EINVAL);
4214 
4215 	blob = kzalloc(sizeof(struct drm_property_blob)+length, GFP_KERNEL);
4216 	if (!blob)
4217 		return ERR_PTR(-ENOMEM);
4218 
4219 	/* This must be explicitly initialised, so we can safely call list_del
4220 	 * on it in the removal handler, even if it isn't in a file list. */
4221 	INIT_LIST_HEAD(&blob->head_file);
4222 	blob->length = length;
4223 	blob->dev = dev;
4224 
4225 	if (data)
4226 		memcpy(blob->data, data, length);
4227 
4228 	mutex_lock(&dev->mode_config.blob_lock);
4229 
4230 	ret = drm_mode_object_get(dev, &blob->base, DRM_MODE_OBJECT_BLOB);
4231 	if (ret) {
4232 		kfree(blob);
4233 		mutex_unlock(&dev->mode_config.blob_lock);
4234 		return ERR_PTR(-EINVAL);
4235 	}
4236 
4237 	kref_init(&blob->refcount);
4238 
4239 	list_add_tail(&blob->head_global,
4240 	              &dev->mode_config.property_blob_list);
4241 
4242 	mutex_unlock(&dev->mode_config.blob_lock);
4243 
4244 	return blob;
4245 }
4246 EXPORT_SYMBOL(drm_property_create_blob);
4247 
4248 /**
4249  * drm_property_free_blob - Blob property destructor
4250  *
4251  * Internal free function for blob properties; must not be used directly.
4252  *
4253  * @kref: Reference
4254  */
4255 static void drm_property_free_blob(struct kref *kref)
4256 {
4257 	struct drm_property_blob *blob =
4258 		container_of(kref, struct drm_property_blob, refcount);
4259 
4260 	WARN_ON(!mutex_is_locked(&blob->dev->mode_config.blob_lock));
4261 
4262 	list_del(&blob->head_global);
4263 	list_del(&blob->head_file);
4264 	drm_mode_object_put(blob->dev, &blob->base);
4265 
4266 	kfree(blob);
4267 }
4268 
4269 /**
4270  * drm_property_unreference_blob - Unreference a blob property
4271  *
4272  * Drop a reference on a blob property. May free the object.
4273  *
4274  * @blob: Pointer to blob property
4275  */
4276 void drm_property_unreference_blob(struct drm_property_blob *blob)
4277 {
4278 	struct drm_device *dev;
4279 
4280 	if (!blob)
4281 		return;
4282 
4283 	dev = blob->dev;
4284 
4285 	DRM_DEBUG("%p: blob ID: %d (%d)\n", blob, blob->base.id, blob->refcount.kr_count);
4286 
4287 	if (kref_put_mutex(&blob->refcount, drm_property_free_blob,
4288 			   &dev->mode_config.blob_lock))
4289 		mutex_unlock(&dev->mode_config.blob_lock);
4290 	else
4291 		might_lock(&dev->mode_config.blob_lock);
4292 }
4293 EXPORT_SYMBOL(drm_property_unreference_blob);
4294 
4295 /**
4296  * drm_property_unreference_blob_locked - Unreference a blob property with blob_lock held
4297  *
4298  * Drop a reference on a blob property. May free the object. This must be
4299  * called with blob_lock held.
4300  *
4301  * @blob: Pointer to blob property
4302  */
4303 static void drm_property_unreference_blob_locked(struct drm_property_blob *blob)
4304 {
4305 	if (!blob)
4306 		return;
4307 
4308 	DRM_DEBUG("%p: blob ID: %d (%d)\n", blob, blob->base.id, blob->refcount.kr_count);
4309 
4310 	kref_put(&blob->refcount, drm_property_free_blob);
4311 }
4312 
4313 /**
4314  * drm_property_destroy_user_blobs - destroy all blobs created by this client
4315  * @dev:       DRM device
4316  * @file_priv: destroy all blobs owned by this file handle
4317  */
4318 void drm_property_destroy_user_blobs(struct drm_device *dev,
4319 				     struct drm_file *file_priv)
4320 {
4321 	struct drm_property_blob *blob, *bt;
4322 
4323 	mutex_lock(&dev->mode_config.blob_lock);
4324 
4325 	list_for_each_entry_safe(blob, bt, &file_priv->blobs, head_file) {
4326 		list_del_init(&blob->head_file);
4327 		drm_property_unreference_blob_locked(blob);
4328 	}
4329 
4330 	mutex_unlock(&dev->mode_config.blob_lock);
4331 }
4332 
4333 /**
4334  * drm_property_reference_blob - Take a reference on an existing property
4335  *
4336  * Take a new reference on an existing blob property.
4337  *
4338  * @blob: Pointer to blob property
4339  */
4340 struct drm_property_blob *drm_property_reference_blob(struct drm_property_blob *blob)
4341 {
4342 	DRM_DEBUG("%p: blob ID: %d (%d)\n", blob, blob->base.id, blob->refcount.kr_count);
4343 	kref_get(&blob->refcount);
4344 	return blob;
4345 }
4346 EXPORT_SYMBOL(drm_property_reference_blob);
4347 
4348 /*
4349  * Like drm_property_lookup_blob, but does not return an additional reference.
4350  * Must be called with blob_lock held.
4351  */
4352 static struct drm_property_blob *__drm_property_lookup_blob(struct drm_device *dev,
4353 							    uint32_t id)
4354 {
4355 	struct drm_mode_object *obj = NULL;
4356 	struct drm_property_blob *blob;
4357 
4358 	WARN_ON(!mutex_is_locked(&dev->mode_config.blob_lock));
4359 
4360 	mutex_lock(&dev->mode_config.idr_mutex);
4361 	obj = idr_find(&dev->mode_config.crtc_idr, id);
4362 	if (!obj || (obj->type != DRM_MODE_OBJECT_BLOB) || (obj->id != id))
4363 		blob = NULL;
4364 	else
4365 		blob = obj_to_blob(obj);
4366 	mutex_unlock(&dev->mode_config.idr_mutex);
4367 
4368 	return blob;
4369 }
4370 
4371 /**
4372  * drm_property_lookup_blob - look up a blob property and take a reference
4373  * @dev: drm device
4374  * @id: id of the blob property
4375  *
4376  * If successful, this takes an additional reference to the blob property.
4377  * callers need to make sure to eventually unreference the returned property
4378  * again, using @drm_property_unreference_blob.
4379  */
4380 struct drm_property_blob *drm_property_lookup_blob(struct drm_device *dev,
4381 					           uint32_t id)
4382 {
4383 	struct drm_property_blob *blob;
4384 
4385 	mutex_lock(&dev->mode_config.blob_lock);
4386 	blob = __drm_property_lookup_blob(dev, id);
4387 	if (blob) {
4388 		if (!kref_get_unless_zero(&blob->refcount))
4389 			blob = NULL;
4390 	}
4391 	mutex_unlock(&dev->mode_config.blob_lock);
4392 
4393 	return blob;
4394 }
4395 EXPORT_SYMBOL(drm_property_lookup_blob);
4396 
4397 /**
4398  * drm_property_replace_global_blob - atomically replace existing blob property
4399  * @dev: drm device
4400  * @replace: location of blob property pointer to be replaced
4401  * @length: length of data for new blob, or 0 for no data
4402  * @data: content for new blob, or NULL for no data
4403  * @obj_holds_id: optional object for property holding blob ID
4404  * @prop_holds_id: optional property holding blob ID
4405  * @return 0 on success or error on failure
4406  *
4407  * This function will atomically replace a global property in the blob list,
4408  * optionally updating a property which holds the ID of that property. It is
4409  * guaranteed to be atomic: no caller will be allowed to see intermediate
4410  * results, and either the entire operation will succeed and clean up the
4411  * previous property, or it will fail and the state will be unchanged.
4412  *
4413  * If length is 0 or data is NULL, no new blob will be created, and the holding
4414  * property, if specified, will be set to 0.
4415  *
4416  * Access to the replace pointer is assumed to be protected by the caller, e.g.
4417  * by holding the relevant modesetting object lock for its parent.
4418  *
4419  * For example, a drm_connector has a 'PATH' property, which contains the ID
4420  * of a blob property with the value of the MST path information. Calling this
4421  * function with replace pointing to the connector's path_blob_ptr, length and
4422  * data set for the new path information, obj_holds_id set to the connector's
4423  * base object, and prop_holds_id set to the path property name, will perform
4424  * a completely atomic update. The access to path_blob_ptr is protected by the
4425  * caller holding a lock on the connector.
4426  */
4427 static int drm_property_replace_global_blob(struct drm_device *dev,
4428                                             struct drm_property_blob **replace,
4429                                             size_t length,
4430                                             const void *data,
4431                                             struct drm_mode_object *obj_holds_id,
4432                                             struct drm_property *prop_holds_id)
4433 {
4434 	struct drm_property_blob *new_blob = NULL;
4435 	struct drm_property_blob *old_blob = NULL;
4436 	int ret;
4437 
4438 	WARN_ON(replace == NULL);
4439 
4440 	old_blob = *replace;
4441 
4442 	if (length && data) {
4443 		new_blob = drm_property_create_blob(dev, length, data);
4444 		if (IS_ERR(new_blob))
4445 			return PTR_ERR(new_blob);
4446 	}
4447 
4448 	/* This does not need to be synchronised with blob_lock, as the
4449 	 * get_properties ioctl locks all modesetting objects, and
4450 	 * obj_holds_id must be locked before calling here, so we cannot
4451 	 * have its value out of sync with the list membership modified
4452 	 * below under blob_lock. */
4453 	if (obj_holds_id) {
4454 		ret = drm_object_property_set_value(obj_holds_id,
4455 						    prop_holds_id,
4456 						    new_blob ?
4457 						        new_blob->base.id : 0);
4458 		if (ret != 0)
4459 			goto err_created;
4460 	}
4461 
4462 	drm_property_unreference_blob(old_blob);
4463 	*replace = new_blob;
4464 
4465 	return 0;
4466 
4467 err_created:
4468 	drm_property_unreference_blob(new_blob);
4469 	return ret;
4470 }
4471 
4472 /**
4473  * drm_mode_getblob_ioctl - get the contents of a blob property value
4474  * @dev: DRM device
4475  * @data: ioctl data
4476  * @file_priv: DRM file info
4477  *
4478  * This function retrieves the contents of a blob property. The value stored in
4479  * an object's blob property is just a normal modeset object id.
4480  *
4481  * Called by the user via ioctl.
4482  *
4483  * Returns:
4484  * Zero on success, negative errno on failure.
4485  */
4486 int drm_mode_getblob_ioctl(struct drm_device *dev,
4487 			   void *data, struct drm_file *file_priv)
4488 {
4489 	struct drm_mode_get_blob *out_resp = data;
4490 	struct drm_property_blob *blob;
4491 	int ret = 0;
4492 	void __user *blob_ptr;
4493 
4494 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
4495 		return -EINVAL;
4496 
4497 	drm_modeset_lock_all(dev);
4498 	mutex_lock(&dev->mode_config.blob_lock);
4499 	blob = __drm_property_lookup_blob(dev, out_resp->blob_id);
4500 	if (!blob) {
4501 		ret = -ENOENT;
4502 		goto done;
4503 	}
4504 
4505 	if (out_resp->length == blob->length) {
4506 		blob_ptr = (void __user *)(unsigned long)out_resp->data;
4507 		if (copy_to_user(blob_ptr, blob->data, blob->length)) {
4508 			ret = -EFAULT;
4509 			goto done;
4510 		}
4511 	}
4512 	out_resp->length = blob->length;
4513 
4514 done:
4515 	mutex_unlock(&dev->mode_config.blob_lock);
4516 	drm_modeset_unlock_all(dev);
4517 	return ret;
4518 }
4519 
4520 /**
4521  * drm_mode_createblob_ioctl - create a new blob property
4522  * @dev: DRM device
4523  * @data: ioctl data
4524  * @file_priv: DRM file info
4525  *
4526  * This function creates a new blob property with user-defined values. In order
4527  * to give us sensible validation and checking when creating, rather than at
4528  * every potential use, we also require a type to be provided upfront.
4529  *
4530  * Called by the user via ioctl.
4531  *
4532  * Returns:
4533  * Zero on success, negative errno on failure.
4534  */
4535 int drm_mode_createblob_ioctl(struct drm_device *dev,
4536 			      void *data, struct drm_file *file_priv)
4537 {
4538 	struct drm_mode_create_blob *out_resp = data;
4539 	struct drm_property_blob *blob;
4540 	void __user *blob_ptr;
4541 	int ret = 0;
4542 
4543 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
4544 		return -EINVAL;
4545 
4546 	blob = drm_property_create_blob(dev, out_resp->length, NULL);
4547 	if (IS_ERR(blob))
4548 		return PTR_ERR(blob);
4549 
4550 	blob_ptr = (void __user *)(unsigned long)out_resp->data;
4551 	if (copy_from_user(blob->data, blob_ptr, out_resp->length)) {
4552 		ret = -EFAULT;
4553 		goto out_blob;
4554 	}
4555 
4556 	/* Dropping the lock between create_blob and our access here is safe
4557 	 * as only the same file_priv can remove the blob; at this point, it is
4558 	 * not associated with any file_priv. */
4559 	mutex_lock(&dev->mode_config.blob_lock);
4560 	out_resp->blob_id = blob->base.id;
4561 	list_add_tail(&blob->head_file, &file_priv->blobs);
4562 	mutex_unlock(&dev->mode_config.blob_lock);
4563 
4564 	return 0;
4565 
4566 out_blob:
4567 	drm_property_unreference_blob(blob);
4568 	return ret;
4569 }
4570 
4571 /**
4572  * drm_mode_destroyblob_ioctl - destroy a user blob property
4573  * @dev: DRM device
4574  * @data: ioctl data
4575  * @file_priv: DRM file info
4576  *
4577  * Destroy an existing user-defined blob property.
4578  *
4579  * Called by the user via ioctl.
4580  *
4581  * Returns:
4582  * Zero on success, negative errno on failure.
4583  */
4584 int drm_mode_destroyblob_ioctl(struct drm_device *dev,
4585 			       void *data, struct drm_file *file_priv)
4586 {
4587 	struct drm_mode_destroy_blob *out_resp = data;
4588 	struct drm_property_blob *blob = NULL, *bt;
4589 	bool found = false;
4590 	int ret = 0;
4591 
4592 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
4593 		return -EINVAL;
4594 
4595 	mutex_lock(&dev->mode_config.blob_lock);
4596 	blob = __drm_property_lookup_blob(dev, out_resp->blob_id);
4597 	if (!blob) {
4598 		ret = -ENOENT;
4599 		goto err;
4600 	}
4601 
4602 	/* Ensure the property was actually created by this user. */
4603 	list_for_each_entry(bt, &file_priv->blobs, head_file) {
4604 		if (bt == blob) {
4605 			found = true;
4606 			break;
4607 		}
4608 	}
4609 
4610 	if (!found) {
4611 		ret = -EPERM;
4612 		goto err;
4613 	}
4614 
4615 	/* We must drop head_file here, because we may not be the last
4616 	 * reference on the blob. */
4617 	list_del_init(&blob->head_file);
4618 	drm_property_unreference_blob_locked(blob);
4619 	mutex_unlock(&dev->mode_config.blob_lock);
4620 
4621 	return 0;
4622 
4623 err:
4624 	mutex_unlock(&dev->mode_config.blob_lock);
4625 	return ret;
4626 }
4627 
4628 /**
4629  * drm_mode_connector_set_path_property - set tile property on connector
4630  * @connector: connector to set property on.
4631  * @path: path to use for property; must not be NULL.
4632  *
4633  * This creates a property to expose to userspace to specify a
4634  * connector path. This is mainly used for DisplayPort MST where
4635  * connectors have a topology and we want to allow userspace to give
4636  * them more meaningful names.
4637  *
4638  * Returns:
4639  * Zero on success, negative errno on failure.
4640  */
4641 int drm_mode_connector_set_path_property(struct drm_connector *connector,
4642 					 const char *path)
4643 {
4644 	struct drm_device *dev = connector->dev;
4645 	int ret;
4646 
4647 	ret = drm_property_replace_global_blob(dev,
4648 	                                       &connector->path_blob_ptr,
4649 	                                       strlen(path) + 1,
4650 	                                       path,
4651 	                                       &connector->base,
4652 	                                       dev->mode_config.path_property);
4653 	return ret;
4654 }
4655 EXPORT_SYMBOL(drm_mode_connector_set_path_property);
4656 
4657 /**
4658  * drm_mode_connector_set_tile_property - set tile property on connector
4659  * @connector: connector to set property on.
4660  *
4661  * This looks up the tile information for a connector, and creates a
4662  * property for userspace to parse if it exists. The property is of
4663  * the form of 8 integers using ':' as a separator.
4664  *
4665  * Returns:
4666  * Zero on success, errno on failure.
4667  */
4668 int drm_mode_connector_set_tile_property(struct drm_connector *connector)
4669 {
4670 	struct drm_device *dev = connector->dev;
4671 	char tile[256];
4672 	int ret;
4673 
4674 	if (!connector->has_tile) {
4675 		ret  = drm_property_replace_global_blob(dev,
4676 		                                        &connector->tile_blob_ptr,
4677 		                                        0,
4678 		                                        NULL,
4679 		                                        &connector->base,
4680 		                                        dev->mode_config.tile_property);
4681 		return ret;
4682 	}
4683 
4684 	snprintf(tile, 256, "%d:%d:%d:%d:%d:%d:%d:%d",
4685 		 connector->tile_group->id, connector->tile_is_single_monitor,
4686 		 connector->num_h_tile, connector->num_v_tile,
4687 		 connector->tile_h_loc, connector->tile_v_loc,
4688 		 connector->tile_h_size, connector->tile_v_size);
4689 
4690 	ret = drm_property_replace_global_blob(dev,
4691 	                                       &connector->tile_blob_ptr,
4692 	                                       strlen(tile) + 1,
4693 	                                       tile,
4694 	                                       &connector->base,
4695 	                                       dev->mode_config.tile_property);
4696 	return ret;
4697 }
4698 EXPORT_SYMBOL(drm_mode_connector_set_tile_property);
4699 
4700 /**
4701  * drm_mode_connector_update_edid_property - update the edid property of a connector
4702  * @connector: drm connector
4703  * @edid: new value of the edid property
4704  *
4705  * This function creates a new blob modeset object and assigns its id to the
4706  * connector's edid property.
4707  *
4708  * Returns:
4709  * Zero on success, negative errno on failure.
4710  */
4711 int drm_mode_connector_update_edid_property(struct drm_connector *connector,
4712 					    const struct edid *edid)
4713 {
4714 	struct drm_device *dev = connector->dev;
4715 	size_t size = 0;
4716 	int ret;
4717 
4718 	/* ignore requests to set edid when overridden */
4719 	if (connector->override_edid)
4720 		return 0;
4721 
4722 	if (edid)
4723 		size = EDID_LENGTH * (1 + edid->extensions);
4724 
4725 	ret = drm_property_replace_global_blob(dev,
4726 					       &connector->edid_blob_ptr,
4727 	                                       size,
4728 	                                       edid,
4729 	                                       &connector->base,
4730 	                                       dev->mode_config.edid_property);
4731 	return ret;
4732 }
4733 EXPORT_SYMBOL(drm_mode_connector_update_edid_property);
4734 
4735 /* Some properties could refer to dynamic refcnt'd objects, or things that
4736  * need special locking to handle lifetime issues (ie. to ensure the prop
4737  * value doesn't become invalid part way through the property update due to
4738  * race).  The value returned by reference via 'obj' should be passed back
4739  * to drm_property_change_valid_put() after the property is set (and the
4740  * object to which the property is attached has a chance to take it's own
4741  * reference).
4742  */
4743 bool drm_property_change_valid_get(struct drm_property *property,
4744 					 uint64_t value, struct drm_mode_object **ref)
4745 {
4746 	int i;
4747 
4748 	if (property->flags & DRM_MODE_PROP_IMMUTABLE)
4749 		return false;
4750 
4751 	*ref = NULL;
4752 
4753 	if (drm_property_type_is(property, DRM_MODE_PROP_RANGE)) {
4754 		if (value < property->values[0] || value > property->values[1])
4755 			return false;
4756 		return true;
4757 	} else if (drm_property_type_is(property, DRM_MODE_PROP_SIGNED_RANGE)) {
4758 		int64_t svalue = U642I64(value);
4759 
4760 		if (svalue < U642I64(property->values[0]) ||
4761 				svalue > U642I64(property->values[1]))
4762 			return false;
4763 		return true;
4764 	} else if (drm_property_type_is(property, DRM_MODE_PROP_BITMASK)) {
4765 		uint64_t valid_mask = 0;
4766 
4767 		for (i = 0; i < property->num_values; i++)
4768 			valid_mask |= (1ULL << property->values[i]);
4769 		return !(value & ~valid_mask);
4770 	} else if (drm_property_type_is(property, DRM_MODE_PROP_BLOB)) {
4771 		struct drm_property_blob *blob;
4772 
4773 		if (value == 0)
4774 			return true;
4775 
4776 		blob = drm_property_lookup_blob(property->dev, value);
4777 		if (blob) {
4778 			*ref = &blob->base;
4779 			return true;
4780 		} else {
4781 			return false;
4782 		}
4783 	} else if (drm_property_type_is(property, DRM_MODE_PROP_OBJECT)) {
4784 		/* a zero value for an object property translates to null: */
4785 		if (value == 0)
4786 			return true;
4787 
4788 		/* handle refcnt'd objects specially: */
4789 		if (property->values[0] == DRM_MODE_OBJECT_FB) {
4790 			struct drm_framebuffer *fb;
4791 			fb = drm_framebuffer_lookup(property->dev, value);
4792 			if (fb) {
4793 				*ref = &fb->base;
4794 				return true;
4795 			} else {
4796 				return false;
4797 			}
4798 		} else {
4799 			return _object_find(property->dev, value, property->values[0]) != NULL;
4800 		}
4801 	}
4802 
4803 	for (i = 0; i < property->num_values; i++)
4804 		if (property->values[i] == value)
4805 			return true;
4806 	return false;
4807 }
4808 
4809 void drm_property_change_valid_put(struct drm_property *property,
4810 		struct drm_mode_object *ref)
4811 {
4812 	if (!ref)
4813 		return;
4814 
4815 	if (drm_property_type_is(property, DRM_MODE_PROP_OBJECT)) {
4816 		if (property->values[0] == DRM_MODE_OBJECT_FB)
4817 			drm_framebuffer_unreference(obj_to_fb(ref));
4818 	} else if (drm_property_type_is(property, DRM_MODE_PROP_BLOB))
4819 		drm_property_unreference_blob(obj_to_blob(ref));
4820 }
4821 
4822 /**
4823  * drm_mode_connector_property_set_ioctl - set the current value of a connector property
4824  * @dev: DRM device
4825  * @data: ioctl data
4826  * @file_priv: DRM file info
4827  *
4828  * This function sets the current value for a connectors's property. It also
4829  * calls into a driver's ->set_property callback to update the hardware state
4830  *
4831  * Called by the user via ioctl.
4832  *
4833  * Returns:
4834  * Zero on success, negative errno on failure.
4835  */
4836 int drm_mode_connector_property_set_ioctl(struct drm_device *dev,
4837 				       void *data, struct drm_file *file_priv)
4838 {
4839 	struct drm_mode_connector_set_property *conn_set_prop = data;
4840 	struct drm_mode_obj_set_property obj_set_prop = {
4841 		.value = conn_set_prop->value,
4842 		.prop_id = conn_set_prop->prop_id,
4843 		.obj_id = conn_set_prop->connector_id,
4844 		.obj_type = DRM_MODE_OBJECT_CONNECTOR
4845 	};
4846 
4847 	/* It does all the locking and checking we need */
4848 	return drm_mode_obj_set_property_ioctl(dev, &obj_set_prop, file_priv);
4849 }
4850 
4851 static int drm_mode_connector_set_obj_prop(struct drm_mode_object *obj,
4852 					   struct drm_property *property,
4853 					   uint64_t value)
4854 {
4855 	int ret = -EINVAL;
4856 	struct drm_connector *connector = obj_to_connector(obj);
4857 
4858 	/* Do DPMS ourselves */
4859 	if (property == connector->dev->mode_config.dpms_property) {
4860 		ret = 0;
4861 		if (connector->funcs->dpms)
4862 			ret = (*connector->funcs->dpms)(connector, (int)value);
4863 	} else if (connector->funcs->set_property)
4864 		ret = connector->funcs->set_property(connector, property, value);
4865 
4866 	/* store the property value if successful */
4867 	if (!ret)
4868 		drm_object_property_set_value(&connector->base, property, value);
4869 	return ret;
4870 }
4871 
4872 static int drm_mode_crtc_set_obj_prop(struct drm_mode_object *obj,
4873 				      struct drm_property *property,
4874 				      uint64_t value)
4875 {
4876 	int ret = -EINVAL;
4877 	struct drm_crtc *crtc = obj_to_crtc(obj);
4878 
4879 	if (crtc->funcs->set_property)
4880 		ret = crtc->funcs->set_property(crtc, property, value);
4881 	if (!ret)
4882 		drm_object_property_set_value(obj, property, value);
4883 
4884 	return ret;
4885 }
4886 
4887 /**
4888  * drm_mode_plane_set_obj_prop - set the value of a property
4889  * @plane: drm plane object to set property value for
4890  * @property: property to set
4891  * @value: value the property should be set to
4892  *
4893  * This functions sets a given property on a given plane object. This function
4894  * calls the driver's ->set_property callback and changes the software state of
4895  * the property if the callback succeeds.
4896  *
4897  * Returns:
4898  * Zero on success, error code on failure.
4899  */
4900 int drm_mode_plane_set_obj_prop(struct drm_plane *plane,
4901 				struct drm_property *property,
4902 				uint64_t value)
4903 {
4904 	int ret = -EINVAL;
4905 	struct drm_mode_object *obj = &plane->base;
4906 
4907 	if (plane->funcs->set_property)
4908 		ret = plane->funcs->set_property(plane, property, value);
4909 	if (!ret)
4910 		drm_object_property_set_value(obj, property, value);
4911 
4912 	return ret;
4913 }
4914 EXPORT_SYMBOL(drm_mode_plane_set_obj_prop);
4915 
4916 /**
4917  * drm_mode_obj_get_properties_ioctl - get the current value of a object's property
4918  * @dev: DRM device
4919  * @data: ioctl data
4920  * @file_priv: DRM file info
4921  *
4922  * This function retrieves the current value for an object's property. Compared
4923  * to the connector specific ioctl this one is extended to also work on crtc and
4924  * plane objects.
4925  *
4926  * Called by the user via ioctl.
4927  *
4928  * Returns:
4929  * Zero on success, negative errno on failure.
4930  */
4931 int drm_mode_obj_get_properties_ioctl(struct drm_device *dev, void *data,
4932 				      struct drm_file *file_priv)
4933 {
4934 	struct drm_mode_obj_get_properties *arg = data;
4935 	struct drm_mode_object *obj;
4936 	int ret = 0;
4937 
4938 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
4939 		return -EINVAL;
4940 
4941 	drm_modeset_lock_all(dev);
4942 
4943 	obj = drm_mode_object_find(dev, arg->obj_id, arg->obj_type);
4944 	if (!obj) {
4945 		ret = -ENOENT;
4946 		goto out;
4947 	}
4948 	if (!obj->properties) {
4949 		ret = -EINVAL;
4950 		goto out;
4951 	}
4952 
4953 	ret = get_properties(obj, file_priv->atomic,
4954 			(uint32_t __user *)(unsigned long)(arg->props_ptr),
4955 			(uint64_t __user *)(unsigned long)(arg->prop_values_ptr),
4956 			&arg->count_props);
4957 
4958 out:
4959 	drm_modeset_unlock_all(dev);
4960 	return ret;
4961 }
4962 
4963 /**
4964  * drm_mode_obj_set_property_ioctl - set the current value of an object's property
4965  * @dev: DRM device
4966  * @data: ioctl data
4967  * @file_priv: DRM file info
4968  *
4969  * This function sets the current value for an object's property. It also calls
4970  * into a driver's ->set_property callback to update the hardware state.
4971  * Compared to the connector specific ioctl this one is extended to also work on
4972  * crtc and plane objects.
4973  *
4974  * Called by the user via ioctl.
4975  *
4976  * Returns:
4977  * Zero on success, negative errno on failure.
4978  */
4979 int drm_mode_obj_set_property_ioctl(struct drm_device *dev, void *data,
4980 				    struct drm_file *file_priv)
4981 {
4982 	struct drm_mode_obj_set_property *arg = data;
4983 	struct drm_mode_object *arg_obj;
4984 	struct drm_mode_object *prop_obj;
4985 	struct drm_property *property;
4986 	int i, ret = -EINVAL;
4987 	struct drm_mode_object *ref;
4988 
4989 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
4990 		return -EINVAL;
4991 
4992 	drm_modeset_lock_all(dev);
4993 
4994 	arg_obj = drm_mode_object_find(dev, arg->obj_id, arg->obj_type);
4995 	if (!arg_obj) {
4996 		ret = -ENOENT;
4997 		goto out;
4998 	}
4999 	if (!arg_obj->properties)
5000 		goto out;
5001 
5002 	for (i = 0; i < arg_obj->properties->count; i++)
5003 		if (arg_obj->properties->properties[i]->base.id == arg->prop_id)
5004 			break;
5005 
5006 	if (i == arg_obj->properties->count)
5007 		goto out;
5008 
5009 	prop_obj = drm_mode_object_find(dev, arg->prop_id,
5010 					DRM_MODE_OBJECT_PROPERTY);
5011 	if (!prop_obj) {
5012 		ret = -ENOENT;
5013 		goto out;
5014 	}
5015 	property = obj_to_property(prop_obj);
5016 
5017 	if (!drm_property_change_valid_get(property, arg->value, &ref))
5018 		goto out;
5019 
5020 	switch (arg_obj->type) {
5021 	case DRM_MODE_OBJECT_CONNECTOR:
5022 		ret = drm_mode_connector_set_obj_prop(arg_obj, property,
5023 						      arg->value);
5024 		break;
5025 	case DRM_MODE_OBJECT_CRTC:
5026 		ret = drm_mode_crtc_set_obj_prop(arg_obj, property, arg->value);
5027 		break;
5028 	case DRM_MODE_OBJECT_PLANE:
5029 		ret = drm_mode_plane_set_obj_prop(obj_to_plane(arg_obj),
5030 						  property, arg->value);
5031 		break;
5032 	}
5033 
5034 	drm_property_change_valid_put(property, ref);
5035 
5036 out:
5037 	drm_modeset_unlock_all(dev);
5038 	return ret;
5039 }
5040 
5041 /**
5042  * drm_mode_connector_attach_encoder - attach a connector to an encoder
5043  * @connector: connector to attach
5044  * @encoder: encoder to attach @connector to
5045  *
5046  * This function links up a connector to an encoder. Note that the routing
5047  * restrictions between encoders and crtcs are exposed to userspace through the
5048  * possible_clones and possible_crtcs bitmasks.
5049  *
5050  * Returns:
5051  * Zero on success, negative errno on failure.
5052  */
5053 int drm_mode_connector_attach_encoder(struct drm_connector *connector,
5054 				      struct drm_encoder *encoder)
5055 {
5056 	int i;
5057 
5058 	for (i = 0; i < DRM_CONNECTOR_MAX_ENCODER; i++) {
5059 		if (connector->encoder_ids[i] == 0) {
5060 			connector->encoder_ids[i] = encoder->base.id;
5061 			return 0;
5062 		}
5063 	}
5064 	return -ENOMEM;
5065 }
5066 EXPORT_SYMBOL(drm_mode_connector_attach_encoder);
5067 
5068 /**
5069  * drm_mode_crtc_set_gamma_size - set the gamma table size
5070  * @crtc: CRTC to set the gamma table size for
5071  * @gamma_size: size of the gamma table
5072  *
5073  * Drivers which support gamma tables should set this to the supported gamma
5074  * table size when initializing the CRTC. Currently the drm core only supports a
5075  * fixed gamma table size.
5076  *
5077  * Returns:
5078  * Zero on success, negative errno on failure.
5079  */
5080 int drm_mode_crtc_set_gamma_size(struct drm_crtc *crtc,
5081 				 int gamma_size)
5082 {
5083 	crtc->gamma_size = gamma_size;
5084 
5085 	crtc->gamma_store = kcalloc(gamma_size, sizeof(uint16_t) * 3,
5086 				    GFP_KERNEL);
5087 	if (!crtc->gamma_store) {
5088 		crtc->gamma_size = 0;
5089 		return -ENOMEM;
5090 	}
5091 
5092 	return 0;
5093 }
5094 EXPORT_SYMBOL(drm_mode_crtc_set_gamma_size);
5095 
5096 /**
5097  * drm_mode_gamma_set_ioctl - set the gamma table
5098  * @dev: DRM device
5099  * @data: ioctl data
5100  * @file_priv: DRM file info
5101  *
5102  * Set the gamma table of a CRTC to the one passed in by the user. Userspace can
5103  * inquire the required gamma table size through drm_mode_gamma_get_ioctl.
5104  *
5105  * Called by the user via ioctl.
5106  *
5107  * Returns:
5108  * Zero on success, negative errno on failure.
5109  */
5110 int drm_mode_gamma_set_ioctl(struct drm_device *dev,
5111 			     void *data, struct drm_file *file_priv)
5112 {
5113 	struct drm_mode_crtc_lut *crtc_lut = data;
5114 	struct drm_crtc *crtc;
5115 	void *r_base, *g_base, *b_base;
5116 	int size;
5117 	int ret = 0;
5118 
5119 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
5120 		return -EINVAL;
5121 
5122 	drm_modeset_lock_all(dev);
5123 	crtc = drm_crtc_find(dev, crtc_lut->crtc_id);
5124 	if (!crtc) {
5125 		ret = -ENOENT;
5126 		goto out;
5127 	}
5128 
5129 	if (crtc->funcs->gamma_set == NULL) {
5130 		ret = -ENOSYS;
5131 		goto out;
5132 	}
5133 
5134 	/* memcpy into gamma store */
5135 	if (crtc_lut->gamma_size != crtc->gamma_size) {
5136 		ret = -EINVAL;
5137 		goto out;
5138 	}
5139 
5140 	size = crtc_lut->gamma_size * (sizeof(uint16_t));
5141 	r_base = crtc->gamma_store;
5142 	if (copy_from_user(r_base, (void __user *)(unsigned long)crtc_lut->red, size)) {
5143 		ret = -EFAULT;
5144 		goto out;
5145 	}
5146 
5147 	g_base = r_base + size;
5148 	if (copy_from_user(g_base, (void __user *)(unsigned long)crtc_lut->green, size)) {
5149 		ret = -EFAULT;
5150 		goto out;
5151 	}
5152 
5153 	b_base = g_base + size;
5154 	if (copy_from_user(b_base, (void __user *)(unsigned long)crtc_lut->blue, size)) {
5155 		ret = -EFAULT;
5156 		goto out;
5157 	}
5158 
5159 	crtc->funcs->gamma_set(crtc, r_base, g_base, b_base, 0, crtc->gamma_size);
5160 
5161 out:
5162 	drm_modeset_unlock_all(dev);
5163 	return ret;
5164 
5165 }
5166 
5167 /**
5168  * drm_mode_gamma_get_ioctl - get the gamma table
5169  * @dev: DRM device
5170  * @data: ioctl data
5171  * @file_priv: DRM file info
5172  *
5173  * Copy the current gamma table into the storage provided. This also provides
5174  * the gamma table size the driver expects, which can be used to size the
5175  * allocated storage.
5176  *
5177  * Called by the user via ioctl.
5178  *
5179  * Returns:
5180  * Zero on success, negative errno on failure.
5181  */
5182 int drm_mode_gamma_get_ioctl(struct drm_device *dev,
5183 			     void *data, struct drm_file *file_priv)
5184 {
5185 	struct drm_mode_crtc_lut *crtc_lut = data;
5186 	struct drm_crtc *crtc;
5187 	void *r_base, *g_base, *b_base;
5188 	int size;
5189 	int ret = 0;
5190 
5191 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
5192 		return -EINVAL;
5193 
5194 	drm_modeset_lock_all(dev);
5195 	crtc = drm_crtc_find(dev, crtc_lut->crtc_id);
5196 	if (!crtc) {
5197 		ret = -ENOENT;
5198 		goto out;
5199 	}
5200 
5201 	/* memcpy into gamma store */
5202 	if (crtc_lut->gamma_size != crtc->gamma_size) {
5203 		ret = -EINVAL;
5204 		goto out;
5205 	}
5206 
5207 	size = crtc_lut->gamma_size * (sizeof(uint16_t));
5208 	r_base = crtc->gamma_store;
5209 	if (copy_to_user((void __user *)(unsigned long)crtc_lut->red, r_base, size)) {
5210 		ret = -EFAULT;
5211 		goto out;
5212 	}
5213 
5214 	g_base = r_base + size;
5215 	if (copy_to_user((void __user *)(unsigned long)crtc_lut->green, g_base, size)) {
5216 		ret = -EFAULT;
5217 		goto out;
5218 	}
5219 
5220 	b_base = g_base + size;
5221 	if (copy_to_user((void __user *)(unsigned long)crtc_lut->blue, b_base, size)) {
5222 		ret = -EFAULT;
5223 		goto out;
5224 	}
5225 out:
5226 	drm_modeset_unlock_all(dev);
5227 	return ret;
5228 }
5229 
5230 /**
5231  * drm_mode_page_flip_ioctl - schedule an asynchronous fb update
5232  * @dev: DRM device
5233  * @data: ioctl data
5234  * @file_priv: DRM file info
5235  *
5236  * This schedules an asynchronous update on a given CRTC, called page flip.
5237  * Optionally a drm event is generated to signal the completion of the event.
5238  * Generic drivers cannot assume that a pageflip with changed framebuffer
5239  * properties (including driver specific metadata like tiling layout) will work,
5240  * but some drivers support e.g. pixel format changes through the pageflip
5241  * ioctl.
5242  *
5243  * Called by the user via ioctl.
5244  *
5245  * Returns:
5246  * Zero on success, negative errno on failure.
5247  */
5248 int drm_mode_page_flip_ioctl(struct drm_device *dev,
5249 			     void *data, struct drm_file *file_priv)
5250 {
5251 	struct drm_mode_crtc_page_flip *page_flip = data;
5252 	struct drm_crtc *crtc;
5253 	struct drm_framebuffer *fb = NULL;
5254 	struct drm_pending_vblank_event *e = NULL;
5255 	unsigned long flags;
5256 	int ret = -EINVAL;
5257 
5258 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
5259 		return -EINVAL;
5260 
5261 	if (page_flip->flags & ~DRM_MODE_PAGE_FLIP_FLAGS ||
5262 	    page_flip->reserved != 0)
5263 		return -EINVAL;
5264 
5265 	if ((page_flip->flags & DRM_MODE_PAGE_FLIP_ASYNC) && !dev->mode_config.async_page_flip)
5266 		return -EINVAL;
5267 
5268 	crtc = drm_crtc_find(dev, page_flip->crtc_id);
5269 	if (!crtc)
5270 		return -ENOENT;
5271 
5272 	drm_modeset_lock_crtc(crtc, crtc->primary);
5273 	if (crtc->primary->fb == NULL) {
5274 		/* The framebuffer is currently unbound, presumably
5275 		 * due to a hotplug event, that userspace has not
5276 		 * yet discovered.
5277 		 */
5278 		ret = -EBUSY;
5279 		goto out;
5280 	}
5281 
5282 	if (crtc->funcs->page_flip == NULL)
5283 		goto out;
5284 
5285 	fb = drm_framebuffer_lookup(dev, page_flip->fb_id);
5286 	if (!fb) {
5287 		ret = -ENOENT;
5288 		goto out;
5289 	}
5290 
5291 	if (crtc->state) {
5292 		const struct drm_plane_state *state = crtc->primary->state;
5293 
5294 		ret = check_src_coords(state->src_x, state->src_y,
5295 				       state->src_w, state->src_h, fb);
5296 	} else {
5297 		ret = drm_crtc_check_viewport(crtc, crtc->x, crtc->y, &crtc->mode, fb);
5298 	}
5299 	if (ret)
5300 		goto out;
5301 
5302 	if (crtc->primary->fb->pixel_format != fb->pixel_format) {
5303 		DRM_DEBUG_KMS("Page flip is not allowed to change frame buffer format.\n");
5304 		ret = -EINVAL;
5305 		goto out;
5306 	}
5307 
5308 	if (page_flip->flags & DRM_MODE_PAGE_FLIP_EVENT) {
5309 		ret = -ENOMEM;
5310 		spin_lock_irqsave(&dev->event_lock, flags);
5311 		if (file_priv->event_space < sizeof(e->event)) {
5312 			spin_unlock_irqrestore(&dev->event_lock, flags);
5313 			goto out;
5314 		}
5315 		file_priv->event_space -= sizeof(e->event);
5316 		spin_unlock_irqrestore(&dev->event_lock, flags);
5317 
5318 		e = kzalloc(sizeof(*e), GFP_KERNEL);
5319 		if (e == NULL) {
5320 			spin_lock_irqsave(&dev->event_lock, flags);
5321 			file_priv->event_space += sizeof(e->event);
5322 			spin_unlock_irqrestore(&dev->event_lock, flags);
5323 			goto out;
5324 		}
5325 
5326 		e->event.base.type = DRM_EVENT_FLIP_COMPLETE;
5327 		e->event.base.length = sizeof(e->event);
5328 		e->event.user_data = page_flip->user_data;
5329 		e->base.event = &e->event.base;
5330 		e->base.file_priv = file_priv;
5331 		e->base.destroy =
5332 			(void (*) (struct drm_pending_event *)) kfree;
5333 	}
5334 
5335 	crtc->primary->old_fb = crtc->primary->fb;
5336 	ret = crtc->funcs->page_flip(crtc, fb, e, page_flip->flags);
5337 	if (ret) {
5338 		if (page_flip->flags & DRM_MODE_PAGE_FLIP_EVENT) {
5339 			spin_lock_irqsave(&dev->event_lock, flags);
5340 			file_priv->event_space += sizeof(e->event);
5341 			spin_unlock_irqrestore(&dev->event_lock, flags);
5342 			kfree(e);
5343 		}
5344 		/* Keep the old fb, don't unref it. */
5345 		crtc->primary->old_fb = NULL;
5346 	} else {
5347 		crtc->primary->fb = fb;
5348 		/* Unref only the old framebuffer. */
5349 		fb = NULL;
5350 	}
5351 
5352 out:
5353 	if (fb)
5354 		drm_framebuffer_unreference(fb);
5355 	if (crtc->primary->old_fb)
5356 		drm_framebuffer_unreference(crtc->primary->old_fb);
5357 	crtc->primary->old_fb = NULL;
5358 	drm_modeset_unlock_crtc(crtc);
5359 
5360 	return ret;
5361 }
5362 
5363 /**
5364  * drm_mode_config_reset - call ->reset callbacks
5365  * @dev: drm device
5366  *
5367  * This functions calls all the crtc's, encoder's and connector's ->reset
5368  * callback. Drivers can use this in e.g. their driver load or resume code to
5369  * reset hardware and software state.
5370  */
5371 void drm_mode_config_reset(struct drm_device *dev)
5372 {
5373 	struct drm_crtc *crtc;
5374 	struct drm_plane *plane;
5375 	struct drm_encoder *encoder;
5376 	struct drm_connector *connector;
5377 
5378 	drm_for_each_plane(plane, dev)
5379 		if (plane->funcs->reset)
5380 			plane->funcs->reset(plane);
5381 
5382 	drm_for_each_crtc(crtc, dev)
5383 		if (crtc->funcs->reset)
5384 			crtc->funcs->reset(crtc);
5385 
5386 	drm_for_each_encoder(encoder, dev)
5387 		if (encoder->funcs->reset)
5388 			encoder->funcs->reset(encoder);
5389 
5390 	mutex_lock(&dev->mode_config.mutex);
5391 	drm_for_each_connector(connector, dev)
5392 		if (connector->funcs->reset)
5393 			connector->funcs->reset(connector);
5394 	mutex_unlock(&dev->mode_config.mutex);
5395 }
5396 EXPORT_SYMBOL(drm_mode_config_reset);
5397 
5398 /**
5399  * drm_mode_create_dumb_ioctl - create a dumb backing storage buffer
5400  * @dev: DRM device
5401  * @data: ioctl data
5402  * @file_priv: DRM file info
5403  *
5404  * This creates a new dumb buffer in the driver's backing storage manager (GEM,
5405  * TTM or something else entirely) and returns the resulting buffer handle. This
5406  * handle can then be wrapped up into a framebuffer modeset object.
5407  *
5408  * Note that userspace is not allowed to use such objects for render
5409  * acceleration - drivers must create their own private ioctls for such a use
5410  * case.
5411  *
5412  * Called by the user via ioctl.
5413  *
5414  * Returns:
5415  * Zero on success, negative errno on failure.
5416  */
5417 int drm_mode_create_dumb_ioctl(struct drm_device *dev,
5418 			       void *data, struct drm_file *file_priv)
5419 {
5420 	struct drm_mode_create_dumb *args = data;
5421 	u32 cpp, stride, size;
5422 
5423 	if (!dev->driver->dumb_create)
5424 		return -ENOSYS;
5425 	if (!args->width || !args->height || !args->bpp)
5426 		return -EINVAL;
5427 
5428 	/* overflow checks for 32bit size calculations */
5429 	/* NOTE: DIV_ROUND_UP() can overflow */
5430 	cpp = DIV_ROUND_UP(args->bpp, 8);
5431 	if (!cpp || cpp > 0xffffffffU / args->width)
5432 		return -EINVAL;
5433 	stride = cpp * args->width;
5434 	if (args->height > 0xffffffffU / stride)
5435 		return -EINVAL;
5436 
5437 	/* test for wrap-around */
5438 	size = args->height * stride;
5439 	if (PAGE_ALIGN(size) == 0)
5440 		return -EINVAL;
5441 
5442 	/*
5443 	 * handle, pitch and size are output parameters. Zero them out to
5444 	 * prevent drivers from accidentally using uninitialized data. Since
5445 	 * not all existing userspace is clearing these fields properly we
5446 	 * cannot reject IOCTL with garbage in them.
5447 	 */
5448 	args->handle = 0;
5449 	args->pitch = 0;
5450 	args->size = 0;
5451 
5452 	return dev->driver->dumb_create(file_priv, dev, args);
5453 }
5454 
5455 /**
5456  * drm_mode_mmap_dumb_ioctl - create an mmap offset for a dumb backing storage buffer
5457  * @dev: DRM device
5458  * @data: ioctl data
5459  * @file_priv: DRM file info
5460  *
5461  * Allocate an offset in the drm device node's address space to be able to
5462  * memory map a dumb buffer.
5463  *
5464  * Called by the user via ioctl.
5465  *
5466  * Returns:
5467  * Zero on success, negative errno on failure.
5468  */
5469 int drm_mode_mmap_dumb_ioctl(struct drm_device *dev,
5470 			     void *data, struct drm_file *file_priv)
5471 {
5472 	struct drm_mode_map_dumb *args = data;
5473 
5474 	/* call driver ioctl to get mmap offset */
5475 	if (!dev->driver->dumb_map_offset)
5476 		return -ENOSYS;
5477 
5478 	return dev->driver->dumb_map_offset(file_priv, dev, args->handle, &args->offset);
5479 }
5480 
5481 /**
5482  * drm_mode_destroy_dumb_ioctl - destroy a dumb backing strage buffer
5483  * @dev: DRM device
5484  * @data: ioctl data
5485  * @file_priv: DRM file info
5486  *
5487  * This destroys the userspace handle for the given dumb backing storage buffer.
5488  * Since buffer objects must be reference counted in the kernel a buffer object
5489  * won't be immediately freed if a framebuffer modeset object still uses it.
5490  *
5491  * Called by the user via ioctl.
5492  *
5493  * Returns:
5494  * Zero on success, negative errno on failure.
5495  */
5496 int drm_mode_destroy_dumb_ioctl(struct drm_device *dev,
5497 				void *data, struct drm_file *file_priv)
5498 {
5499 	struct drm_mode_destroy_dumb *args = data;
5500 
5501 	if (!dev->driver->dumb_destroy)
5502 		return -ENOSYS;
5503 
5504 	return dev->driver->dumb_destroy(file_priv, dev, args->handle);
5505 }
5506 
5507 /**
5508  * drm_fb_get_bpp_depth - get the bpp/depth values for format
5509  * @format: pixel format (DRM_FORMAT_*)
5510  * @depth: storage for the depth value
5511  * @bpp: storage for the bpp value
5512  *
5513  * This only supports RGB formats here for compat with code that doesn't use
5514  * pixel formats directly yet.
5515  */
5516 void drm_fb_get_bpp_depth(uint32_t format, unsigned int *depth,
5517 			  int *bpp)
5518 {
5519 	switch (format) {
5520 	case DRM_FORMAT_C8:
5521 	case DRM_FORMAT_RGB332:
5522 	case DRM_FORMAT_BGR233:
5523 		*depth = 8;
5524 		*bpp = 8;
5525 		break;
5526 	case DRM_FORMAT_XRGB1555:
5527 	case DRM_FORMAT_XBGR1555:
5528 	case DRM_FORMAT_RGBX5551:
5529 	case DRM_FORMAT_BGRX5551:
5530 	case DRM_FORMAT_ARGB1555:
5531 	case DRM_FORMAT_ABGR1555:
5532 	case DRM_FORMAT_RGBA5551:
5533 	case DRM_FORMAT_BGRA5551:
5534 		*depth = 15;
5535 		*bpp = 16;
5536 		break;
5537 	case DRM_FORMAT_RGB565:
5538 	case DRM_FORMAT_BGR565:
5539 		*depth = 16;
5540 		*bpp = 16;
5541 		break;
5542 	case DRM_FORMAT_RGB888:
5543 	case DRM_FORMAT_BGR888:
5544 		*depth = 24;
5545 		*bpp = 24;
5546 		break;
5547 	case DRM_FORMAT_XRGB8888:
5548 	case DRM_FORMAT_XBGR8888:
5549 	case DRM_FORMAT_RGBX8888:
5550 	case DRM_FORMAT_BGRX8888:
5551 		*depth = 24;
5552 		*bpp = 32;
5553 		break;
5554 	case DRM_FORMAT_XRGB2101010:
5555 	case DRM_FORMAT_XBGR2101010:
5556 	case DRM_FORMAT_RGBX1010102:
5557 	case DRM_FORMAT_BGRX1010102:
5558 	case DRM_FORMAT_ARGB2101010:
5559 	case DRM_FORMAT_ABGR2101010:
5560 	case DRM_FORMAT_RGBA1010102:
5561 	case DRM_FORMAT_BGRA1010102:
5562 		*depth = 30;
5563 		*bpp = 32;
5564 		break;
5565 	case DRM_FORMAT_ARGB8888:
5566 	case DRM_FORMAT_ABGR8888:
5567 	case DRM_FORMAT_RGBA8888:
5568 	case DRM_FORMAT_BGRA8888:
5569 		*depth = 32;
5570 		*bpp = 32;
5571 		break;
5572 	default:
5573 		DRM_DEBUG_KMS("unsupported pixel format %s\n",
5574 			      drm_get_format_name(format));
5575 		*depth = 0;
5576 		*bpp = 0;
5577 		break;
5578 	}
5579 }
5580 EXPORT_SYMBOL(drm_fb_get_bpp_depth);
5581 
5582 /**
5583  * drm_format_num_planes - get the number of planes for format
5584  * @format: pixel format (DRM_FORMAT_*)
5585  *
5586  * Returns:
5587  * The number of planes used by the specified pixel format.
5588  */
5589 int drm_format_num_planes(uint32_t format)
5590 {
5591 	switch (format) {
5592 	case DRM_FORMAT_YUV410:
5593 	case DRM_FORMAT_YVU410:
5594 	case DRM_FORMAT_YUV411:
5595 	case DRM_FORMAT_YVU411:
5596 	case DRM_FORMAT_YUV420:
5597 	case DRM_FORMAT_YVU420:
5598 	case DRM_FORMAT_YUV422:
5599 	case DRM_FORMAT_YVU422:
5600 	case DRM_FORMAT_YUV444:
5601 	case DRM_FORMAT_YVU444:
5602 		return 3;
5603 	case DRM_FORMAT_NV12:
5604 	case DRM_FORMAT_NV21:
5605 	case DRM_FORMAT_NV16:
5606 	case DRM_FORMAT_NV61:
5607 	case DRM_FORMAT_NV24:
5608 	case DRM_FORMAT_NV42:
5609 		return 2;
5610 	default:
5611 		return 1;
5612 	}
5613 }
5614 EXPORT_SYMBOL(drm_format_num_planes);
5615 
5616 /**
5617  * drm_format_plane_cpp - determine the bytes per pixel value
5618  * @format: pixel format (DRM_FORMAT_*)
5619  * @plane: plane index
5620  *
5621  * Returns:
5622  * The bytes per pixel value for the specified plane.
5623  */
5624 int drm_format_plane_cpp(uint32_t format, int plane)
5625 {
5626 	unsigned int depth;
5627 	int bpp;
5628 
5629 	if (plane >= drm_format_num_planes(format))
5630 		return 0;
5631 
5632 	switch (format) {
5633 	case DRM_FORMAT_YUYV:
5634 	case DRM_FORMAT_YVYU:
5635 	case DRM_FORMAT_UYVY:
5636 	case DRM_FORMAT_VYUY:
5637 		return 2;
5638 	case DRM_FORMAT_NV12:
5639 	case DRM_FORMAT_NV21:
5640 	case DRM_FORMAT_NV16:
5641 	case DRM_FORMAT_NV61:
5642 	case DRM_FORMAT_NV24:
5643 	case DRM_FORMAT_NV42:
5644 		return plane ? 2 : 1;
5645 	case DRM_FORMAT_YUV410:
5646 	case DRM_FORMAT_YVU410:
5647 	case DRM_FORMAT_YUV411:
5648 	case DRM_FORMAT_YVU411:
5649 	case DRM_FORMAT_YUV420:
5650 	case DRM_FORMAT_YVU420:
5651 	case DRM_FORMAT_YUV422:
5652 	case DRM_FORMAT_YVU422:
5653 	case DRM_FORMAT_YUV444:
5654 	case DRM_FORMAT_YVU444:
5655 		return 1;
5656 	default:
5657 		drm_fb_get_bpp_depth(format, &depth, &bpp);
5658 		return bpp >> 3;
5659 	}
5660 }
5661 EXPORT_SYMBOL(drm_format_plane_cpp);
5662 
5663 /**
5664  * drm_format_horz_chroma_subsampling - get the horizontal chroma subsampling factor
5665  * @format: pixel format (DRM_FORMAT_*)
5666  *
5667  * Returns:
5668  * The horizontal chroma subsampling factor for the
5669  * specified pixel format.
5670  */
5671 int drm_format_horz_chroma_subsampling(uint32_t format)
5672 {
5673 	switch (format) {
5674 	case DRM_FORMAT_YUV411:
5675 	case DRM_FORMAT_YVU411:
5676 	case DRM_FORMAT_YUV410:
5677 	case DRM_FORMAT_YVU410:
5678 		return 4;
5679 	case DRM_FORMAT_YUYV:
5680 	case DRM_FORMAT_YVYU:
5681 	case DRM_FORMAT_UYVY:
5682 	case DRM_FORMAT_VYUY:
5683 	case DRM_FORMAT_NV12:
5684 	case DRM_FORMAT_NV21:
5685 	case DRM_FORMAT_NV16:
5686 	case DRM_FORMAT_NV61:
5687 	case DRM_FORMAT_YUV422:
5688 	case DRM_FORMAT_YVU422:
5689 	case DRM_FORMAT_YUV420:
5690 	case DRM_FORMAT_YVU420:
5691 		return 2;
5692 	default:
5693 		return 1;
5694 	}
5695 }
5696 EXPORT_SYMBOL(drm_format_horz_chroma_subsampling);
5697 
5698 /**
5699  * drm_format_vert_chroma_subsampling - get the vertical chroma subsampling factor
5700  * @format: pixel format (DRM_FORMAT_*)
5701  *
5702  * Returns:
5703  * The vertical chroma subsampling factor for the
5704  * specified pixel format.
5705  */
5706 int drm_format_vert_chroma_subsampling(uint32_t format)
5707 {
5708 	switch (format) {
5709 	case DRM_FORMAT_YUV410:
5710 	case DRM_FORMAT_YVU410:
5711 		return 4;
5712 	case DRM_FORMAT_YUV420:
5713 	case DRM_FORMAT_YVU420:
5714 	case DRM_FORMAT_NV12:
5715 	case DRM_FORMAT_NV21:
5716 		return 2;
5717 	default:
5718 		return 1;
5719 	}
5720 }
5721 EXPORT_SYMBOL(drm_format_vert_chroma_subsampling);
5722 
5723 /**
5724  * drm_rotation_simplify() - Try to simplify the rotation
5725  * @rotation: Rotation to be simplified
5726  * @supported_rotations: Supported rotations
5727  *
5728  * Attempt to simplify the rotation to a form that is supported.
5729  * Eg. if the hardware supports everything except DRM_REFLECT_X
5730  * one could call this function like this:
5731  *
5732  * drm_rotation_simplify(rotation, BIT(DRM_ROTATE_0) |
5733  *                       BIT(DRM_ROTATE_90) | BIT(DRM_ROTATE_180) |
5734  *                       BIT(DRM_ROTATE_270) | BIT(DRM_REFLECT_Y));
5735  *
5736  * to eliminate the DRM_ROTATE_X flag. Depending on what kind of
5737  * transforms the hardware supports, this function may not
5738  * be able to produce a supported transform, so the caller should
5739  * check the result afterwards.
5740  */
5741 unsigned int drm_rotation_simplify(unsigned int rotation,
5742 				   unsigned int supported_rotations)
5743 {
5744 	if (rotation & ~supported_rotations) {
5745 		rotation ^= BIT(DRM_REFLECT_X) | BIT(DRM_REFLECT_Y);
5746 		rotation = (rotation & DRM_REFLECT_MASK) |
5747 		           BIT((ffs(rotation & DRM_ROTATE_MASK) + 1) % 4);
5748 	}
5749 
5750 	return rotation;
5751 }
5752 EXPORT_SYMBOL(drm_rotation_simplify);
5753 
5754 /**
5755  * drm_mode_config_init - initialize DRM mode_configuration structure
5756  * @dev: DRM device
5757  *
5758  * Initialize @dev's mode_config structure, used for tracking the graphics
5759  * configuration of @dev.
5760  *
5761  * Since this initializes the modeset locks, no locking is possible. Which is no
5762  * problem, since this should happen single threaded at init time. It is the
5763  * driver's problem to ensure this guarantee.
5764  *
5765  */
5766 void drm_mode_config_init(struct drm_device *dev)
5767 {
5768 	mutex_init(&dev->mode_config.mutex);
5769 	drm_modeset_lock_init(&dev->mode_config.connection_mutex);
5770 	mutex_init(&dev->mode_config.idr_mutex);
5771 	mutex_init(&dev->mode_config.fb_lock);
5772 	mutex_init(&dev->mode_config.blob_lock);
5773 	INIT_LIST_HEAD(&dev->mode_config.fb_list);
5774 	INIT_LIST_HEAD(&dev->mode_config.crtc_list);
5775 	INIT_LIST_HEAD(&dev->mode_config.connector_list);
5776 	INIT_LIST_HEAD(&dev->mode_config.encoder_list);
5777 	INIT_LIST_HEAD(&dev->mode_config.property_list);
5778 	INIT_LIST_HEAD(&dev->mode_config.property_blob_list);
5779 	INIT_LIST_HEAD(&dev->mode_config.plane_list);
5780 	idr_init(&dev->mode_config.crtc_idr);
5781 	idr_init(&dev->mode_config.tile_idr);
5782 
5783 	drm_modeset_lock_all(dev);
5784 	drm_mode_create_standard_properties(dev);
5785 	drm_modeset_unlock_all(dev);
5786 
5787 	/* Just to be sure */
5788 	dev->mode_config.num_fb = 0;
5789 	dev->mode_config.num_connector = 0;
5790 	dev->mode_config.num_crtc = 0;
5791 	dev->mode_config.num_encoder = 0;
5792 	dev->mode_config.num_overlay_plane = 0;
5793 	dev->mode_config.num_total_plane = 0;
5794 }
5795 EXPORT_SYMBOL(drm_mode_config_init);
5796 
5797 /**
5798  * drm_mode_config_cleanup - free up DRM mode_config info
5799  * @dev: DRM device
5800  *
5801  * Free up all the connectors and CRTCs associated with this DRM device, then
5802  * free up the framebuffers and associated buffer objects.
5803  *
5804  * Note that since this /should/ happen single-threaded at driver/device
5805  * teardown time, no locking is required. It's the driver's job to ensure that
5806  * this guarantee actually holds true.
5807  *
5808  * FIXME: cleanup any dangling user buffer objects too
5809  */
5810 void drm_mode_config_cleanup(struct drm_device *dev)
5811 {
5812 	struct drm_connector *connector, *ot;
5813 	struct drm_crtc *crtc, *ct;
5814 	struct drm_encoder *encoder, *enct;
5815 	struct drm_framebuffer *fb, *fbt;
5816 	struct drm_property *property, *pt;
5817 	struct drm_property_blob *blob, *bt;
5818 	struct drm_plane *plane, *plt;
5819 
5820 	list_for_each_entry_safe(encoder, enct, &dev->mode_config.encoder_list,
5821 				 head) {
5822 		encoder->funcs->destroy(encoder);
5823 	}
5824 
5825 	list_for_each_entry_safe(connector, ot,
5826 				 &dev->mode_config.connector_list, head) {
5827 		connector->funcs->destroy(connector);
5828 	}
5829 
5830 	list_for_each_entry_safe(property, pt, &dev->mode_config.property_list,
5831 				 head) {
5832 		drm_property_destroy(dev, property);
5833 	}
5834 
5835 	list_for_each_entry_safe(blob, bt, &dev->mode_config.property_blob_list,
5836 				 head_global) {
5837 		drm_property_unreference_blob(blob);
5838 	}
5839 
5840 	/*
5841 	 * Single-threaded teardown context, so it's not required to grab the
5842 	 * fb_lock to protect against concurrent fb_list access. Contrary, it
5843 	 * would actually deadlock with the drm_framebuffer_cleanup function.
5844 	 *
5845 	 * Also, if there are any framebuffers left, that's a driver leak now,
5846 	 * so politely WARN about this.
5847 	 */
5848 	WARN_ON(!list_empty(&dev->mode_config.fb_list));
5849 	list_for_each_entry_safe(fb, fbt, &dev->mode_config.fb_list, head) {
5850 		drm_framebuffer_free(&fb->refcount);
5851 	}
5852 
5853 	list_for_each_entry_safe(plane, plt, &dev->mode_config.plane_list,
5854 				 head) {
5855 		plane->funcs->destroy(plane);
5856 	}
5857 
5858 	list_for_each_entry_safe(crtc, ct, &dev->mode_config.crtc_list, head) {
5859 		crtc->funcs->destroy(crtc);
5860 	}
5861 
5862 	idr_destroy(&dev->mode_config.tile_idr);
5863 	idr_destroy(&dev->mode_config.crtc_idr);
5864 	mutex_destroy(&dev->mode_config.blob_lock);
5865 	mutex_destroy(&dev->mode_config.fb_lock);
5866 	mutex_destroy(&dev->mode_config.idr_mutex);
5867 	mutex_destroy(&dev->mode_config.mutex);
5868 	drm_modeset_lock_fini(&dev->mode_config.connection_mutex);
5869 }
5870 EXPORT_SYMBOL(drm_mode_config_cleanup);
5871 
5872 struct drm_property *drm_mode_create_rotation_property(struct drm_device *dev,
5873 						       unsigned int supported_rotations)
5874 {
5875 	static const struct drm_prop_enum_list props[] = {
5876 		{ DRM_ROTATE_0,   "rotate-0" },
5877 		{ DRM_ROTATE_90,  "rotate-90" },
5878 		{ DRM_ROTATE_180, "rotate-180" },
5879 		{ DRM_ROTATE_270, "rotate-270" },
5880 		{ DRM_REFLECT_X,  "reflect-x" },
5881 		{ DRM_REFLECT_Y,  "reflect-y" },
5882 	};
5883 
5884 	return drm_property_create_bitmask(dev, 0, "rotation",
5885 					   props, ARRAY_SIZE(props),
5886 					   supported_rotations);
5887 }
5888 EXPORT_SYMBOL(drm_mode_create_rotation_property);
5889 
5890 /**
5891  * DOC: Tile group
5892  *
5893  * Tile groups are used to represent tiled monitors with a unique
5894  * integer identifier. Tiled monitors using DisplayID v1.3 have
5895  * a unique 8-byte handle, we store this in a tile group, so we
5896  * have a common identifier for all tiles in a monitor group.
5897  */
5898 static void drm_tile_group_free(struct kref *kref)
5899 {
5900 	struct drm_tile_group *tg = container_of(kref, struct drm_tile_group, refcount);
5901 	struct drm_device *dev = tg->dev;
5902 	mutex_lock(&dev->mode_config.idr_mutex);
5903 	idr_remove(&dev->mode_config.tile_idr, tg->id);
5904 	mutex_unlock(&dev->mode_config.idr_mutex);
5905 	kfree(tg);
5906 }
5907 
5908 /**
5909  * drm_mode_put_tile_group - drop a reference to a tile group.
5910  * @dev: DRM device
5911  * @tg: tile group to drop reference to.
5912  *
5913  * drop reference to tile group and free if 0.
5914  */
5915 void drm_mode_put_tile_group(struct drm_device *dev,
5916 			     struct drm_tile_group *tg)
5917 {
5918 	kref_put(&tg->refcount, drm_tile_group_free);
5919 }
5920 
5921 /**
5922  * drm_mode_get_tile_group - get a reference to an existing tile group
5923  * @dev: DRM device
5924  * @topology: 8-bytes unique per monitor.
5925  *
5926  * Use the unique bytes to get a reference to an existing tile group.
5927  *
5928  * RETURNS:
5929  * tile group or NULL if not found.
5930  */
5931 struct drm_tile_group *drm_mode_get_tile_group(struct drm_device *dev,
5932 					       char topology[8])
5933 {
5934 	struct drm_tile_group *tg;
5935 	int id;
5936 	mutex_lock(&dev->mode_config.idr_mutex);
5937 	idr_for_each_entry(&dev->mode_config.tile_idr, tg, id) {
5938 		if (!memcmp(tg->group_data, topology, 8)) {
5939 			if (!kref_get_unless_zero(&tg->refcount))
5940 				tg = NULL;
5941 			mutex_unlock(&dev->mode_config.idr_mutex);
5942 			return tg;
5943 		}
5944 	}
5945 	mutex_unlock(&dev->mode_config.idr_mutex);
5946 	return NULL;
5947 }
5948 EXPORT_SYMBOL(drm_mode_get_tile_group);
5949 
5950 /**
5951  * drm_mode_create_tile_group - create a tile group from a displayid description
5952  * @dev: DRM device
5953  * @topology: 8-bytes unique per monitor.
5954  *
5955  * Create a tile group for the unique monitor, and get a unique
5956  * identifier for the tile group.
5957  *
5958  * RETURNS:
5959  * new tile group or error.
5960  */
5961 struct drm_tile_group *drm_mode_create_tile_group(struct drm_device *dev,
5962 						  char topology[8])
5963 {
5964 	struct drm_tile_group *tg;
5965 	int ret;
5966 
5967 	tg = kzalloc(sizeof(*tg), GFP_KERNEL);
5968 	if (!tg)
5969 		return ERR_PTR(-ENOMEM);
5970 
5971 	kref_init(&tg->refcount);
5972 	memcpy(tg->group_data, topology, 8);
5973 	tg->dev = dev;
5974 
5975 	idr_preload(GFP_KERNEL);
5976 	mutex_lock(&dev->mode_config.idr_mutex);
5977 	ret = idr_alloc(&dev->mode_config.tile_idr, tg, 1, 0, GFP_KERNEL);
5978 	if (ret >= 0) {
5979 		tg->id = ret;
5980 	} else {
5981 		kfree(tg);
5982 		tg = ERR_PTR(ret);
5983 	}
5984 
5985 	mutex_unlock(&dev->mode_config.idr_mutex);
5986 	idr_preload_end();
5987 	return tg;
5988 }
5989 EXPORT_SYMBOL(drm_mode_create_tile_group);
5990