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