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