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