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