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