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