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