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