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