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