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