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