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