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