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