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