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