drm: store property instead of id in obj attachment
[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                         struct drm_property *prop = connector->properties.properties[i];
2109                         if (put_user(prop->base.id, prop_ptr + copied)) {
2110                                 ret = -EFAULT;
2111                                 goto out;
2112                         }
2113                         if (put_user(connector->properties.values[i],
2114                                      prop_values + copied)) {
2115                                 ret = -EFAULT;
2116                                 goto out;
2117                         }
2118                         copied++;
2119                 }
2120         }
2121         out_resp->count_props = props_count;
2122
2123         if ((out_resp->count_encoders >= encoders_count) && encoders_count) {
2124                 copied = 0;
2125                 encoder_ptr = (uint32_t __user *)(unsigned long)(out_resp->encoders_ptr);
2126                 for (i = 0; i < DRM_CONNECTOR_MAX_ENCODER; i++) {
2127                         if (connector->encoder_ids[i] != 0) {
2128                                 if (put_user(connector->encoder_ids[i],
2129                                              encoder_ptr + copied)) {
2130                                         ret = -EFAULT;
2131                                         goto out;
2132                                 }
2133                                 copied++;
2134                         }
2135                 }
2136         }
2137         out_resp->count_encoders = encoders_count;
2138
2139 out:
2140         mutex_unlock(&dev->mode_config.mutex);
2141
2142         return ret;
2143 }
2144
2145 static struct drm_crtc *drm_encoder_get_crtc(struct drm_encoder *encoder)
2146 {
2147         struct drm_connector *connector;
2148         struct drm_device *dev = encoder->dev;
2149         bool uses_atomic = false;
2150
2151         /* For atomic drivers only state objects are synchronously updated and
2152          * protected by modeset locks, so check those first. */
2153         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
2154                 if (!connector->state)
2155                         continue;
2156
2157                 uses_atomic = true;
2158
2159                 if (connector->state->best_encoder != encoder)
2160                         continue;
2161
2162                 return connector->state->crtc;
2163         }
2164
2165         /* Don't return stale data (e.g. pending async disable). */
2166         if (uses_atomic)
2167                 return NULL;
2168
2169         return encoder->crtc;
2170 }
2171
2172 /**
2173  * drm_mode_getencoder - get encoder configuration
2174  * @dev: drm device for the ioctl
2175  * @data: data pointer for the ioctl
2176  * @file_priv: drm file for the ioctl call
2177  *
2178  * Construct a encoder configuration structure to return to the user.
2179  *
2180  * Called by the user via ioctl.
2181  *
2182  * Returns:
2183  * Zero on success, negative errno on failure.
2184  */
2185 int drm_mode_getencoder(struct drm_device *dev, void *data,
2186                         struct drm_file *file_priv)
2187 {
2188         struct drm_mode_get_encoder *enc_resp = data;
2189         struct drm_encoder *encoder;
2190         struct drm_crtc *crtc;
2191
2192         if (!drm_core_check_feature(dev, DRIVER_MODESET))
2193                 return -EINVAL;
2194
2195         encoder = drm_encoder_find(dev, enc_resp->encoder_id);
2196         if (!encoder)
2197                 return -ENOENT;
2198
2199         drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
2200         crtc = drm_encoder_get_crtc(encoder);
2201         if (crtc)
2202                 enc_resp->crtc_id = crtc->base.id;
2203         else if (encoder->crtc)
2204                 enc_resp->crtc_id = encoder->crtc->base.id;
2205         else
2206                 enc_resp->crtc_id = 0;
2207         drm_modeset_unlock(&dev->mode_config.connection_mutex);
2208
2209         enc_resp->encoder_type = encoder->encoder_type;
2210         enc_resp->encoder_id = encoder->base.id;
2211         enc_resp->possible_crtcs = encoder->possible_crtcs;
2212         enc_resp->possible_clones = encoder->possible_clones;
2213
2214         return 0;
2215 }
2216
2217 /**
2218  * drm_mode_getplane_res - enumerate all plane resources
2219  * @dev: DRM device
2220  * @data: ioctl data
2221  * @file_priv: DRM file info
2222  *
2223  * Construct a list of plane ids to return to the user.
2224  *
2225  * Called by the user via ioctl.
2226  *
2227  * Returns:
2228  * Zero on success, negative errno on failure.
2229  */
2230 int drm_mode_getplane_res(struct drm_device *dev, void *data,
2231                           struct drm_file *file_priv)
2232 {
2233         struct drm_mode_get_plane_res *plane_resp = data;
2234         struct drm_mode_config *config;
2235         struct drm_plane *plane;
2236         uint32_t __user *plane_ptr;
2237         int copied = 0;
2238         unsigned num_planes;
2239
2240         if (!drm_core_check_feature(dev, DRIVER_MODESET))
2241                 return -EINVAL;
2242
2243         config = &dev->mode_config;
2244
2245         if (file_priv->universal_planes)
2246                 num_planes = config->num_total_plane;
2247         else
2248                 num_planes = config->num_overlay_plane;
2249
2250         /*
2251          * This ioctl is called twice, once to determine how much space is
2252          * needed, and the 2nd time to fill it.
2253          */
2254         if (num_planes &&
2255             (plane_resp->count_planes >= num_planes)) {
2256                 plane_ptr = (uint32_t __user *)(unsigned long)plane_resp->plane_id_ptr;
2257
2258                 /* Plane lists are invariant, no locking needed. */
2259                 list_for_each_entry(plane, &config->plane_list, head) {
2260                         /*
2261                          * Unless userspace set the 'universal planes'
2262                          * capability bit, only advertise overlays.
2263                          */
2264                         if (plane->type != DRM_PLANE_TYPE_OVERLAY &&
2265                             !file_priv->universal_planes)
2266                                 continue;
2267
2268                         if (put_user(plane->base.id, plane_ptr + copied))
2269                                 return -EFAULT;
2270                         copied++;
2271                 }
2272         }
2273         plane_resp->count_planes = num_planes;
2274
2275         return 0;
2276 }
2277
2278 /**
2279  * drm_mode_getplane - get plane configuration
2280  * @dev: DRM device
2281  * @data: ioctl data
2282  * @file_priv: DRM file info
2283  *
2284  * Construct a plane configuration structure to return to the user.
2285  *
2286  * Called by the user via ioctl.
2287  *
2288  * Returns:
2289  * Zero on success, negative errno on failure.
2290  */
2291 int drm_mode_getplane(struct drm_device *dev, void *data,
2292                       struct drm_file *file_priv)
2293 {
2294         struct drm_mode_get_plane *plane_resp = data;
2295         struct drm_plane *plane;
2296         uint32_t __user *format_ptr;
2297
2298         if (!drm_core_check_feature(dev, DRIVER_MODESET))
2299                 return -EINVAL;
2300
2301         plane = drm_plane_find(dev, plane_resp->plane_id);
2302         if (!plane)
2303                 return -ENOENT;
2304
2305         drm_modeset_lock(&plane->mutex, NULL);
2306         if (plane->crtc)
2307                 plane_resp->crtc_id = plane->crtc->base.id;
2308         else
2309                 plane_resp->crtc_id = 0;
2310
2311         if (plane->fb)
2312                 plane_resp->fb_id = plane->fb->base.id;
2313         else
2314                 plane_resp->fb_id = 0;
2315         drm_modeset_unlock(&plane->mutex);
2316
2317         plane_resp->plane_id = plane->base.id;
2318         plane_resp->possible_crtcs = plane->possible_crtcs;
2319         plane_resp->gamma_size = 0;
2320
2321         /*
2322          * This ioctl is called twice, once to determine how much space is
2323          * needed, and the 2nd time to fill it.
2324          */
2325         if (plane->format_count &&
2326             (plane_resp->count_format_types >= plane->format_count)) {
2327                 format_ptr = (uint32_t __user *)(unsigned long)plane_resp->format_type_ptr;
2328                 if (copy_to_user(format_ptr,
2329                                  plane->format_types,
2330                                  sizeof(uint32_t) * plane->format_count)) {
2331                         return -EFAULT;
2332                 }
2333         }
2334         plane_resp->count_format_types = plane->format_count;
2335
2336         return 0;
2337 }
2338
2339 /*
2340  * setplane_internal - setplane handler for internal callers
2341  *
2342  * Note that we assume an extra reference has already been taken on fb.  If the
2343  * update fails, this reference will be dropped before return; if it succeeds,
2344  * the previous framebuffer (if any) will be unreferenced instead.
2345  *
2346  * src_{x,y,w,h} are provided in 16.16 fixed point format
2347  */
2348 static int __setplane_internal(struct drm_plane *plane,
2349                                struct drm_crtc *crtc,
2350                                struct drm_framebuffer *fb,
2351                                int32_t crtc_x, int32_t crtc_y,
2352                                uint32_t crtc_w, uint32_t crtc_h,
2353                                /* src_{x,y,w,h} values are 16.16 fixed point */
2354                                uint32_t src_x, uint32_t src_y,
2355                                uint32_t src_w, uint32_t src_h)
2356 {
2357         int ret = 0;
2358         unsigned int fb_width, fb_height;
2359         unsigned int i;
2360
2361         /* No fb means shut it down */
2362         if (!fb) {
2363                 plane->old_fb = plane->fb;
2364                 ret = plane->funcs->disable_plane(plane);
2365                 if (!ret) {
2366                         plane->crtc = NULL;
2367                         plane->fb = NULL;
2368                 } else {
2369                         plane->old_fb = NULL;
2370                 }
2371                 goto out;
2372         }
2373
2374         /* Check whether this plane is usable on this CRTC */
2375         if (!(plane->possible_crtcs & drm_crtc_mask(crtc))) {
2376                 DRM_DEBUG_KMS("Invalid crtc for plane\n");
2377                 ret = -EINVAL;
2378                 goto out;
2379         }
2380
2381         /* Check whether this plane supports the fb pixel format. */
2382         for (i = 0; i < plane->format_count; i++)
2383                 if (fb->pixel_format == plane->format_types[i])
2384                         break;
2385         if (i == plane->format_count) {
2386                 DRM_DEBUG_KMS("Invalid pixel format %s\n",
2387                               drm_get_format_name(fb->pixel_format));
2388                 ret = -EINVAL;
2389                 goto out;
2390         }
2391
2392         fb_width = fb->width << 16;
2393         fb_height = fb->height << 16;
2394
2395         /* Make sure source coordinates are inside the fb. */
2396         if (src_w > fb_width ||
2397             src_x > fb_width - src_w ||
2398             src_h > fb_height ||
2399             src_y > fb_height - src_h) {
2400                 DRM_DEBUG_KMS("Invalid source coordinates "
2401                               "%u.%06ux%u.%06u+%u.%06u+%u.%06u\n",
2402                               src_w >> 16, ((src_w & 0xffff) * 15625) >> 10,
2403                               src_h >> 16, ((src_h & 0xffff) * 15625) >> 10,
2404                               src_x >> 16, ((src_x & 0xffff) * 15625) >> 10,
2405                               src_y >> 16, ((src_y & 0xffff) * 15625) >> 10);
2406                 ret = -ENOSPC;
2407                 goto out;
2408         }
2409
2410         plane->old_fb = plane->fb;
2411         ret = plane->funcs->update_plane(plane, crtc, fb,
2412                                          crtc_x, crtc_y, crtc_w, crtc_h,
2413                                          src_x, src_y, src_w, src_h);
2414         if (!ret) {
2415                 plane->crtc = crtc;
2416                 plane->fb = fb;
2417                 fb = NULL;
2418         } else {
2419                 plane->old_fb = NULL;
2420         }
2421
2422 out:
2423         if (fb)
2424                 drm_framebuffer_unreference(fb);
2425         if (plane->old_fb)
2426                 drm_framebuffer_unreference(plane->old_fb);
2427         plane->old_fb = NULL;
2428
2429         return ret;
2430 }
2431
2432 static int setplane_internal(struct drm_plane *plane,
2433                              struct drm_crtc *crtc,
2434                              struct drm_framebuffer *fb,
2435                              int32_t crtc_x, int32_t crtc_y,
2436                              uint32_t crtc_w, uint32_t crtc_h,
2437                              /* src_{x,y,w,h} values are 16.16 fixed point */
2438                              uint32_t src_x, uint32_t src_y,
2439                              uint32_t src_w, uint32_t src_h)
2440 {
2441         int ret;
2442
2443         drm_modeset_lock_all(plane->dev);
2444         ret = __setplane_internal(plane, crtc, fb,
2445                                   crtc_x, crtc_y, crtc_w, crtc_h,
2446                                   src_x, src_y, src_w, src_h);
2447         drm_modeset_unlock_all(plane->dev);
2448
2449         return ret;
2450 }
2451
2452 /**
2453  * drm_mode_setplane - configure a plane's configuration
2454  * @dev: DRM device
2455  * @data: ioctl data*
2456  * @file_priv: DRM file info
2457  *
2458  * Set plane configuration, including placement, fb, scaling, and other factors.
2459  * Or pass a NULL fb to disable (planes may be disabled without providing a
2460  * valid crtc).
2461  *
2462  * Returns:
2463  * Zero on success, negative errno on failure.
2464  */
2465 int drm_mode_setplane(struct drm_device *dev, void *data,
2466                       struct drm_file *file_priv)
2467 {
2468         struct drm_mode_set_plane *plane_req = data;
2469         struct drm_plane *plane;
2470         struct drm_crtc *crtc = NULL;
2471         struct drm_framebuffer *fb = NULL;
2472
2473         if (!drm_core_check_feature(dev, DRIVER_MODESET))
2474                 return -EINVAL;
2475
2476         /* Give drivers some help against integer overflows */
2477         if (plane_req->crtc_w > INT_MAX ||
2478             plane_req->crtc_x > INT_MAX - (int32_t) plane_req->crtc_w ||
2479             plane_req->crtc_h > INT_MAX ||
2480             plane_req->crtc_y > INT_MAX - (int32_t) plane_req->crtc_h) {
2481                 DRM_DEBUG_KMS("Invalid CRTC coordinates %ux%u+%d+%d\n",
2482                               plane_req->crtc_w, plane_req->crtc_h,
2483                               plane_req->crtc_x, plane_req->crtc_y);
2484                 return -ERANGE;
2485         }
2486
2487         /*
2488          * First, find the plane, crtc, and fb objects.  If not available,
2489          * we don't bother to call the driver.
2490          */
2491         plane = drm_plane_find(dev, plane_req->plane_id);
2492         if (!plane) {
2493                 DRM_DEBUG_KMS("Unknown plane ID %d\n",
2494                               plane_req->plane_id);
2495                 return -ENOENT;
2496         }
2497
2498         if (plane_req->fb_id) {
2499                 fb = drm_framebuffer_lookup(dev, plane_req->fb_id);
2500                 if (!fb) {
2501                         DRM_DEBUG_KMS("Unknown framebuffer ID %d\n",
2502                                       plane_req->fb_id);
2503                         return -ENOENT;
2504                 }
2505
2506                 crtc = drm_crtc_find(dev, plane_req->crtc_id);
2507                 if (!crtc) {
2508                         DRM_DEBUG_KMS("Unknown crtc ID %d\n",
2509                                       plane_req->crtc_id);
2510                         return -ENOENT;
2511                 }
2512         }
2513
2514         /*
2515          * setplane_internal will take care of deref'ing either the old or new
2516          * framebuffer depending on success.
2517          */
2518         return setplane_internal(plane, crtc, fb,
2519                                  plane_req->crtc_x, plane_req->crtc_y,
2520                                  plane_req->crtc_w, plane_req->crtc_h,
2521                                  plane_req->src_x, plane_req->src_y,
2522                                  plane_req->src_w, plane_req->src_h);
2523 }
2524
2525 /**
2526  * drm_mode_set_config_internal - helper to call ->set_config
2527  * @set: modeset config to set
2528  *
2529  * This is a little helper to wrap internal calls to the ->set_config driver
2530  * interface. The only thing it adds is correct refcounting dance.
2531  * 
2532  * Returns:
2533  * Zero on success, negative errno on failure.
2534  */
2535 int drm_mode_set_config_internal(struct drm_mode_set *set)
2536 {
2537         struct drm_crtc *crtc = set->crtc;
2538         struct drm_framebuffer *fb;
2539         struct drm_crtc *tmp;
2540         int ret;
2541
2542         /*
2543          * NOTE: ->set_config can also disable other crtcs (if we steal all
2544          * connectors from it), hence we need to refcount the fbs across all
2545          * crtcs. Atomic modeset will have saner semantics ...
2546          */
2547         list_for_each_entry(tmp, &crtc->dev->mode_config.crtc_list, head)
2548                 tmp->primary->old_fb = tmp->primary->fb;
2549
2550         fb = set->fb;
2551
2552         ret = crtc->funcs->set_config(set);
2553         if (ret == 0) {
2554                 crtc->primary->crtc = crtc;
2555                 crtc->primary->fb = fb;
2556         }
2557
2558         list_for_each_entry(tmp, &crtc->dev->mode_config.crtc_list, head) {
2559                 if (tmp->primary->fb)
2560                         drm_framebuffer_reference(tmp->primary->fb);
2561                 if (tmp->primary->old_fb)
2562                         drm_framebuffer_unreference(tmp->primary->old_fb);
2563                 tmp->primary->old_fb = NULL;
2564         }
2565
2566         return ret;
2567 }
2568 EXPORT_SYMBOL(drm_mode_set_config_internal);
2569
2570 /**
2571  * drm_crtc_check_viewport - Checks that a framebuffer is big enough for the
2572  *     CRTC viewport
2573  * @crtc: CRTC that framebuffer will be displayed on
2574  * @x: x panning
2575  * @y: y panning
2576  * @mode: mode that framebuffer will be displayed under
2577  * @fb: framebuffer to check size of
2578  */
2579 int drm_crtc_check_viewport(const struct drm_crtc *crtc,
2580                             int x, int y,
2581                             const struct drm_display_mode *mode,
2582                             const struct drm_framebuffer *fb)
2583
2584 {
2585         int hdisplay, vdisplay;
2586
2587         hdisplay = mode->hdisplay;
2588         vdisplay = mode->vdisplay;
2589
2590         if (drm_mode_is_stereo(mode)) {
2591                 struct drm_display_mode adjusted = *mode;
2592
2593                 drm_mode_set_crtcinfo(&adjusted, CRTC_STEREO_DOUBLE);
2594                 hdisplay = adjusted.crtc_hdisplay;
2595                 vdisplay = adjusted.crtc_vdisplay;
2596         }
2597
2598         if (crtc->invert_dimensions)
2599                 swap(hdisplay, vdisplay);
2600
2601         if (hdisplay > fb->width ||
2602             vdisplay > fb->height ||
2603             x > fb->width - hdisplay ||
2604             y > fb->height - vdisplay) {
2605                 DRM_DEBUG_KMS("Invalid fb size %ux%u for CRTC viewport %ux%u+%d+%d%s.\n",
2606                               fb->width, fb->height, hdisplay, vdisplay, x, y,
2607                               crtc->invert_dimensions ? " (inverted)" : "");
2608                 return -ENOSPC;
2609         }
2610
2611         return 0;
2612 }
2613 EXPORT_SYMBOL(drm_crtc_check_viewport);
2614
2615 /**
2616  * drm_mode_setcrtc - set CRTC configuration
2617  * @dev: drm device for the ioctl
2618  * @data: data pointer for the ioctl
2619  * @file_priv: drm file for the ioctl call
2620  *
2621  * Build a new CRTC configuration based on user request.
2622  *
2623  * Called by the user via ioctl.
2624  *
2625  * Returns:
2626  * Zero on success, negative errno on failure.
2627  */
2628 int drm_mode_setcrtc(struct drm_device *dev, void *data,
2629                      struct drm_file *file_priv)
2630 {
2631         struct drm_mode_config *config = &dev->mode_config;
2632         struct drm_mode_crtc *crtc_req = data;
2633         struct drm_crtc *crtc;
2634         struct drm_connector **connector_set = NULL, *connector;
2635         struct drm_framebuffer *fb = NULL;
2636         struct drm_display_mode *mode = NULL;
2637         struct drm_mode_set set;
2638         uint32_t __user *set_connectors_ptr;
2639         int ret;
2640         int i;
2641
2642         if (!drm_core_check_feature(dev, DRIVER_MODESET))
2643                 return -EINVAL;
2644
2645         /* For some reason crtc x/y offsets are signed internally. */
2646         if (crtc_req->x > INT_MAX || crtc_req->y > INT_MAX)
2647                 return -ERANGE;
2648
2649         drm_modeset_lock_all(dev);
2650         crtc = drm_crtc_find(dev, crtc_req->crtc_id);
2651         if (!crtc) {
2652                 DRM_DEBUG_KMS("Unknown CRTC ID %d\n", crtc_req->crtc_id);
2653                 ret = -ENOENT;
2654                 goto out;
2655         }
2656         DRM_DEBUG_KMS("[CRTC:%d]\n", crtc->base.id);
2657
2658         if (crtc_req->mode_valid) {
2659                 /* If we have a mode we need a framebuffer. */
2660                 /* If we pass -1, set the mode with the currently bound fb */
2661                 if (crtc_req->fb_id == -1) {
2662                         if (!crtc->primary->fb) {
2663                                 DRM_DEBUG_KMS("CRTC doesn't have current FB\n");
2664                                 ret = -EINVAL;
2665                                 goto out;
2666                         }
2667                         fb = crtc->primary->fb;
2668                         /* Make refcounting symmetric with the lookup path. */
2669                         drm_framebuffer_reference(fb);
2670                 } else {
2671                         fb = drm_framebuffer_lookup(dev, crtc_req->fb_id);
2672                         if (!fb) {
2673                                 DRM_DEBUG_KMS("Unknown FB ID%d\n",
2674                                                 crtc_req->fb_id);
2675                                 ret = -ENOENT;
2676                                 goto out;
2677                         }
2678                 }
2679
2680                 mode = drm_mode_create(dev);
2681                 if (!mode) {
2682                         ret = -ENOMEM;
2683                         goto out;
2684                 }
2685
2686                 ret = drm_crtc_convert_umode(mode, &crtc_req->mode);
2687                 if (ret) {
2688                         DRM_DEBUG_KMS("Invalid mode\n");
2689                         goto out;
2690                 }
2691
2692                 drm_mode_set_crtcinfo(mode, CRTC_INTERLACE_HALVE_V);
2693
2694                 ret = drm_crtc_check_viewport(crtc, crtc_req->x, crtc_req->y,
2695                                               mode, fb);
2696                 if (ret)
2697                         goto out;
2698
2699         }
2700
2701         if (crtc_req->count_connectors == 0 && mode) {
2702                 DRM_DEBUG_KMS("Count connectors is 0 but mode set\n");
2703                 ret = -EINVAL;
2704                 goto out;
2705         }
2706
2707         if (crtc_req->count_connectors > 0 && (!mode || !fb)) {
2708                 DRM_DEBUG_KMS("Count connectors is %d but no mode or fb set\n",
2709                           crtc_req->count_connectors);
2710                 ret = -EINVAL;
2711                 goto out;
2712         }
2713
2714         if (crtc_req->count_connectors > 0) {
2715                 u32 out_id;
2716
2717                 /* Avoid unbounded kernel memory allocation */
2718                 if (crtc_req->count_connectors > config->num_connector) {
2719                         ret = -EINVAL;
2720                         goto out;
2721                 }
2722
2723                 connector_set = kmalloc(crtc_req->count_connectors *
2724                                         sizeof(struct drm_connector *),
2725                                         GFP_KERNEL);
2726                 if (!connector_set) {
2727                         ret = -ENOMEM;
2728                         goto out;
2729                 }
2730
2731                 for (i = 0; i < crtc_req->count_connectors; i++) {
2732                         set_connectors_ptr = (uint32_t __user *)(unsigned long)crtc_req->set_connectors_ptr;
2733                         if (get_user(out_id, &set_connectors_ptr[i])) {
2734                                 ret = -EFAULT;
2735                                 goto out;
2736                         }
2737
2738                         connector = drm_connector_find(dev, out_id);
2739                         if (!connector) {
2740                                 DRM_DEBUG_KMS("Connector id %d unknown\n",
2741                                                 out_id);
2742                                 ret = -ENOENT;
2743                                 goto out;
2744                         }
2745                         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
2746                                         connector->base.id,
2747                                         connector->name);
2748
2749                         connector_set[i] = connector;
2750                 }
2751         }
2752
2753         set.crtc = crtc;
2754         set.x = crtc_req->x;
2755         set.y = crtc_req->y;
2756         set.mode = mode;
2757         set.connectors = connector_set;
2758         set.num_connectors = crtc_req->count_connectors;
2759         set.fb = fb;
2760         ret = drm_mode_set_config_internal(&set);
2761
2762 out:
2763         if (fb)
2764                 drm_framebuffer_unreference(fb);
2765
2766         kfree(connector_set);
2767         drm_mode_destroy(dev, mode);
2768         drm_modeset_unlock_all(dev);
2769         return ret;
2770 }
2771
2772 /**
2773  * drm_mode_cursor_universal - translate legacy cursor ioctl call into a
2774  *     universal plane handler call
2775  * @crtc: crtc to update cursor for
2776  * @req: data pointer for the ioctl
2777  * @file_priv: drm file for the ioctl call
2778  *
2779  * Legacy cursor ioctl's work directly with driver buffer handles.  To
2780  * translate legacy ioctl calls into universal plane handler calls, we need to
2781  * wrap the native buffer handle in a drm_framebuffer.
2782  *
2783  * Note that we assume any handle passed to the legacy ioctls was a 32-bit ARGB
2784  * buffer with a pitch of 4*width; the universal plane interface should be used
2785  * directly in cases where the hardware can support other buffer settings and
2786  * userspace wants to make use of these capabilities.
2787  *
2788  * Returns:
2789  * Zero on success, negative errno on failure.
2790  */
2791 static int drm_mode_cursor_universal(struct drm_crtc *crtc,
2792                                      struct drm_mode_cursor2 *req,
2793                                      struct drm_file *file_priv)
2794 {
2795         struct drm_device *dev = crtc->dev;
2796         struct drm_framebuffer *fb = NULL;
2797         struct drm_mode_fb_cmd2 fbreq = {
2798                 .width = req->width,
2799                 .height = req->height,
2800                 .pixel_format = DRM_FORMAT_ARGB8888,
2801                 .pitches = { req->width * 4 },
2802                 .handles = { req->handle },
2803         };
2804         int32_t crtc_x, crtc_y;
2805         uint32_t crtc_w = 0, crtc_h = 0;
2806         uint32_t src_w = 0, src_h = 0;
2807         int ret = 0;
2808
2809         BUG_ON(!crtc->cursor);
2810         WARN_ON(crtc->cursor->crtc != crtc && crtc->cursor->crtc != NULL);
2811
2812         /*
2813          * Obtain fb we'll be using (either new or existing) and take an extra
2814          * reference to it if fb != null.  setplane will take care of dropping
2815          * the reference if the plane update fails.
2816          */
2817         if (req->flags & DRM_MODE_CURSOR_BO) {
2818                 if (req->handle) {
2819                         fb = add_framebuffer_internal(dev, &fbreq, file_priv);
2820                         if (IS_ERR(fb)) {
2821                                 DRM_DEBUG_KMS("failed to wrap cursor buffer in drm framebuffer\n");
2822                                 return PTR_ERR(fb);
2823                         }
2824
2825                         drm_framebuffer_reference(fb);
2826                 } else {
2827                         fb = NULL;
2828                 }
2829         } else {
2830                 fb = crtc->cursor->fb;
2831                 if (fb)
2832                         drm_framebuffer_reference(fb);
2833         }
2834
2835         if (req->flags & DRM_MODE_CURSOR_MOVE) {
2836                 crtc_x = req->x;
2837                 crtc_y = req->y;
2838         } else {
2839                 crtc_x = crtc->cursor_x;
2840                 crtc_y = crtc->cursor_y;
2841         }
2842
2843         if (fb) {
2844                 crtc_w = fb->width;
2845                 crtc_h = fb->height;
2846                 src_w = fb->width << 16;
2847                 src_h = fb->height << 16;
2848         }
2849
2850         /*
2851          * setplane_internal will take care of deref'ing either the old or new
2852          * framebuffer depending on success.
2853          */
2854         ret = __setplane_internal(crtc->cursor, crtc, fb,
2855                                 crtc_x, crtc_y, crtc_w, crtc_h,
2856                                 0, 0, src_w, src_h);
2857
2858         /* Update successful; save new cursor position, if necessary */
2859         if (ret == 0 && req->flags & DRM_MODE_CURSOR_MOVE) {
2860                 crtc->cursor_x = req->x;
2861                 crtc->cursor_y = req->y;
2862         }
2863
2864         return ret;
2865 }
2866
2867 static int drm_mode_cursor_common(struct drm_device *dev,
2868                                   struct drm_mode_cursor2 *req,
2869                                   struct drm_file *file_priv)
2870 {
2871         struct drm_crtc *crtc;
2872         int ret = 0;
2873
2874         if (!drm_core_check_feature(dev, DRIVER_MODESET))
2875                 return -EINVAL;
2876
2877         if (!req->flags || (~DRM_MODE_CURSOR_FLAGS & req->flags))
2878                 return -EINVAL;
2879
2880         crtc = drm_crtc_find(dev, req->crtc_id);
2881         if (!crtc) {
2882                 DRM_DEBUG_KMS("Unknown CRTC ID %d\n", req->crtc_id);
2883                 return -ENOENT;
2884         }
2885
2886         /*
2887          * If this crtc has a universal cursor plane, call that plane's update
2888          * handler rather than using legacy cursor handlers.
2889          */
2890         drm_modeset_lock_crtc(crtc, crtc->cursor);
2891         if (crtc->cursor) {
2892                 ret = drm_mode_cursor_universal(crtc, req, file_priv);
2893                 goto out;
2894         }
2895
2896         if (req->flags & DRM_MODE_CURSOR_BO) {
2897                 if (!crtc->funcs->cursor_set && !crtc->funcs->cursor_set2) {
2898                         ret = -ENXIO;
2899                         goto out;
2900                 }
2901                 /* Turns off the cursor if handle is 0 */
2902                 if (crtc->funcs->cursor_set2)
2903                         ret = crtc->funcs->cursor_set2(crtc, file_priv, req->handle,
2904                                                       req->width, req->height, req->hot_x, req->hot_y);
2905                 else
2906                         ret = crtc->funcs->cursor_set(crtc, file_priv, req->handle,
2907                                                       req->width, req->height);
2908         }
2909
2910         if (req->flags & DRM_MODE_CURSOR_MOVE) {
2911                 if (crtc->funcs->cursor_move) {
2912                         ret = crtc->funcs->cursor_move(crtc, req->x, req->y);
2913                 } else {
2914                         ret = -EFAULT;
2915                         goto out;
2916                 }
2917         }
2918 out:
2919         drm_modeset_unlock_crtc(crtc);
2920
2921         return ret;
2922
2923 }
2924
2925
2926 /**
2927  * drm_mode_cursor_ioctl - set CRTC's cursor configuration
2928  * @dev: drm device for the ioctl
2929  * @data: data pointer for the ioctl
2930  * @file_priv: drm file for the ioctl call
2931  *
2932  * Set the cursor configuration based on user request.
2933  *
2934  * Called by the user via ioctl.
2935  *
2936  * Returns:
2937  * Zero on success, negative errno on failure.
2938  */
2939 int drm_mode_cursor_ioctl(struct drm_device *dev,
2940                           void *data, struct drm_file *file_priv)
2941 {
2942         struct drm_mode_cursor *req = data;
2943         struct drm_mode_cursor2 new_req;
2944
2945         memcpy(&new_req, req, sizeof(struct drm_mode_cursor));
2946         new_req.hot_x = new_req.hot_y = 0;
2947
2948         return drm_mode_cursor_common(dev, &new_req, file_priv);
2949 }
2950
2951 /**
2952  * drm_mode_cursor2_ioctl - set CRTC's cursor configuration
2953  * @dev: drm device for the ioctl
2954  * @data: data pointer for the ioctl
2955  * @file_priv: drm file for the ioctl call
2956  *
2957  * Set the cursor configuration based on user request. This implements the 2nd
2958  * version of the cursor ioctl, which allows userspace to additionally specify
2959  * the hotspot of the pointer.
2960  *
2961  * Called by the user via ioctl.
2962  *
2963  * Returns:
2964  * Zero on success, negative errno on failure.
2965  */
2966 int drm_mode_cursor2_ioctl(struct drm_device *dev,
2967                            void *data, struct drm_file *file_priv)
2968 {
2969         struct drm_mode_cursor2 *req = data;
2970         return drm_mode_cursor_common(dev, req, file_priv);
2971 }
2972
2973 /**
2974  * drm_mode_legacy_fb_format - compute drm fourcc code from legacy description
2975  * @bpp: bits per pixels
2976  * @depth: bit depth per pixel
2977  *
2978  * Computes a drm fourcc pixel format code for the given @bpp/@depth values.
2979  * Useful in fbdev emulation code, since that deals in those values.
2980  */
2981 uint32_t drm_mode_legacy_fb_format(uint32_t bpp, uint32_t depth)
2982 {
2983         uint32_t fmt;
2984
2985         switch (bpp) {
2986         case 8:
2987                 fmt = DRM_FORMAT_C8;
2988                 break;
2989         case 16:
2990                 if (depth == 15)
2991                         fmt = DRM_FORMAT_XRGB1555;
2992                 else
2993                         fmt = DRM_FORMAT_RGB565;
2994                 break;
2995         case 24:
2996                 fmt = DRM_FORMAT_RGB888;
2997                 break;
2998         case 32:
2999                 if (depth == 24)
3000                         fmt = DRM_FORMAT_XRGB8888;
3001                 else if (depth == 30)
3002                         fmt = DRM_FORMAT_XRGB2101010;
3003                 else
3004                         fmt = DRM_FORMAT_ARGB8888;
3005                 break;
3006         default:
3007                 DRM_ERROR("bad bpp, assuming x8r8g8b8 pixel format\n");
3008                 fmt = DRM_FORMAT_XRGB8888;
3009                 break;
3010         }
3011
3012         return fmt;
3013 }
3014 EXPORT_SYMBOL(drm_mode_legacy_fb_format);
3015
3016 /**
3017  * drm_mode_addfb - add an FB to the graphics configuration
3018  * @dev: drm device for the ioctl
3019  * @data: data pointer for the ioctl
3020  * @file_priv: drm file for the ioctl call
3021  *
3022  * Add a new FB to the specified CRTC, given a user request. This is the
3023  * original addfb ioctl which only supported RGB formats.
3024  *
3025  * Called by the user via ioctl.
3026  *
3027  * Returns:
3028  * Zero on success, negative errno on failure.
3029  */
3030 int drm_mode_addfb(struct drm_device *dev,
3031                    void *data, struct drm_file *file_priv)
3032 {
3033         struct drm_mode_fb_cmd *or = data;
3034         struct drm_mode_fb_cmd2 r = {};
3035         int ret;
3036
3037         /* convert to new format and call new ioctl */
3038         r.fb_id = or->fb_id;
3039         r.width = or->width;
3040         r.height = or->height;
3041         r.pitches[0] = or->pitch;
3042         r.pixel_format = drm_mode_legacy_fb_format(or->bpp, or->depth);
3043         r.handles[0] = or->handle;
3044
3045         ret = drm_mode_addfb2(dev, &r, file_priv);
3046         if (ret)
3047                 return ret;
3048
3049         or->fb_id = r.fb_id;
3050
3051         return 0;
3052 }
3053
3054 static int format_check(const struct drm_mode_fb_cmd2 *r)
3055 {
3056         uint32_t format = r->pixel_format & ~DRM_FORMAT_BIG_ENDIAN;
3057
3058         switch (format) {
3059         case DRM_FORMAT_C8:
3060         case DRM_FORMAT_RGB332:
3061         case DRM_FORMAT_BGR233:
3062         case DRM_FORMAT_XRGB4444:
3063         case DRM_FORMAT_XBGR4444:
3064         case DRM_FORMAT_RGBX4444:
3065         case DRM_FORMAT_BGRX4444:
3066         case DRM_FORMAT_ARGB4444:
3067         case DRM_FORMAT_ABGR4444:
3068         case DRM_FORMAT_RGBA4444:
3069         case DRM_FORMAT_BGRA4444:
3070         case DRM_FORMAT_XRGB1555:
3071         case DRM_FORMAT_XBGR1555:
3072         case DRM_FORMAT_RGBX5551:
3073         case DRM_FORMAT_BGRX5551:
3074         case DRM_FORMAT_ARGB1555:
3075         case DRM_FORMAT_ABGR1555:
3076         case DRM_FORMAT_RGBA5551:
3077         case DRM_FORMAT_BGRA5551:
3078         case DRM_FORMAT_RGB565:
3079         case DRM_FORMAT_BGR565:
3080         case DRM_FORMAT_RGB888:
3081         case DRM_FORMAT_BGR888:
3082         case DRM_FORMAT_XRGB8888:
3083         case DRM_FORMAT_XBGR8888:
3084         case DRM_FORMAT_RGBX8888:
3085         case DRM_FORMAT_BGRX8888:
3086         case DRM_FORMAT_ARGB8888:
3087         case DRM_FORMAT_ABGR8888:
3088         case DRM_FORMAT_RGBA8888:
3089         case DRM_FORMAT_BGRA8888:
3090         case DRM_FORMAT_XRGB2101010:
3091         case DRM_FORMAT_XBGR2101010:
3092         case DRM_FORMAT_RGBX1010102:
3093         case DRM_FORMAT_BGRX1010102:
3094         case DRM_FORMAT_ARGB2101010:
3095         case DRM_FORMAT_ABGR2101010:
3096         case DRM_FORMAT_RGBA1010102:
3097         case DRM_FORMAT_BGRA1010102:
3098         case DRM_FORMAT_YUYV:
3099         case DRM_FORMAT_YVYU:
3100         case DRM_FORMAT_UYVY:
3101         case DRM_FORMAT_VYUY:
3102         case DRM_FORMAT_AYUV:
3103         case DRM_FORMAT_NV12:
3104         case DRM_FORMAT_NV21:
3105         case DRM_FORMAT_NV16:
3106         case DRM_FORMAT_NV61:
3107         case DRM_FORMAT_NV24:
3108         case DRM_FORMAT_NV42:
3109         case DRM_FORMAT_YUV410:
3110         case DRM_FORMAT_YVU410:
3111         case DRM_FORMAT_YUV411:
3112         case DRM_FORMAT_YVU411:
3113         case DRM_FORMAT_YUV420:
3114         case DRM_FORMAT_YVU420:
3115         case DRM_FORMAT_YUV422:
3116         case DRM_FORMAT_YVU422:
3117         case DRM_FORMAT_YUV444:
3118         case DRM_FORMAT_YVU444:
3119                 return 0;
3120         default:
3121                 DRM_DEBUG_KMS("invalid pixel format %s\n",
3122                               drm_get_format_name(r->pixel_format));
3123                 return -EINVAL;
3124         }
3125 }
3126
3127 static int framebuffer_check(const struct drm_mode_fb_cmd2 *r)
3128 {
3129         int ret, hsub, vsub, num_planes, i;
3130
3131         ret = format_check(r);
3132         if (ret) {
3133                 DRM_DEBUG_KMS("bad framebuffer format %s\n",
3134                               drm_get_format_name(r->pixel_format));
3135                 return ret;
3136         }
3137
3138         hsub = drm_format_horz_chroma_subsampling(r->pixel_format);
3139         vsub = drm_format_vert_chroma_subsampling(r->pixel_format);
3140         num_planes = drm_format_num_planes(r->pixel_format);
3141
3142         if (r->width == 0 || r->width % hsub) {
3143                 DRM_DEBUG_KMS("bad framebuffer width %u\n", r->width);
3144                 return -EINVAL;
3145         }
3146
3147         if (r->height == 0 || r->height % vsub) {
3148                 DRM_DEBUG_KMS("bad framebuffer height %u\n", r->height);
3149                 return -EINVAL;
3150         }
3151
3152         for (i = 0; i < num_planes; i++) {
3153                 unsigned int width = r->width / (i != 0 ? hsub : 1);
3154                 unsigned int height = r->height / (i != 0 ? vsub : 1);
3155                 unsigned int cpp = drm_format_plane_cpp(r->pixel_format, i);
3156
3157                 if (!r->handles[i]) {
3158                         DRM_DEBUG_KMS("no buffer object handle for plane %d\n", i);
3159                         return -EINVAL;
3160                 }
3161
3162                 if ((uint64_t) width * cpp > UINT_MAX)
3163                         return -ERANGE;
3164
3165                 if ((uint64_t) height * r->pitches[i] + r->offsets[i] > UINT_MAX)
3166                         return -ERANGE;
3167
3168                 if (r->pitches[i] < width * cpp) {
3169                         DRM_DEBUG_KMS("bad pitch %u for plane %d\n", r->pitches[i], i);
3170                         return -EINVAL;
3171                 }
3172         }
3173
3174         return 0;
3175 }
3176
3177 static struct drm_framebuffer *add_framebuffer_internal(struct drm_device *dev,
3178                                                         struct drm_mode_fb_cmd2 *r,
3179                                                         struct drm_file *file_priv)
3180 {
3181         struct drm_mode_config *config = &dev->mode_config;
3182         struct drm_framebuffer *fb;
3183         int ret;
3184
3185         if (r->flags & ~DRM_MODE_FB_INTERLACED) {
3186                 DRM_DEBUG_KMS("bad framebuffer flags 0x%08x\n", r->flags);
3187                 return ERR_PTR(-EINVAL);
3188         }
3189
3190         if ((config->min_width > r->width) || (r->width > config->max_width)) {
3191                 DRM_DEBUG_KMS("bad framebuffer width %d, should be >= %d && <= %d\n",
3192                           r->width, config->min_width, config->max_width);
3193                 return ERR_PTR(-EINVAL);
3194         }
3195         if ((config->min_height > r->height) || (r->height > config->max_height)) {
3196                 DRM_DEBUG_KMS("bad framebuffer height %d, should be >= %d && <= %d\n",
3197                           r->height, config->min_height, config->max_height);
3198                 return ERR_PTR(-EINVAL);
3199         }
3200
3201         ret = framebuffer_check(r);
3202         if (ret)
3203                 return ERR_PTR(ret);
3204
3205         fb = dev->mode_config.funcs->fb_create(dev, file_priv, r);
3206         if (IS_ERR(fb)) {
3207                 DRM_DEBUG_KMS("could not create framebuffer\n");
3208                 return fb;
3209         }
3210
3211         mutex_lock(&file_priv->fbs_lock);
3212         r->fb_id = fb->base.id;
3213         list_add(&fb->filp_head, &file_priv->fbs);
3214         DRM_DEBUG_KMS("[FB:%d]\n", fb->base.id);
3215         mutex_unlock(&file_priv->fbs_lock);
3216
3217         return fb;
3218 }
3219
3220 /**
3221  * drm_mode_addfb2 - add an FB to the graphics configuration
3222  * @dev: drm device for the ioctl
3223  * @data: data pointer for the ioctl
3224  * @file_priv: drm file for the ioctl call
3225  *
3226  * Add a new FB to the specified CRTC, given a user request with format. This is
3227  * the 2nd version of the addfb ioctl, which supports multi-planar framebuffers
3228  * and uses fourcc codes as pixel format specifiers.
3229  *
3230  * Called by the user via ioctl.
3231  *
3232  * Returns:
3233  * Zero on success, negative errno on failure.
3234  */
3235 int drm_mode_addfb2(struct drm_device *dev,
3236                     void *data, struct drm_file *file_priv)
3237 {
3238         struct drm_framebuffer *fb;
3239
3240         if (!drm_core_check_feature(dev, DRIVER_MODESET))
3241                 return -EINVAL;
3242
3243         fb = add_framebuffer_internal(dev, data, file_priv);
3244         if (IS_ERR(fb))
3245                 return PTR_ERR(fb);
3246
3247         return 0;
3248 }
3249
3250 /**
3251  * drm_mode_rmfb - remove an FB from the configuration
3252  * @dev: drm device for the ioctl
3253  * @data: data pointer for the ioctl
3254  * @file_priv: drm file for the ioctl call
3255  *
3256  * Remove the FB specified by the user.
3257  *
3258  * Called by the user via ioctl.
3259  *
3260  * Returns:
3261  * Zero on success, negative errno on failure.
3262  */
3263 int drm_mode_rmfb(struct drm_device *dev,
3264                    void *data, struct drm_file *file_priv)
3265 {
3266         struct drm_framebuffer *fb = NULL;
3267         struct drm_framebuffer *fbl = NULL;
3268         uint32_t *id = data;
3269         int found = 0;
3270
3271         if (!drm_core_check_feature(dev, DRIVER_MODESET))
3272                 return -EINVAL;
3273
3274         mutex_lock(&file_priv->fbs_lock);
3275         mutex_lock(&dev->mode_config.fb_lock);
3276         fb = __drm_framebuffer_lookup(dev, *id);
3277         if (!fb)
3278                 goto fail_lookup;
3279
3280         list_for_each_entry(fbl, &file_priv->fbs, filp_head)
3281                 if (fb == fbl)
3282                         found = 1;
3283         if (!found)
3284                 goto fail_lookup;
3285
3286         /* Mark fb as reaped, we still have a ref from fpriv->fbs. */
3287         __drm_framebuffer_unregister(dev, fb);
3288
3289         list_del_init(&fb->filp_head);
3290         mutex_unlock(&dev->mode_config.fb_lock);
3291         mutex_unlock(&file_priv->fbs_lock);
3292
3293         drm_framebuffer_remove(fb);
3294
3295         return 0;
3296
3297 fail_lookup:
3298         mutex_unlock(&dev->mode_config.fb_lock);
3299         mutex_unlock(&file_priv->fbs_lock);
3300
3301         return -ENOENT;
3302 }
3303
3304 /**
3305  * drm_mode_getfb - get FB info
3306  * @dev: drm device for the ioctl
3307  * @data: data pointer for the ioctl
3308  * @file_priv: drm file for the ioctl call
3309  *
3310  * Lookup the FB given its ID and return info about it.
3311  *
3312  * Called by the user via ioctl.
3313  *
3314  * Returns:
3315  * Zero on success, negative errno on failure.
3316  */
3317 int drm_mode_getfb(struct drm_device *dev,
3318                    void *data, struct drm_file *file_priv)
3319 {
3320         struct drm_mode_fb_cmd *r = data;
3321         struct drm_framebuffer *fb;
3322         int ret;
3323
3324         if (!drm_core_check_feature(dev, DRIVER_MODESET))
3325                 return -EINVAL;
3326
3327         fb = drm_framebuffer_lookup(dev, r->fb_id);
3328         if (!fb)
3329                 return -ENOENT;
3330
3331         r->height = fb->height;
3332         r->width = fb->width;
3333         r->depth = fb->depth;
3334         r->bpp = fb->bits_per_pixel;
3335         r->pitch = fb->pitches[0];
3336         if (fb->funcs->create_handle) {
3337                 if (file_priv->is_master || capable(CAP_SYS_ADMIN) ||
3338                     drm_is_control_client(file_priv)) {
3339                         ret = fb->funcs->create_handle(fb, file_priv,
3340                                                        &r->handle);
3341                 } else {
3342                         /* GET_FB() is an unprivileged ioctl so we must not
3343                          * return a buffer-handle to non-master processes! For
3344                          * backwards-compatibility reasons, we cannot make
3345                          * GET_FB() privileged, so just return an invalid handle
3346                          * for non-masters. */
3347                         r->handle = 0;
3348                         ret = 0;
3349                 }
3350         } else {
3351                 ret = -ENODEV;
3352         }
3353
3354         drm_framebuffer_unreference(fb);
3355
3356         return ret;
3357 }
3358
3359 /**
3360  * drm_mode_dirtyfb_ioctl - flush frontbuffer rendering on an FB
3361  * @dev: drm device for the ioctl
3362  * @data: data pointer for the ioctl
3363  * @file_priv: drm file for the ioctl call
3364  *
3365  * Lookup the FB and flush out the damaged area supplied by userspace as a clip
3366  * rectangle list. Generic userspace which does frontbuffer rendering must call
3367  * this ioctl to flush out the changes on manual-update display outputs, e.g.
3368  * usb display-link, mipi manual update panels or edp panel self refresh modes.
3369  *
3370  * Modesetting drivers which always update the frontbuffer do not need to
3371  * implement the corresponding ->dirty framebuffer callback.
3372  *
3373  * Called by the user via ioctl.
3374  *
3375  * Returns:
3376  * Zero on success, negative errno on failure.
3377  */
3378 int drm_mode_dirtyfb_ioctl(struct drm_device *dev,
3379                            void *data, struct drm_file *file_priv)
3380 {
3381         struct drm_clip_rect __user *clips_ptr;
3382         struct drm_clip_rect *clips = NULL;
3383         struct drm_mode_fb_dirty_cmd *r = data;
3384         struct drm_framebuffer *fb;
3385         unsigned flags;
3386         int num_clips;
3387         int ret;
3388
3389         if (!drm_core_check_feature(dev, DRIVER_MODESET))
3390                 return -EINVAL;
3391
3392         fb = drm_framebuffer_lookup(dev, r->fb_id);
3393         if (!fb)
3394                 return -ENOENT;
3395
3396         num_clips = r->num_clips;
3397         clips_ptr = (struct drm_clip_rect __user *)(unsigned long)r->clips_ptr;
3398
3399         if (!num_clips != !clips_ptr) {
3400                 ret = -EINVAL;
3401                 goto out_err1;
3402         }
3403
3404         flags = DRM_MODE_FB_DIRTY_FLAGS & r->flags;
3405
3406         /* If userspace annotates copy, clips must come in pairs */
3407         if (flags & DRM_MODE_FB_DIRTY_ANNOTATE_COPY && (num_clips % 2)) {
3408                 ret = -EINVAL;
3409                 goto out_err1;
3410         }
3411
3412         if (num_clips && clips_ptr) {
3413                 if (num_clips < 0 || num_clips > DRM_MODE_FB_DIRTY_MAX_CLIPS) {
3414                         ret = -EINVAL;
3415                         goto out_err1;
3416                 }
3417                 clips = kzalloc(num_clips * sizeof(*clips), GFP_KERNEL);
3418                 if (!clips) {
3419                         ret = -ENOMEM;
3420                         goto out_err1;
3421                 }
3422
3423                 ret = copy_from_user(clips, clips_ptr,
3424                                      num_clips * sizeof(*clips));
3425                 if (ret) {
3426                         ret = -EFAULT;
3427                         goto out_err2;
3428                 }
3429         }
3430
3431         if (fb->funcs->dirty) {
3432                 ret = fb->funcs->dirty(fb, file_priv, flags, r->color,
3433                                        clips, num_clips);
3434         } else {
3435                 ret = -ENOSYS;
3436         }
3437
3438 out_err2:
3439         kfree(clips);
3440 out_err1:
3441         drm_framebuffer_unreference(fb);
3442
3443         return ret;
3444 }
3445
3446
3447 /**
3448  * drm_fb_release - remove and free the FBs on this file
3449  * @priv: drm file for the ioctl
3450  *
3451  * Destroy all the FBs associated with @filp.
3452  *
3453  * Called by the user via ioctl.
3454  *
3455  * Returns:
3456  * Zero on success, negative errno on failure.
3457  */
3458 void drm_fb_release(struct drm_file *priv)
3459 {
3460         struct drm_device *dev = priv->minor->dev;
3461         struct drm_framebuffer *fb, *tfb;
3462
3463         /*
3464          * When the file gets released that means no one else can access the fb
3465          * list any more, so no need to grab fpriv->fbs_lock. And we need to
3466          * avoid upsetting lockdep since the universal cursor code adds a
3467          * framebuffer while holding mutex locks.
3468          *
3469          * Note that a real deadlock between fpriv->fbs_lock and the modeset
3470          * locks is impossible here since no one else but this function can get
3471          * at it any more.
3472          */
3473         list_for_each_entry_safe(fb, tfb, &priv->fbs, filp_head) {
3474
3475                 mutex_lock(&dev->mode_config.fb_lock);
3476                 /* Mark fb as reaped, we still have a ref from fpriv->fbs. */
3477                 __drm_framebuffer_unregister(dev, fb);
3478                 mutex_unlock(&dev->mode_config.fb_lock);
3479
3480                 list_del_init(&fb->filp_head);
3481
3482                 /* This will also drop the fpriv->fbs reference. */
3483                 drm_framebuffer_remove(fb);
3484         }
3485 }
3486
3487 /**
3488  * drm_property_create - create a new property type
3489  * @dev: drm device
3490  * @flags: flags specifying the property type
3491  * @name: name of the property
3492  * @num_values: number of pre-defined values
3493  *
3494  * This creates a new generic drm property which can then be attached to a drm
3495  * object with drm_object_attach_property. The returned property object must be
3496  * freed with drm_property_destroy.
3497  *
3498  * Note that the DRM core keeps a per-device list of properties and that, if
3499  * drm_mode_config_cleanup() is called, it will destroy all properties created
3500  * by the driver.
3501  *
3502  * Returns:
3503  * A pointer to the newly created property on success, NULL on failure.
3504  */
3505 struct drm_property *drm_property_create(struct drm_device *dev, int flags,
3506                                          const char *name, int num_values)
3507 {
3508         struct drm_property *property = NULL;
3509         int ret;
3510
3511         property = kzalloc(sizeof(struct drm_property), GFP_KERNEL);
3512         if (!property)
3513                 return NULL;
3514
3515         property->dev = dev;
3516
3517         if (num_values) {
3518                 property->values = kzalloc(sizeof(uint64_t)*num_values, GFP_KERNEL);
3519                 if (!property->values)
3520                         goto fail;
3521         }
3522
3523         ret = drm_mode_object_get(dev, &property->base, DRM_MODE_OBJECT_PROPERTY);
3524         if (ret)
3525                 goto fail;
3526
3527         property->flags = flags;
3528         property->num_values = num_values;
3529         INIT_LIST_HEAD(&property->enum_list);
3530
3531         if (name) {
3532                 strncpy(property->name, name, DRM_PROP_NAME_LEN);
3533                 property->name[DRM_PROP_NAME_LEN-1] = '\0';
3534         }
3535
3536         list_add_tail(&property->head, &dev->mode_config.property_list);
3537
3538         WARN_ON(!drm_property_type_valid(property));
3539
3540         return property;
3541 fail:
3542         kfree(property->values);
3543         kfree(property);
3544         return NULL;
3545 }
3546 EXPORT_SYMBOL(drm_property_create);
3547
3548 /**
3549  * drm_property_create_enum - create a new enumeration property type
3550  * @dev: drm device
3551  * @flags: flags specifying the property type
3552  * @name: name of the property
3553  * @props: enumeration lists with property values
3554  * @num_values: number of pre-defined values
3555  *
3556  * This creates a new generic drm property which can then be attached to a drm
3557  * object with drm_object_attach_property. The returned property object must be
3558  * freed with drm_property_destroy.
3559  *
3560  * Userspace is only allowed to set one of the predefined values for enumeration
3561  * properties.
3562  *
3563  * Returns:
3564  * A pointer to the newly created property on success, NULL on failure.
3565  */
3566 struct drm_property *drm_property_create_enum(struct drm_device *dev, int flags,
3567                                          const char *name,
3568                                          const struct drm_prop_enum_list *props,
3569                                          int num_values)
3570 {
3571         struct drm_property *property;
3572         int i, ret;
3573
3574         flags |= DRM_MODE_PROP_ENUM;
3575
3576         property = drm_property_create(dev, flags, name, num_values);
3577         if (!property)
3578                 return NULL;
3579
3580         for (i = 0; i < num_values; i++) {
3581                 ret = drm_property_add_enum(property, i,
3582                                       props[i].type,
3583                                       props[i].name);
3584                 if (ret) {
3585                         drm_property_destroy(dev, property);
3586                         return NULL;
3587                 }
3588         }
3589
3590         return property;
3591 }
3592 EXPORT_SYMBOL(drm_property_create_enum);
3593
3594 /**
3595  * drm_property_create_bitmask - create a new bitmask property type
3596  * @dev: drm device
3597  * @flags: flags specifying the property type
3598  * @name: name of the property
3599  * @props: enumeration lists with property bitflags
3600  * @num_props: size of the @props array
3601  * @supported_bits: bitmask of all supported enumeration values
3602  *
3603  * This creates a new bitmask drm property which can then be attached to a drm
3604  * object with drm_object_attach_property. The returned property object must be
3605  * freed with drm_property_destroy.
3606  *
3607  * Compared to plain enumeration properties userspace is allowed to set any
3608  * or'ed together combination of the predefined property bitflag values
3609  *
3610  * Returns:
3611  * A pointer to the newly created property on success, NULL on failure.
3612  */
3613 struct drm_property *drm_property_create_bitmask(struct drm_device *dev,
3614                                          int flags, const char *name,
3615                                          const struct drm_prop_enum_list *props,
3616                                          int num_props,
3617                                          uint64_t supported_bits)
3618 {
3619         struct drm_property *property;
3620         int i, ret, index = 0;
3621         int num_values = hweight64(supported_bits);
3622
3623         flags |= DRM_MODE_PROP_BITMASK;
3624
3625         property = drm_property_create(dev, flags, name, num_values);
3626         if (!property)
3627                 return NULL;
3628         for (i = 0; i < num_props; i++) {
3629                 if (!(supported_bits & (1ULL << props[i].type)))
3630                         continue;
3631
3632                 if (WARN_ON(index >= num_values)) {
3633                         drm_property_destroy(dev, property);
3634                         return NULL;
3635                 }
3636
3637                 ret = drm_property_add_enum(property, index++,
3638                                       props[i].type,
3639                                       props[i].name);
3640                 if (ret) {
3641                         drm_property_destroy(dev, property);
3642                         return NULL;
3643                 }
3644         }
3645
3646         return property;
3647 }
3648 EXPORT_SYMBOL(drm_property_create_bitmask);
3649
3650 static struct drm_property *property_create_range(struct drm_device *dev,
3651                                          int flags, const char *name,
3652                                          uint64_t min, uint64_t max)
3653 {
3654         struct drm_property *property;
3655
3656         property = drm_property_create(dev, flags, name, 2);
3657         if (!property)
3658                 return NULL;
3659
3660         property->values[0] = min;
3661         property->values[1] = max;
3662
3663         return property;
3664 }
3665
3666 /**
3667  * drm_property_create_range - create a new ranged property type
3668  * @dev: drm device
3669  * @flags: flags specifying the property type
3670  * @name: name of the property
3671  * @min: minimum value of the property
3672  * @max: maximum value of the property
3673  *
3674  * This creates a new generic drm property which can then be attached to a drm
3675  * object with drm_object_attach_property. The returned property object must be
3676  * freed with drm_property_destroy.
3677  *
3678  * Userspace is allowed to set any integer value in the (min, max) range
3679  * inclusive.
3680  *
3681  * Returns:
3682  * A pointer to the newly created property on success, NULL on failure.
3683  */
3684 struct drm_property *drm_property_create_range(struct drm_device *dev, int flags,
3685                                          const char *name,
3686                                          uint64_t min, uint64_t max)
3687 {
3688         return property_create_range(dev, DRM_MODE_PROP_RANGE | flags,
3689                         name, min, max);
3690 }
3691 EXPORT_SYMBOL(drm_property_create_range);
3692
3693 struct drm_property *drm_property_create_signed_range(struct drm_device *dev,
3694                                          int flags, const char *name,
3695                                          int64_t min, int64_t max)
3696 {
3697         return property_create_range(dev, DRM_MODE_PROP_SIGNED_RANGE | flags,
3698                         name, I642U64(min), I642U64(max));
3699 }
3700 EXPORT_SYMBOL(drm_property_create_signed_range);
3701
3702 struct drm_property *drm_property_create_object(struct drm_device *dev,
3703                                          int flags, const char *name, uint32_t type)
3704 {
3705         struct drm_property *property;
3706
3707         flags |= DRM_MODE_PROP_OBJECT;
3708
3709         property = drm_property_create(dev, flags, name, 1);
3710         if (!property)
3711                 return NULL;
3712
3713         property->values[0] = type;
3714
3715         return property;
3716 }
3717 EXPORT_SYMBOL(drm_property_create_object);
3718
3719 /**
3720  * drm_property_add_enum - add a possible value to an enumeration property
3721  * @property: enumeration property to change
3722  * @index: index of the new enumeration
3723  * @value: value of the new enumeration
3724  * @name: symbolic name of the new enumeration
3725  *
3726  * This functions adds enumerations to a property.
3727  *
3728  * It's use is deprecated, drivers should use one of the more specific helpers
3729  * to directly create the property with all enumerations already attached.
3730  *
3731  * Returns:
3732  * Zero on success, error code on failure.
3733  */
3734 int drm_property_add_enum(struct drm_property *property, int index,
3735                           uint64_t value, const char *name)
3736 {
3737         struct drm_property_enum *prop_enum;
3738
3739         if (!(drm_property_type_is(property, DRM_MODE_PROP_ENUM) ||
3740                         drm_property_type_is(property, DRM_MODE_PROP_BITMASK)))
3741                 return -EINVAL;
3742
3743         /*
3744          * Bitmask enum properties have the additional constraint of values
3745          * from 0 to 63
3746          */
3747         if (drm_property_type_is(property, DRM_MODE_PROP_BITMASK) &&
3748                         (value > 63))
3749                 return -EINVAL;
3750
3751         if (!list_empty(&property->enum_list)) {
3752                 list_for_each_entry(prop_enum, &property->enum_list, head) {
3753                         if (prop_enum->value == value) {
3754                                 strncpy(prop_enum->name, name, DRM_PROP_NAME_LEN);
3755                                 prop_enum->name[DRM_PROP_NAME_LEN-1] = '\0';
3756                                 return 0;
3757                         }
3758                 }
3759         }
3760
3761         prop_enum = kzalloc(sizeof(struct drm_property_enum), GFP_KERNEL);
3762         if (!prop_enum)
3763                 return -ENOMEM;
3764
3765         strncpy(prop_enum->name, name, DRM_PROP_NAME_LEN);
3766         prop_enum->name[DRM_PROP_NAME_LEN-1] = '\0';
3767         prop_enum->value = value;
3768
3769         property->values[index] = value;
3770         list_add_tail(&prop_enum->head, &property->enum_list);
3771         return 0;
3772 }
3773 EXPORT_SYMBOL(drm_property_add_enum);
3774
3775 /**
3776  * drm_property_destroy - destroy a drm property
3777  * @dev: drm device
3778  * @property: property to destry
3779  *
3780  * This function frees a property including any attached resources like
3781  * enumeration values.
3782  */
3783 void drm_property_destroy(struct drm_device *dev, struct drm_property *property)
3784 {
3785         struct drm_property_enum *prop_enum, *pt;
3786
3787         list_for_each_entry_safe(prop_enum, pt, &property->enum_list, head) {
3788                 list_del(&prop_enum->head);
3789                 kfree(prop_enum);
3790         }
3791
3792         if (property->num_values)
3793                 kfree(property->values);
3794         drm_mode_object_put(dev, &property->base);
3795         list_del(&property->head);
3796         kfree(property);
3797 }
3798 EXPORT_SYMBOL(drm_property_destroy);
3799
3800 /**
3801  * drm_object_attach_property - attach a property to a modeset object
3802  * @obj: drm modeset object
3803  * @property: property to attach
3804  * @init_val: initial value of the property
3805  *
3806  * This attaches the given property to the modeset object with the given initial
3807  * value. Currently this function cannot fail since the properties are stored in
3808  * a statically sized array.
3809  */
3810 void drm_object_attach_property(struct drm_mode_object *obj,
3811                                 struct drm_property *property,
3812                                 uint64_t init_val)
3813 {
3814         int count = obj->properties->count;
3815
3816         if (count == DRM_OBJECT_MAX_PROPERTY) {
3817                 WARN(1, "Failed to attach object property (type: 0x%x). Please "
3818                         "increase DRM_OBJECT_MAX_PROPERTY by 1 for each time "
3819                         "you see this message on the same object type.\n",
3820                         obj->type);
3821                 return;
3822         }
3823
3824         obj->properties->properties[count] = property;
3825         obj->properties->values[count] = init_val;
3826         obj->properties->count++;
3827 }
3828 EXPORT_SYMBOL(drm_object_attach_property);
3829
3830 /**
3831  * drm_object_property_set_value - set the value of a property
3832  * @obj: drm mode object to set property value for
3833  * @property: property to set
3834  * @val: value the property should be set to
3835  *
3836  * This functions sets a given property on a given object. This function only
3837  * changes the software state of the property, it does not call into the
3838  * driver's ->set_property callback.
3839  *
3840  * Returns:
3841  * Zero on success, error code on failure.
3842  */
3843 int drm_object_property_set_value(struct drm_mode_object *obj,
3844                                   struct drm_property *property, uint64_t val)
3845 {
3846         int i;
3847
3848         for (i = 0; i < obj->properties->count; i++) {
3849                 if (obj->properties->properties[i] == property) {
3850                         obj->properties->values[i] = val;
3851                         return 0;
3852                 }
3853         }
3854
3855         return -EINVAL;
3856 }
3857 EXPORT_SYMBOL(drm_object_property_set_value);
3858
3859 /**
3860  * drm_object_property_get_value - retrieve the value of a property
3861  * @obj: drm mode object to get property value from
3862  * @property: property to retrieve
3863  * @val: storage for the property value
3864  *
3865  * This function retrieves the softare state of the given property for the given
3866  * property. Since there is no driver callback to retrieve the current property
3867  * value this might be out of sync with the hardware, depending upon the driver
3868  * and property.
3869  *
3870  * Returns:
3871  * Zero on success, error code on failure.
3872  */
3873 int drm_object_property_get_value(struct drm_mode_object *obj,
3874                                   struct drm_property *property, uint64_t *val)
3875 {
3876         int i;
3877
3878         for (i = 0; i < obj->properties->count; i++) {
3879                 if (obj->properties->properties[i] == property) {
3880                         *val = obj->properties->values[i];
3881                         return 0;
3882                 }
3883         }
3884
3885         return -EINVAL;
3886 }
3887 EXPORT_SYMBOL(drm_object_property_get_value);
3888
3889 /**
3890  * drm_mode_getproperty_ioctl - get the property metadata
3891  * @dev: DRM device
3892  * @data: ioctl data
3893  * @file_priv: DRM file info
3894  *
3895  * This function retrieves the metadata for a given property, like the different
3896  * possible values for an enum property or the limits for a range property.
3897  *
3898  * Blob properties are special
3899  *
3900  * Called by the user via ioctl.
3901  *
3902  * Returns:
3903  * Zero on success, negative errno on failure.
3904  */
3905 int drm_mode_getproperty_ioctl(struct drm_device *dev,
3906                                void *data, struct drm_file *file_priv)
3907 {
3908         struct drm_mode_get_property *out_resp = data;
3909         struct drm_property *property;
3910         int enum_count = 0;
3911         int value_count = 0;
3912         int ret = 0, i;
3913         int copied;
3914         struct drm_property_enum *prop_enum;
3915         struct drm_mode_property_enum __user *enum_ptr;
3916         uint64_t __user *values_ptr;
3917
3918         if (!drm_core_check_feature(dev, DRIVER_MODESET))
3919                 return -EINVAL;
3920
3921         drm_modeset_lock_all(dev);
3922         property = drm_property_find(dev, out_resp->prop_id);
3923         if (!property) {
3924                 ret = -ENOENT;
3925                 goto done;
3926         }
3927
3928         if (drm_property_type_is(property, DRM_MODE_PROP_ENUM) ||
3929                         drm_property_type_is(property, DRM_MODE_PROP_BITMASK)) {
3930                 list_for_each_entry(prop_enum, &property->enum_list, head)
3931                         enum_count++;
3932         }
3933
3934         value_count = property->num_values;
3935
3936         strncpy(out_resp->name, property->name, DRM_PROP_NAME_LEN);
3937         out_resp->name[DRM_PROP_NAME_LEN-1] = 0;
3938         out_resp->flags = property->flags;
3939
3940         if ((out_resp->count_values >= value_count) && value_count) {
3941                 values_ptr = (uint64_t __user *)(unsigned long)out_resp->values_ptr;
3942                 for (i = 0; i < value_count; i++) {
3943                         if (copy_to_user(values_ptr + i, &property->values[i], sizeof(uint64_t))) {
3944                                 ret = -EFAULT;
3945                                 goto done;
3946                         }
3947                 }
3948         }
3949         out_resp->count_values = value_count;
3950
3951         if (drm_property_type_is(property, DRM_MODE_PROP_ENUM) ||
3952                         drm_property_type_is(property, DRM_MODE_PROP_BITMASK)) {
3953                 if ((out_resp->count_enum_blobs >= enum_count) && enum_count) {
3954                         copied = 0;
3955                         enum_ptr = (struct drm_mode_property_enum __user *)(unsigned long)out_resp->enum_blob_ptr;
3956                         list_for_each_entry(prop_enum, &property->enum_list, head) {
3957
3958                                 if (copy_to_user(&enum_ptr[copied].value, &prop_enum->value, sizeof(uint64_t))) {
3959                                         ret = -EFAULT;
3960                                         goto done;
3961                                 }
3962
3963                                 if (copy_to_user(&enum_ptr[copied].name,
3964                                                  &prop_enum->name, DRM_PROP_NAME_LEN)) {
3965                                         ret = -EFAULT;
3966                                         goto done;
3967                                 }
3968                                 copied++;
3969                         }
3970                 }
3971                 out_resp->count_enum_blobs = enum_count;
3972         }
3973
3974         /*
3975          * NOTE: The idea seems to have been to use this to read all the blob
3976          * property values. But nothing ever added them to the corresponding
3977          * list, userspace always used the special-purpose get_blob ioctl to
3978          * read the value for a blob property. It also doesn't make a lot of
3979          * sense to return values here when everything else is just metadata for
3980          * the property itself.
3981          */
3982         if (drm_property_type_is(property, DRM_MODE_PROP_BLOB))
3983                 out_resp->count_enum_blobs = 0;
3984 done:
3985         drm_modeset_unlock_all(dev);
3986         return ret;
3987 }
3988
3989 static struct drm_property_blob *
3990 drm_property_create_blob(struct drm_device *dev, size_t length,
3991                          const void *data)
3992 {
3993         struct drm_property_blob *blob;
3994         int ret;
3995
3996         if (!length || !data)
3997                 return NULL;
3998
3999         blob = kzalloc(sizeof(struct drm_property_blob)+length, GFP_KERNEL);
4000         if (!blob)
4001                 return NULL;
4002
4003         ret = drm_mode_object_get(dev, &blob->base, DRM_MODE_OBJECT_BLOB);
4004         if (ret) {
4005                 kfree(blob);
4006                 return NULL;
4007         }
4008
4009         blob->length = length;
4010
4011         memcpy(blob->data, data, length);
4012
4013         list_add_tail(&blob->head, &dev->mode_config.property_blob_list);
4014         return blob;
4015 }
4016
4017 static void drm_property_destroy_blob(struct drm_device *dev,
4018                                struct drm_property_blob *blob)
4019 {
4020         drm_mode_object_put(dev, &blob->base);
4021         list_del(&blob->head);
4022         kfree(blob);
4023 }
4024
4025 /**
4026  * drm_mode_getblob_ioctl - get the contents of a blob property value
4027  * @dev: DRM device
4028  * @data: ioctl data
4029  * @file_priv: DRM file info
4030  *
4031  * This function retrieves the contents of a blob property. The value stored in
4032  * an object's blob property is just a normal modeset object id.
4033  *
4034  * Called by the user via ioctl.
4035  *
4036  * Returns:
4037  * Zero on success, negative errno on failure.
4038  */
4039 int drm_mode_getblob_ioctl(struct drm_device *dev,
4040                            void *data, struct drm_file *file_priv)
4041 {
4042         struct drm_mode_get_blob *out_resp = data;
4043         struct drm_property_blob *blob;
4044         int ret = 0;
4045         void __user *blob_ptr;
4046
4047         if (!drm_core_check_feature(dev, DRIVER_MODESET))
4048                 return -EINVAL;
4049
4050         drm_modeset_lock_all(dev);
4051         blob = drm_property_blob_find(dev, out_resp->blob_id);
4052         if (!blob) {
4053                 ret = -ENOENT;
4054                 goto done;
4055         }
4056
4057         if (out_resp->length == blob->length) {
4058                 blob_ptr = (void __user *)(unsigned long)out_resp->data;
4059                 if (copy_to_user(blob_ptr, blob->data, blob->length)){
4060                         ret = -EFAULT;
4061                         goto done;
4062                 }
4063         }
4064         out_resp->length = blob->length;
4065
4066 done:
4067         drm_modeset_unlock_all(dev);
4068         return ret;
4069 }
4070
4071 /**
4072  * drm_mode_connector_set_path_property - set tile property on connector
4073  * @connector: connector to set property on.
4074  * @path: path to use for property.
4075  *
4076  * This creates a property to expose to userspace to specify a
4077  * connector path. This is mainly used for DisplayPort MST where
4078  * connectors have a topology and we want to allow userspace to give
4079  * them more meaningful names.
4080  *
4081  * Returns:
4082  * Zero on success, negative errno on failure.
4083  */
4084 int drm_mode_connector_set_path_property(struct drm_connector *connector,
4085                                          const char *path)
4086 {
4087         struct drm_device *dev = connector->dev;
4088         size_t size = strlen(path) + 1;
4089         int ret;
4090
4091         connector->path_blob_ptr = drm_property_create_blob(connector->dev,
4092                                                             size, path);
4093         if (!connector->path_blob_ptr)
4094                 return -EINVAL;
4095
4096         ret = drm_object_property_set_value(&connector->base,
4097                                             dev->mode_config.path_property,
4098                                             connector->path_blob_ptr->base.id);
4099         return ret;
4100 }
4101 EXPORT_SYMBOL(drm_mode_connector_set_path_property);
4102
4103 /**
4104  * drm_mode_connector_set_tile_property - set tile property on connector
4105  * @connector: connector to set property on.
4106  *
4107  * This looks up the tile information for a connector, and creates a
4108  * property for userspace to parse if it exists. The property is of
4109  * the form of 8 integers using ':' as a separator.
4110  *
4111  * Returns:
4112  * Zero on success, errno on failure.
4113  */
4114 int drm_mode_connector_set_tile_property(struct drm_connector *connector)
4115 {
4116         struct drm_device *dev = connector->dev;
4117         int ret, size;
4118         char tile[256];
4119
4120         if (connector->tile_blob_ptr)
4121                 drm_property_destroy_blob(dev, connector->tile_blob_ptr);
4122
4123         if (!connector->has_tile) {
4124                 connector->tile_blob_ptr = NULL;
4125                 ret = drm_object_property_set_value(&connector->base,
4126                                                     dev->mode_config.tile_property, 0);
4127                 return ret;
4128         }
4129
4130         snprintf(tile, 256, "%d:%d:%d:%d:%d:%d:%d:%d",
4131                  connector->tile_group->id, connector->tile_is_single_monitor,
4132                  connector->num_h_tile, connector->num_v_tile,
4133                  connector->tile_h_loc, connector->tile_v_loc,
4134                  connector->tile_h_size, connector->tile_v_size);
4135         size = strlen(tile) + 1;
4136
4137         connector->tile_blob_ptr = drm_property_create_blob(connector->dev,
4138                                                             size, tile);
4139         if (!connector->tile_blob_ptr)
4140                 return -EINVAL;
4141
4142         ret = drm_object_property_set_value(&connector->base,
4143                                             dev->mode_config.tile_property,
4144                                             connector->tile_blob_ptr->base.id);
4145         return ret;
4146 }
4147 EXPORT_SYMBOL(drm_mode_connector_set_tile_property);
4148
4149 /**
4150  * drm_mode_connector_update_edid_property - update the edid property of a connector
4151  * @connector: drm connector
4152  * @edid: new value of the edid property
4153  *
4154  * This function creates a new blob modeset object and assigns its id to the
4155  * connector's edid property.
4156  *
4157  * Returns:
4158  * Zero on success, negative errno on failure.
4159  */
4160 int drm_mode_connector_update_edid_property(struct drm_connector *connector,
4161                                             const struct edid *edid)
4162 {
4163         struct drm_device *dev = connector->dev;
4164         size_t size;
4165         int ret;
4166
4167         /* ignore requests to set edid when overridden */
4168         if (connector->override_edid)
4169                 return 0;
4170
4171         if (connector->edid_blob_ptr)
4172                 drm_property_destroy_blob(dev, connector->edid_blob_ptr);
4173
4174         /* Delete edid, when there is none. */
4175         if (!edid) {
4176                 connector->edid_blob_ptr = NULL;
4177                 ret = drm_object_property_set_value(&connector->base, dev->mode_config.edid_property, 0);
4178                 return ret;
4179         }
4180
4181         size = EDID_LENGTH * (1 + edid->extensions);
4182         connector->edid_blob_ptr = drm_property_create_blob(connector->dev,
4183                                                             size, edid);
4184         if (!connector->edid_blob_ptr)
4185                 return -EINVAL;
4186
4187         ret = drm_object_property_set_value(&connector->base,
4188                                                dev->mode_config.edid_property,
4189                                                connector->edid_blob_ptr->base.id);
4190
4191         return ret;
4192 }
4193 EXPORT_SYMBOL(drm_mode_connector_update_edid_property);
4194
4195 /* Some properties could refer to dynamic refcnt'd objects, or things that
4196  * need special locking to handle lifetime issues (ie. to ensure the prop
4197  * value doesn't become invalid part way through the property update due to
4198  * race).  The value returned by reference via 'obj' should be passed back
4199  * to drm_property_change_valid_put() after the property is set (and the
4200  * object to which the property is attached has a chance to take it's own
4201  * reference).
4202  */
4203 static bool drm_property_change_valid_get(struct drm_property *property,
4204                                          uint64_t value, struct drm_mode_object **ref)
4205 {
4206         if (property->flags & DRM_MODE_PROP_IMMUTABLE)
4207                 return false;
4208
4209         *ref = NULL;
4210
4211         if (drm_property_type_is(property, DRM_MODE_PROP_RANGE)) {
4212                 if (value < property->values[0] || value > property->values[1])
4213                         return false;
4214                 return true;
4215         } else if (drm_property_type_is(property, DRM_MODE_PROP_SIGNED_RANGE)) {
4216                 int64_t svalue = U642I64(value);
4217                 if (svalue < U642I64(property->values[0]) ||
4218                                 svalue > U642I64(property->values[1]))
4219                         return false;
4220                 return true;
4221         } else if (drm_property_type_is(property, DRM_MODE_PROP_BITMASK)) {
4222                 int i;
4223                 uint64_t valid_mask = 0;
4224                 for (i = 0; i < property->num_values; i++)
4225                         valid_mask |= (1ULL << property->values[i]);
4226                 return !(value & ~valid_mask);
4227         } else if (drm_property_type_is(property, DRM_MODE_PROP_BLOB)) {
4228                 /* Only the driver knows */
4229                 return true;
4230         } else if (drm_property_type_is(property, DRM_MODE_PROP_OBJECT)) {
4231                 /* a zero value for an object property translates to null: */
4232                 if (value == 0)
4233                         return true;
4234
4235                 /* handle refcnt'd objects specially: */
4236                 if (property->values[0] == DRM_MODE_OBJECT_FB) {
4237                         struct drm_framebuffer *fb;
4238                         fb = drm_framebuffer_lookup(property->dev, value);
4239                         if (fb) {
4240                                 *ref = &fb->base;
4241                                 return true;
4242                         } else {
4243                                 return false;
4244                         }
4245                 } else {
4246                         return _object_find(property->dev, value, property->values[0]) != NULL;
4247                 }
4248         } else {
4249                 int i;
4250                 for (i = 0; i < property->num_values; i++)
4251                         if (property->values[i] == value)
4252                                 return true;
4253                 return false;
4254         }
4255 }
4256
4257 static void drm_property_change_valid_put(struct drm_property *property,
4258                 struct drm_mode_object *ref)
4259 {
4260         if (!ref)
4261                 return;
4262
4263         if (drm_property_type_is(property, DRM_MODE_PROP_OBJECT)) {
4264                 if (property->values[0] == DRM_MODE_OBJECT_FB)
4265                         drm_framebuffer_unreference(obj_to_fb(ref));
4266         }
4267 }
4268
4269 /**
4270  * drm_mode_connector_property_set_ioctl - set the current value of a connector property
4271  * @dev: DRM device
4272  * @data: ioctl data
4273  * @file_priv: DRM file info
4274  *
4275  * This function sets the current value for a connectors's property. It also
4276  * calls into a driver's ->set_property callback to update the hardware state
4277  *
4278  * Called by the user via ioctl.
4279  *
4280  * Returns:
4281  * Zero on success, negative errno on failure.
4282  */
4283 int drm_mode_connector_property_set_ioctl(struct drm_device *dev,
4284                                        void *data, struct drm_file *file_priv)
4285 {
4286         struct drm_mode_connector_set_property *conn_set_prop = data;
4287         struct drm_mode_obj_set_property obj_set_prop = {
4288                 .value = conn_set_prop->value,
4289                 .prop_id = conn_set_prop->prop_id,
4290                 .obj_id = conn_set_prop->connector_id,
4291                 .obj_type = DRM_MODE_OBJECT_CONNECTOR
4292         };
4293
4294         /* It does all the locking and checking we need */
4295         return drm_mode_obj_set_property_ioctl(dev, &obj_set_prop, file_priv);
4296 }
4297
4298 static int drm_mode_connector_set_obj_prop(struct drm_mode_object *obj,
4299                                            struct drm_property *property,
4300                                            uint64_t value)
4301 {
4302         int ret = -EINVAL;
4303         struct drm_connector *connector = obj_to_connector(obj);
4304
4305         /* Do DPMS ourselves */
4306         if (property == connector->dev->mode_config.dpms_property) {
4307                 if (connector->funcs->dpms)
4308                         (*connector->funcs->dpms)(connector, (int)value);
4309                 ret = 0;
4310         } else if (connector->funcs->set_property)
4311                 ret = connector->funcs->set_property(connector, property, value);
4312
4313         /* store the property value if successful */
4314         if (!ret)
4315                 drm_object_property_set_value(&connector->base, property, value);
4316         return ret;
4317 }
4318
4319 static int drm_mode_crtc_set_obj_prop(struct drm_mode_object *obj,
4320                                       struct drm_property *property,
4321                                       uint64_t value)
4322 {
4323         int ret = -EINVAL;
4324         struct drm_crtc *crtc = obj_to_crtc(obj);
4325
4326         if (crtc->funcs->set_property)
4327                 ret = crtc->funcs->set_property(crtc, property, value);
4328         if (!ret)
4329                 drm_object_property_set_value(obj, property, value);
4330
4331         return ret;
4332 }
4333
4334 /**
4335  * drm_mode_plane_set_obj_prop - set the value of a property
4336  * @plane: drm plane object to set property value for
4337  * @property: property to set
4338  * @value: value the property should be set to
4339  *
4340  * This functions sets a given property on a given plane object. This function
4341  * calls the driver's ->set_property callback and changes the software state of
4342  * the property if the callback succeeds.
4343  *
4344  * Returns:
4345  * Zero on success, error code on failure.
4346  */
4347 int drm_mode_plane_set_obj_prop(struct drm_plane *plane,
4348                                 struct drm_property *property,
4349                                 uint64_t value)
4350 {
4351         int ret = -EINVAL;
4352         struct drm_mode_object *obj = &plane->base;
4353
4354         if (plane->funcs->set_property)
4355                 ret = plane->funcs->set_property(plane, property, value);
4356         if (!ret)
4357                 drm_object_property_set_value(obj, property, value);
4358
4359         return ret;
4360 }
4361 EXPORT_SYMBOL(drm_mode_plane_set_obj_prop);
4362
4363 /**
4364  * drm_mode_obj_get_properties_ioctl - get the current value of a object's property
4365  * @dev: DRM device
4366  * @data: ioctl data
4367  * @file_priv: DRM file info
4368  *
4369  * This function retrieves the current value for an object's property. Compared
4370  * to the connector specific ioctl this one is extended to also work on crtc and
4371  * plane objects.
4372  *
4373  * Called by the user via ioctl.
4374  *
4375  * Returns:
4376  * Zero on success, negative errno on failure.
4377  */
4378 int drm_mode_obj_get_properties_ioctl(struct drm_device *dev, void *data,
4379                                       struct drm_file *file_priv)
4380 {
4381         struct drm_mode_obj_get_properties *arg = data;
4382         struct drm_mode_object *obj;
4383         int ret = 0;
4384         int i;
4385         int copied = 0;
4386         int props_count = 0;
4387         uint32_t __user *props_ptr;
4388         uint64_t __user *prop_values_ptr;
4389
4390         if (!drm_core_check_feature(dev, DRIVER_MODESET))
4391                 return -EINVAL;
4392
4393         drm_modeset_lock_all(dev);
4394
4395         obj = drm_mode_object_find(dev, arg->obj_id, arg->obj_type);
4396         if (!obj) {
4397                 ret = -ENOENT;
4398                 goto out;
4399         }
4400         if (!obj->properties) {
4401                 ret = -EINVAL;
4402                 goto out;
4403         }
4404
4405         props_count = obj->properties->count;
4406
4407         /* This ioctl is called twice, once to determine how much space is
4408          * needed, and the 2nd time to fill it. */
4409         if ((arg->count_props >= props_count) && props_count) {
4410                 copied = 0;
4411                 props_ptr = (uint32_t __user *)(unsigned long)(arg->props_ptr);
4412                 prop_values_ptr = (uint64_t __user *)(unsigned long)
4413                                   (arg->prop_values_ptr);
4414                 for (i = 0; i < props_count; i++) {
4415                         struct drm_property *prop = obj->properties->properties[i];
4416                         if (put_user(prop->base.id, props_ptr + copied)) {
4417                                 ret = -EFAULT;
4418                                 goto out;
4419                         }
4420                         if (put_user(obj->properties->values[i],
4421                                      prop_values_ptr + copied)) {
4422                                 ret = -EFAULT;
4423                                 goto out;
4424                         }
4425                         copied++;
4426                 }
4427         }
4428         arg->count_props = props_count;
4429 out:
4430         drm_modeset_unlock_all(dev);
4431         return ret;
4432 }
4433
4434 /**
4435  * drm_mode_obj_set_property_ioctl - set the current value of an object's property
4436  * @dev: DRM device
4437  * @data: ioctl data
4438  * @file_priv: DRM file info
4439  *
4440  * This function sets the current value for an object's property. It also calls
4441  * into a driver's ->set_property callback to update the hardware state.
4442  * Compared to the connector specific ioctl this one is extended to also work on
4443  * crtc and plane objects.
4444  *
4445  * Called by the user via ioctl.
4446  *
4447  * Returns:
4448  * Zero on success, negative errno on failure.
4449  */
4450 int drm_mode_obj_set_property_ioctl(struct drm_device *dev, void *data,
4451                                     struct drm_file *file_priv)
4452 {
4453         struct drm_mode_obj_set_property *arg = data;
4454         struct drm_mode_object *arg_obj;
4455         struct drm_mode_object *prop_obj;
4456         struct drm_property *property;
4457         int i, ret = -EINVAL;
4458         struct drm_mode_object *ref;
4459
4460         if (!drm_core_check_feature(dev, DRIVER_MODESET))
4461                 return -EINVAL;
4462
4463         drm_modeset_lock_all(dev);
4464
4465         arg_obj = drm_mode_object_find(dev, arg->obj_id, arg->obj_type);
4466         if (!arg_obj) {
4467                 ret = -ENOENT;
4468                 goto out;
4469         }
4470         if (!arg_obj->properties)
4471                 goto out;
4472
4473         for (i = 0; i < arg_obj->properties->count; i++)
4474                 if (arg_obj->properties->properties[i]->base.id == arg->prop_id)
4475                         break;
4476
4477         if (i == arg_obj->properties->count)
4478                 goto out;
4479
4480         prop_obj = drm_mode_object_find(dev, arg->prop_id,
4481                                         DRM_MODE_OBJECT_PROPERTY);
4482         if (!prop_obj) {
4483                 ret = -ENOENT;
4484                 goto out;
4485         }
4486         property = obj_to_property(prop_obj);
4487
4488         if (!drm_property_change_valid_get(property, arg->value, &ref))
4489                 goto out;
4490
4491         switch (arg_obj->type) {
4492         case DRM_MODE_OBJECT_CONNECTOR:
4493                 ret = drm_mode_connector_set_obj_prop(arg_obj, property,
4494                                                       arg->value);
4495                 break;
4496         case DRM_MODE_OBJECT_CRTC:
4497                 ret = drm_mode_crtc_set_obj_prop(arg_obj, property, arg->value);
4498                 break;
4499         case DRM_MODE_OBJECT_PLANE:
4500                 ret = drm_mode_plane_set_obj_prop(obj_to_plane(arg_obj),
4501                                                   property, arg->value);
4502                 break;
4503         }
4504
4505         drm_property_change_valid_put(property, ref);
4506
4507 out:
4508         drm_modeset_unlock_all(dev);
4509         return ret;
4510 }
4511
4512 /**
4513  * drm_mode_connector_attach_encoder - attach a connector to an encoder
4514  * @connector: connector to attach
4515  * @encoder: encoder to attach @connector to
4516  *
4517  * This function links up a connector to an encoder. Note that the routing
4518  * restrictions between encoders and crtcs are exposed to userspace through the
4519  * possible_clones and possible_crtcs bitmasks.
4520  *
4521  * Returns:
4522  * Zero on success, negative errno on failure.
4523  */
4524 int drm_mode_connector_attach_encoder(struct drm_connector *connector,
4525                                       struct drm_encoder *encoder)
4526 {
4527         int i;
4528
4529         for (i = 0; i < DRM_CONNECTOR_MAX_ENCODER; i++) {
4530                 if (connector->encoder_ids[i] == 0) {
4531                         connector->encoder_ids[i] = encoder->base.id;
4532                         return 0;
4533                 }
4534         }
4535         return -ENOMEM;
4536 }
4537 EXPORT_SYMBOL(drm_mode_connector_attach_encoder);
4538
4539 /**
4540  * drm_mode_crtc_set_gamma_size - set the gamma table size
4541  * @crtc: CRTC to set the gamma table size for
4542  * @gamma_size: size of the gamma table
4543  *
4544  * Drivers which support gamma tables should set this to the supported gamma
4545  * table size when initializing the CRTC. Currently the drm core only supports a
4546  * fixed gamma table size.
4547  *
4548  * Returns:
4549  * Zero on success, negative errno on failure.
4550  */
4551 int drm_mode_crtc_set_gamma_size(struct drm_crtc *crtc,
4552                                  int gamma_size)
4553 {
4554         crtc->gamma_size = gamma_size;
4555
4556         crtc->gamma_store = kzalloc(gamma_size * sizeof(uint16_t) * 3, GFP_KERNEL);
4557         if (!crtc->gamma_store) {
4558                 crtc->gamma_size = 0;
4559                 return -ENOMEM;
4560         }
4561
4562         return 0;
4563 }
4564 EXPORT_SYMBOL(drm_mode_crtc_set_gamma_size);
4565
4566 /**
4567  * drm_mode_gamma_set_ioctl - set the gamma table
4568  * @dev: DRM device
4569  * @data: ioctl data
4570  * @file_priv: DRM file info
4571  *
4572  * Set the gamma table of a CRTC to the one passed in by the user. Userspace can
4573  * inquire the required gamma table size through drm_mode_gamma_get_ioctl.
4574  *
4575  * Called by the user via ioctl.
4576  *
4577  * Returns:
4578  * Zero on success, negative errno on failure.
4579  */
4580 int drm_mode_gamma_set_ioctl(struct drm_device *dev,
4581                              void *data, struct drm_file *file_priv)
4582 {
4583         struct drm_mode_crtc_lut *crtc_lut = data;
4584         struct drm_crtc *crtc;
4585         void *r_base, *g_base, *b_base;
4586         int size;
4587         int ret = 0;
4588
4589         if (!drm_core_check_feature(dev, DRIVER_MODESET))
4590                 return -EINVAL;
4591
4592         drm_modeset_lock_all(dev);
4593         crtc = drm_crtc_find(dev, crtc_lut->crtc_id);
4594         if (!crtc) {
4595                 ret = -ENOENT;
4596                 goto out;
4597         }
4598
4599         if (crtc->funcs->gamma_set == NULL) {
4600                 ret = -ENOSYS;
4601                 goto out;
4602         }
4603
4604         /* memcpy into gamma store */
4605         if (crtc_lut->gamma_size != crtc->gamma_size) {
4606                 ret = -EINVAL;
4607                 goto out;
4608         }
4609
4610         size = crtc_lut->gamma_size * (sizeof(uint16_t));
4611         r_base = crtc->gamma_store;
4612         if (copy_from_user(r_base, (void __user *)(unsigned long)crtc_lut->red, size)) {
4613                 ret = -EFAULT;
4614                 goto out;
4615         }
4616
4617         g_base = r_base + size;
4618         if (copy_from_user(g_base, (void __user *)(unsigned long)crtc_lut->green, size)) {
4619                 ret = -EFAULT;
4620                 goto out;
4621         }
4622
4623         b_base = g_base + size;
4624         if (copy_from_user(b_base, (void __user *)(unsigned long)crtc_lut->blue, size)) {
4625                 ret = -EFAULT;
4626                 goto out;
4627         }
4628
4629         crtc->funcs->gamma_set(crtc, r_base, g_base, b_base, 0, crtc->gamma_size);
4630
4631 out:
4632         drm_modeset_unlock_all(dev);
4633         return ret;
4634
4635 }
4636
4637 /**
4638  * drm_mode_gamma_get_ioctl - get the gamma table
4639  * @dev: DRM device
4640  * @data: ioctl data
4641  * @file_priv: DRM file info
4642  *
4643  * Copy the current gamma table into the storage provided. This also provides
4644  * the gamma table size the driver expects, which can be used to size the
4645  * allocated storage.
4646  *
4647  * Called by the user via ioctl.
4648  *
4649  * Returns:
4650  * Zero on success, negative errno on failure.
4651  */
4652 int drm_mode_gamma_get_ioctl(struct drm_device *dev,
4653                              void *data, struct drm_file *file_priv)
4654 {
4655         struct drm_mode_crtc_lut *crtc_lut = data;
4656         struct drm_crtc *crtc;
4657         void *r_base, *g_base, *b_base;
4658         int size;
4659         int ret = 0;
4660
4661         if (!drm_core_check_feature(dev, DRIVER_MODESET))
4662                 return -EINVAL;
4663
4664         drm_modeset_lock_all(dev);
4665         crtc = drm_crtc_find(dev, crtc_lut->crtc_id);
4666         if (!crtc) {
4667                 ret = -ENOENT;
4668                 goto out;
4669         }
4670
4671         /* memcpy into gamma store */
4672         if (crtc_lut->gamma_size != crtc->gamma_size) {
4673                 ret = -EINVAL;
4674                 goto out;
4675         }
4676
4677         size = crtc_lut->gamma_size * (sizeof(uint16_t));
4678         r_base = crtc->gamma_store;
4679         if (copy_to_user((void __user *)(unsigned long)crtc_lut->red, r_base, size)) {
4680                 ret = -EFAULT;
4681                 goto out;
4682         }
4683
4684         g_base = r_base + size;
4685         if (copy_to_user((void __user *)(unsigned long)crtc_lut->green, g_base, size)) {
4686                 ret = -EFAULT;
4687                 goto out;
4688         }
4689
4690         b_base = g_base + size;
4691         if (copy_to_user((void __user *)(unsigned long)crtc_lut->blue, b_base, size)) {
4692                 ret = -EFAULT;
4693                 goto out;
4694         }
4695 out:
4696         drm_modeset_unlock_all(dev);
4697         return ret;
4698 }
4699
4700 /**
4701  * drm_mode_page_flip_ioctl - schedule an asynchronous fb update
4702  * @dev: DRM device
4703  * @data: ioctl data
4704  * @file_priv: DRM file info
4705  *
4706  * This schedules an asynchronous update on a given CRTC, called page flip.
4707  * Optionally a drm event is generated to signal the completion of the event.
4708  * Generic drivers cannot assume that a pageflip with changed framebuffer
4709  * properties (including driver specific metadata like tiling layout) will work,
4710  * but some drivers support e.g. pixel format changes through the pageflip
4711  * ioctl.
4712  *
4713  * Called by the user via ioctl.
4714  *
4715  * Returns:
4716  * Zero on success, negative errno on failure.
4717  */
4718 int drm_mode_page_flip_ioctl(struct drm_device *dev,
4719                              void *data, struct drm_file *file_priv)
4720 {
4721         struct drm_mode_crtc_page_flip *page_flip = data;
4722         struct drm_crtc *crtc;
4723         struct drm_framebuffer *fb = NULL;
4724         struct drm_pending_vblank_event *e = NULL;
4725         unsigned long flags;
4726         int ret = -EINVAL;
4727
4728         if (page_flip->flags & ~DRM_MODE_PAGE_FLIP_FLAGS ||
4729             page_flip->reserved != 0)
4730                 return -EINVAL;
4731
4732         if ((page_flip->flags & DRM_MODE_PAGE_FLIP_ASYNC) && !dev->mode_config.async_page_flip)
4733                 return -EINVAL;
4734
4735         crtc = drm_crtc_find(dev, page_flip->crtc_id);
4736         if (!crtc)
4737                 return -ENOENT;
4738
4739         drm_modeset_lock_crtc(crtc, crtc->primary);
4740         if (crtc->primary->fb == NULL) {
4741                 /* The framebuffer is currently unbound, presumably
4742                  * due to a hotplug event, that userspace has not
4743                  * yet discovered.
4744                  */
4745                 ret = -EBUSY;
4746                 goto out;
4747         }
4748
4749         if (crtc->funcs->page_flip == NULL)
4750                 goto out;
4751
4752         fb = drm_framebuffer_lookup(dev, page_flip->fb_id);
4753         if (!fb) {
4754                 ret = -ENOENT;
4755                 goto out;
4756         }
4757
4758         ret = drm_crtc_check_viewport(crtc, crtc->x, crtc->y, &crtc->mode, fb);
4759         if (ret)
4760                 goto out;
4761
4762         if (crtc->primary->fb->pixel_format != fb->pixel_format) {
4763                 DRM_DEBUG_KMS("Page flip is not allowed to change frame buffer format.\n");
4764                 ret = -EINVAL;
4765                 goto out;
4766         }
4767
4768         if (page_flip->flags & DRM_MODE_PAGE_FLIP_EVENT) {
4769                 ret = -ENOMEM;
4770                 spin_lock_irqsave(&dev->event_lock, flags);
4771                 if (file_priv->event_space < sizeof e->event) {
4772                         spin_unlock_irqrestore(&dev->event_lock, flags);
4773                         goto out;
4774                 }
4775                 file_priv->event_space -= sizeof e->event;
4776                 spin_unlock_irqrestore(&dev->event_lock, flags);
4777
4778                 e = kzalloc(sizeof *e, GFP_KERNEL);
4779                 if (e == NULL) {
4780                         spin_lock_irqsave(&dev->event_lock, flags);
4781                         file_priv->event_space += sizeof e->event;
4782                         spin_unlock_irqrestore(&dev->event_lock, flags);
4783                         goto out;
4784                 }
4785
4786                 e->event.base.type = DRM_EVENT_FLIP_COMPLETE;
4787                 e->event.base.length = sizeof e->event;
4788                 e->event.user_data = page_flip->user_data;
4789                 e->base.event = &e->event.base;
4790                 e->base.file_priv = file_priv;
4791                 e->base.destroy =
4792                         (void (*) (struct drm_pending_event *)) kfree;
4793         }
4794
4795         crtc->primary->old_fb = crtc->primary->fb;
4796         ret = crtc->funcs->page_flip(crtc, fb, e, page_flip->flags);
4797         if (ret) {
4798                 if (page_flip->flags & DRM_MODE_PAGE_FLIP_EVENT) {
4799                         spin_lock_irqsave(&dev->event_lock, flags);
4800                         file_priv->event_space += sizeof e->event;
4801                         spin_unlock_irqrestore(&dev->event_lock, flags);
4802                         kfree(e);
4803                 }
4804                 /* Keep the old fb, don't unref it. */
4805                 crtc->primary->old_fb = NULL;
4806         } else {
4807                 /*
4808                  * Warn if the driver hasn't properly updated the crtc->fb
4809                  * field to reflect that the new framebuffer is now used.
4810                  * Failing to do so will screw with the reference counting
4811                  * on framebuffers.
4812                  */
4813                 WARN_ON(crtc->primary->fb != fb);
4814                 /* Unref only the old framebuffer. */
4815                 fb = NULL;
4816         }
4817
4818 out:
4819         if (fb)
4820                 drm_framebuffer_unreference(fb);
4821         if (crtc->primary->old_fb)
4822                 drm_framebuffer_unreference(crtc->primary->old_fb);
4823         crtc->primary->old_fb = NULL;
4824         drm_modeset_unlock_crtc(crtc);
4825
4826         return ret;
4827 }
4828
4829 /**
4830  * drm_mode_config_reset - call ->reset callbacks
4831  * @dev: drm device
4832  *
4833  * This functions calls all the crtc's, encoder's and connector's ->reset
4834  * callback. Drivers can use this in e.g. their driver load or resume code to
4835  * reset hardware and software state.
4836  */
4837 void drm_mode_config_reset(struct drm_device *dev)
4838 {
4839         struct drm_crtc *crtc;
4840         struct drm_plane *plane;
4841         struct drm_encoder *encoder;
4842         struct drm_connector *connector;
4843
4844         list_for_each_entry(plane, &dev->mode_config.plane_list, head)
4845                 if (plane->funcs->reset)
4846                         plane->funcs->reset(plane);
4847
4848         list_for_each_entry(crtc, &dev->mode_config.crtc_list, head)
4849                 if (crtc->funcs->reset)
4850                         crtc->funcs->reset(crtc);
4851
4852         list_for_each_entry(encoder, &dev->mode_config.encoder_list, head)
4853                 if (encoder->funcs->reset)
4854                         encoder->funcs->reset(encoder);
4855
4856         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
4857                 connector->status = connector_status_unknown;
4858
4859                 if (connector->funcs->reset)
4860                         connector->funcs->reset(connector);
4861         }
4862 }
4863 EXPORT_SYMBOL(drm_mode_config_reset);
4864
4865 /**
4866  * drm_mode_create_dumb_ioctl - create a dumb backing storage buffer
4867  * @dev: DRM device
4868  * @data: ioctl data
4869  * @file_priv: DRM file info
4870  *
4871  * This creates a new dumb buffer in the driver's backing storage manager (GEM,
4872  * TTM or something else entirely) and returns the resulting buffer handle. This
4873  * handle can then be wrapped up into a framebuffer modeset object.
4874  *
4875  * Note that userspace is not allowed to use such objects for render
4876  * acceleration - drivers must create their own private ioctls for such a use
4877  * case.
4878  *
4879  * Called by the user via ioctl.
4880  *
4881  * Returns:
4882  * Zero on success, negative errno on failure.
4883  */
4884 int drm_mode_create_dumb_ioctl(struct drm_device *dev,
4885                                void *data, struct drm_file *file_priv)
4886 {
4887         struct drm_mode_create_dumb *args = data;
4888         u32 cpp, stride, size;
4889
4890         if (!dev->driver->dumb_create)
4891                 return -ENOSYS;
4892         if (!args->width || !args->height || !args->bpp)
4893                 return -EINVAL;
4894
4895         /* overflow checks for 32bit size calculations */
4896         /* NOTE: DIV_ROUND_UP() can overflow */
4897         cpp = DIV_ROUND_UP(args->bpp, 8);
4898         if (!cpp || cpp > 0xffffffffU / args->width)
4899                 return -EINVAL;
4900         stride = cpp * args->width;
4901         if (args->height > 0xffffffffU / stride)
4902                 return -EINVAL;
4903
4904         /* test for wrap-around */
4905         size = args->height * stride;
4906         if (PAGE_ALIGN(size) == 0)
4907                 return -EINVAL;
4908
4909         /*
4910          * handle, pitch and size are output parameters. Zero them out to
4911          * prevent drivers from accidentally using uninitialized data. Since
4912          * not all existing userspace is clearing these fields properly we
4913          * cannot reject IOCTL with garbage in them.
4914          */
4915         args->handle = 0;
4916         args->pitch = 0;
4917         args->size = 0;
4918
4919         return dev->driver->dumb_create(file_priv, dev, args);
4920 }
4921
4922 /**
4923  * drm_mode_mmap_dumb_ioctl - create an mmap offset for a dumb backing storage buffer
4924  * @dev: DRM device
4925  * @data: ioctl data
4926  * @file_priv: DRM file info
4927  *
4928  * Allocate an offset in the drm device node's address space to be able to
4929  * memory map a dumb buffer.
4930  *
4931  * Called by the user via ioctl.
4932  *
4933  * Returns:
4934  * Zero on success, negative errno on failure.
4935  */
4936 int drm_mode_mmap_dumb_ioctl(struct drm_device *dev,
4937                              void *data, struct drm_file *file_priv)
4938 {
4939         struct drm_mode_map_dumb *args = data;
4940
4941         /* call driver ioctl to get mmap offset */
4942         if (!dev->driver->dumb_map_offset)
4943                 return -ENOSYS;
4944
4945         return dev->driver->dumb_map_offset(file_priv, dev, args->handle, &args->offset);
4946 }
4947
4948 /**
4949  * drm_mode_destroy_dumb_ioctl - destroy a dumb backing strage buffer
4950  * @dev: DRM device
4951  * @data: ioctl data
4952  * @file_priv: DRM file info
4953  *
4954  * This destroys the userspace handle for the given dumb backing storage buffer.
4955  * Since buffer objects must be reference counted in the kernel a buffer object
4956  * won't be immediately freed if a framebuffer modeset object still uses it.
4957  *
4958  * Called by the user via ioctl.
4959  *
4960  * Returns:
4961  * Zero on success, negative errno on failure.
4962  */
4963 int drm_mode_destroy_dumb_ioctl(struct drm_device *dev,
4964                                 void *data, struct drm_file *file_priv)
4965 {
4966         struct drm_mode_destroy_dumb *args = data;
4967
4968         if (!dev->driver->dumb_destroy)
4969                 return -ENOSYS;
4970
4971         return dev->driver->dumb_destroy(file_priv, dev, args->handle);
4972 }
4973
4974 /**
4975  * drm_fb_get_bpp_depth - get the bpp/depth values for format
4976  * @format: pixel format (DRM_FORMAT_*)
4977  * @depth: storage for the depth value
4978  * @bpp: storage for the bpp value
4979  *
4980  * This only supports RGB formats here for compat with code that doesn't use
4981  * pixel formats directly yet.
4982  */
4983 void drm_fb_get_bpp_depth(uint32_t format, unsigned int *depth,
4984                           int *bpp)
4985 {
4986         switch (format) {
4987         case DRM_FORMAT_C8:
4988         case DRM_FORMAT_RGB332:
4989         case DRM_FORMAT_BGR233:
4990                 *depth = 8;
4991                 *bpp = 8;
4992                 break;
4993         case DRM_FORMAT_XRGB1555:
4994         case DRM_FORMAT_XBGR1555:
4995         case DRM_FORMAT_RGBX5551:
4996         case DRM_FORMAT_BGRX5551:
4997         case DRM_FORMAT_ARGB1555:
4998         case DRM_FORMAT_ABGR1555:
4999         case DRM_FORMAT_RGBA5551:
5000         case DRM_FORMAT_BGRA5551:
5001                 *depth = 15;
5002                 *bpp = 16;
5003                 break;
5004         case DRM_FORMAT_RGB565:
5005         case DRM_FORMAT_BGR565:
5006                 *depth = 16;
5007                 *bpp = 16;
5008                 break;
5009         case DRM_FORMAT_RGB888:
5010         case DRM_FORMAT_BGR888:
5011                 *depth = 24;
5012                 *bpp = 24;
5013                 break;
5014         case DRM_FORMAT_XRGB8888:
5015         case DRM_FORMAT_XBGR8888:
5016         case DRM_FORMAT_RGBX8888:
5017         case DRM_FORMAT_BGRX8888:
5018                 *depth = 24;
5019                 *bpp = 32;
5020                 break;
5021         case DRM_FORMAT_XRGB2101010:
5022         case DRM_FORMAT_XBGR2101010:
5023         case DRM_FORMAT_RGBX1010102:
5024         case DRM_FORMAT_BGRX1010102:
5025         case DRM_FORMAT_ARGB2101010:
5026         case DRM_FORMAT_ABGR2101010:
5027         case DRM_FORMAT_RGBA1010102:
5028         case DRM_FORMAT_BGRA1010102:
5029                 *depth = 30;
5030                 *bpp = 32;
5031                 break;
5032         case DRM_FORMAT_ARGB8888:
5033         case DRM_FORMAT_ABGR8888:
5034         case DRM_FORMAT_RGBA8888:
5035         case DRM_FORMAT_BGRA8888:
5036                 *depth = 32;
5037                 *bpp = 32;
5038                 break;
5039         default:
5040                 DRM_DEBUG_KMS("unsupported pixel format %s\n",
5041                               drm_get_format_name(format));
5042                 *depth = 0;
5043                 *bpp = 0;
5044                 break;
5045         }
5046 }
5047 EXPORT_SYMBOL(drm_fb_get_bpp_depth);
5048
5049 /**
5050  * drm_format_num_planes - get the number of planes for format
5051  * @format: pixel format (DRM_FORMAT_*)
5052  *
5053  * Returns:
5054  * The number of planes used by the specified pixel format.
5055  */
5056 int drm_format_num_planes(uint32_t format)
5057 {
5058         switch (format) {
5059         case DRM_FORMAT_YUV410:
5060         case DRM_FORMAT_YVU410:
5061         case DRM_FORMAT_YUV411:
5062         case DRM_FORMAT_YVU411:
5063         case DRM_FORMAT_YUV420:
5064         case DRM_FORMAT_YVU420:
5065         case DRM_FORMAT_YUV422:
5066         case DRM_FORMAT_YVU422:
5067         case DRM_FORMAT_YUV444:
5068         case DRM_FORMAT_YVU444:
5069                 return 3;
5070         case DRM_FORMAT_NV12:
5071         case DRM_FORMAT_NV21:
5072         case DRM_FORMAT_NV16:
5073         case DRM_FORMAT_NV61:
5074         case DRM_FORMAT_NV24:
5075         case DRM_FORMAT_NV42:
5076                 return 2;
5077         default:
5078                 return 1;
5079         }
5080 }
5081 EXPORT_SYMBOL(drm_format_num_planes);
5082
5083 /**
5084  * drm_format_plane_cpp - determine the bytes per pixel value
5085  * @format: pixel format (DRM_FORMAT_*)
5086  * @plane: plane index
5087  *
5088  * Returns:
5089  * The bytes per pixel value for the specified plane.
5090  */
5091 int drm_format_plane_cpp(uint32_t format, int plane)
5092 {
5093         unsigned int depth;
5094         int bpp;
5095
5096         if (plane >= drm_format_num_planes(format))
5097                 return 0;
5098
5099         switch (format) {
5100         case DRM_FORMAT_YUYV:
5101         case DRM_FORMAT_YVYU:
5102         case DRM_FORMAT_UYVY:
5103         case DRM_FORMAT_VYUY:
5104                 return 2;
5105         case DRM_FORMAT_NV12:
5106         case DRM_FORMAT_NV21:
5107         case DRM_FORMAT_NV16:
5108         case DRM_FORMAT_NV61:
5109         case DRM_FORMAT_NV24:
5110         case DRM_FORMAT_NV42:
5111                 return plane ? 2 : 1;
5112         case DRM_FORMAT_YUV410:
5113         case DRM_FORMAT_YVU410:
5114         case DRM_FORMAT_YUV411:
5115         case DRM_FORMAT_YVU411:
5116         case DRM_FORMAT_YUV420:
5117         case DRM_FORMAT_YVU420:
5118         case DRM_FORMAT_YUV422:
5119         case DRM_FORMAT_YVU422:
5120         case DRM_FORMAT_YUV444:
5121         case DRM_FORMAT_YVU444:
5122                 return 1;
5123         default:
5124                 drm_fb_get_bpp_depth(format, &depth, &bpp);
5125                 return bpp >> 3;
5126         }
5127 }
5128 EXPORT_SYMBOL(drm_format_plane_cpp);
5129
5130 /**
5131  * drm_format_horz_chroma_subsampling - get the horizontal chroma subsampling factor
5132  * @format: pixel format (DRM_FORMAT_*)
5133  *
5134  * Returns:
5135  * The horizontal chroma subsampling factor for the
5136  * specified pixel format.
5137  */
5138 int drm_format_horz_chroma_subsampling(uint32_t format)
5139 {
5140         switch (format) {
5141         case DRM_FORMAT_YUV411:
5142         case DRM_FORMAT_YVU411:
5143         case DRM_FORMAT_YUV410:
5144         case DRM_FORMAT_YVU410:
5145                 return 4;
5146         case DRM_FORMAT_YUYV:
5147         case DRM_FORMAT_YVYU:
5148         case DRM_FORMAT_UYVY:
5149         case DRM_FORMAT_VYUY:
5150         case DRM_FORMAT_NV12:
5151         case DRM_FORMAT_NV21:
5152         case DRM_FORMAT_NV16:
5153         case DRM_FORMAT_NV61:
5154         case DRM_FORMAT_YUV422:
5155         case DRM_FORMAT_YVU422:
5156         case DRM_FORMAT_YUV420:
5157         case DRM_FORMAT_YVU420:
5158                 return 2;
5159         default:
5160                 return 1;
5161         }
5162 }
5163 EXPORT_SYMBOL(drm_format_horz_chroma_subsampling);
5164
5165 /**
5166  * drm_format_vert_chroma_subsampling - get the vertical chroma subsampling factor
5167  * @format: pixel format (DRM_FORMAT_*)
5168  *
5169  * Returns:
5170  * The vertical chroma subsampling factor for the
5171  * specified pixel format.
5172  */
5173 int drm_format_vert_chroma_subsampling(uint32_t format)
5174 {
5175         switch (format) {
5176         case DRM_FORMAT_YUV410:
5177         case DRM_FORMAT_YVU410:
5178                 return 4;
5179         case DRM_FORMAT_YUV420:
5180         case DRM_FORMAT_YVU420:
5181         case DRM_FORMAT_NV12:
5182         case DRM_FORMAT_NV21:
5183                 return 2;
5184         default:
5185                 return 1;
5186         }
5187 }
5188 EXPORT_SYMBOL(drm_format_vert_chroma_subsampling);
5189
5190 /**
5191  * drm_rotation_simplify() - Try to simplify the rotation
5192  * @rotation: Rotation to be simplified
5193  * @supported_rotations: Supported rotations
5194  *
5195  * Attempt to simplify the rotation to a form that is supported.
5196  * Eg. if the hardware supports everything except DRM_REFLECT_X
5197  * one could call this function like this:
5198  *
5199  * drm_rotation_simplify(rotation, BIT(DRM_ROTATE_0) |
5200  *                       BIT(DRM_ROTATE_90) | BIT(DRM_ROTATE_180) |
5201  *                       BIT(DRM_ROTATE_270) | BIT(DRM_REFLECT_Y));
5202  *
5203  * to eliminate the DRM_ROTATE_X flag. Depending on what kind of
5204  * transforms the hardware supports, this function may not
5205  * be able to produce a supported transform, so the caller should
5206  * check the result afterwards.
5207  */
5208 unsigned int drm_rotation_simplify(unsigned int rotation,
5209                                    unsigned int supported_rotations)
5210 {
5211         if (rotation & ~supported_rotations) {
5212                 rotation ^= BIT(DRM_REFLECT_X) | BIT(DRM_REFLECT_Y);
5213                 rotation = (rotation & ~0xf) | BIT((ffs(rotation & 0xf) + 1) % 4);
5214         }
5215
5216         return rotation;
5217 }
5218 EXPORT_SYMBOL(drm_rotation_simplify);
5219
5220 /**
5221  * drm_mode_config_init - initialize DRM mode_configuration structure
5222  * @dev: DRM device
5223  *
5224  * Initialize @dev's mode_config structure, used for tracking the graphics
5225  * configuration of @dev.
5226  *
5227  * Since this initializes the modeset locks, no locking is possible. Which is no
5228  * problem, since this should happen single threaded at init time. It is the
5229  * driver's problem to ensure this guarantee.
5230  *
5231  */
5232 void drm_mode_config_init(struct drm_device *dev)
5233 {
5234         mutex_init(&dev->mode_config.mutex);
5235         drm_modeset_lock_init(&dev->mode_config.connection_mutex);
5236         mutex_init(&dev->mode_config.idr_mutex);
5237         mutex_init(&dev->mode_config.fb_lock);
5238         INIT_LIST_HEAD(&dev->mode_config.fb_list);
5239         INIT_LIST_HEAD(&dev->mode_config.crtc_list);
5240         INIT_LIST_HEAD(&dev->mode_config.connector_list);
5241         INIT_LIST_HEAD(&dev->mode_config.bridge_list);
5242         INIT_LIST_HEAD(&dev->mode_config.encoder_list);
5243         INIT_LIST_HEAD(&dev->mode_config.property_list);
5244         INIT_LIST_HEAD(&dev->mode_config.property_blob_list);
5245         INIT_LIST_HEAD(&dev->mode_config.plane_list);
5246         idr_init(&dev->mode_config.crtc_idr);
5247         idr_init(&dev->mode_config.tile_idr);
5248
5249         drm_modeset_lock_all(dev);
5250         drm_mode_create_standard_connector_properties(dev);
5251         drm_mode_create_standard_plane_properties(dev);
5252         drm_modeset_unlock_all(dev);
5253
5254         /* Just to be sure */
5255         dev->mode_config.num_fb = 0;
5256         dev->mode_config.num_connector = 0;
5257         dev->mode_config.num_crtc = 0;
5258         dev->mode_config.num_encoder = 0;
5259         dev->mode_config.num_overlay_plane = 0;
5260         dev->mode_config.num_total_plane = 0;
5261 }
5262 EXPORT_SYMBOL(drm_mode_config_init);
5263
5264 /**
5265  * drm_mode_config_cleanup - free up DRM mode_config info
5266  * @dev: DRM device
5267  *
5268  * Free up all the connectors and CRTCs associated with this DRM device, then
5269  * free up the framebuffers and associated buffer objects.
5270  *
5271  * Note that since this /should/ happen single-threaded at driver/device
5272  * teardown time, no locking is required. It's the driver's job to ensure that
5273  * this guarantee actually holds true.
5274  *
5275  * FIXME: cleanup any dangling user buffer objects too
5276  */
5277 void drm_mode_config_cleanup(struct drm_device *dev)
5278 {
5279         struct drm_connector *connector, *ot;
5280         struct drm_crtc *crtc, *ct;
5281         struct drm_encoder *encoder, *enct;
5282         struct drm_bridge *bridge, *brt;
5283         struct drm_framebuffer *fb, *fbt;
5284         struct drm_property *property, *pt;
5285         struct drm_property_blob *blob, *bt;
5286         struct drm_plane *plane, *plt;
5287
5288         list_for_each_entry_safe(encoder, enct, &dev->mode_config.encoder_list,
5289                                  head) {
5290                 encoder->funcs->destroy(encoder);
5291         }
5292
5293         list_for_each_entry_safe(bridge, brt,
5294                                  &dev->mode_config.bridge_list, head) {
5295                 bridge->funcs->destroy(bridge);
5296         }
5297
5298         list_for_each_entry_safe(connector, ot,
5299                                  &dev->mode_config.connector_list, head) {
5300                 connector->funcs->destroy(connector);
5301         }
5302
5303         list_for_each_entry_safe(property, pt, &dev->mode_config.property_list,
5304                                  head) {
5305                 drm_property_destroy(dev, property);
5306         }
5307
5308         list_for_each_entry_safe(blob, bt, &dev->mode_config.property_blob_list,
5309                                  head) {
5310                 drm_property_destroy_blob(dev, blob);
5311         }
5312
5313         /*
5314          * Single-threaded teardown context, so it's not required to grab the
5315          * fb_lock to protect against concurrent fb_list access. Contrary, it
5316          * would actually deadlock with the drm_framebuffer_cleanup function.
5317          *
5318          * Also, if there are any framebuffers left, that's a driver leak now,
5319          * so politely WARN about this.
5320          */
5321         WARN_ON(!list_empty(&dev->mode_config.fb_list));
5322         list_for_each_entry_safe(fb, fbt, &dev->mode_config.fb_list, head) {
5323                 drm_framebuffer_remove(fb);
5324         }
5325
5326         list_for_each_entry_safe(plane, plt, &dev->mode_config.plane_list,
5327                                  head) {
5328                 plane->funcs->destroy(plane);
5329         }
5330
5331         list_for_each_entry_safe(crtc, ct, &dev->mode_config.crtc_list, head) {
5332                 crtc->funcs->destroy(crtc);
5333         }
5334
5335         idr_destroy(&dev->mode_config.tile_idr);
5336         idr_destroy(&dev->mode_config.crtc_idr);
5337         drm_modeset_lock_fini(&dev->mode_config.connection_mutex);
5338 }
5339 EXPORT_SYMBOL(drm_mode_config_cleanup);
5340
5341 struct drm_property *drm_mode_create_rotation_property(struct drm_device *dev,
5342                                                        unsigned int supported_rotations)
5343 {
5344         static const struct drm_prop_enum_list props[] = {
5345                 { DRM_ROTATE_0,   "rotate-0" },
5346                 { DRM_ROTATE_90,  "rotate-90" },
5347                 { DRM_ROTATE_180, "rotate-180" },
5348                 { DRM_ROTATE_270, "rotate-270" },
5349                 { DRM_REFLECT_X,  "reflect-x" },
5350                 { DRM_REFLECT_Y,  "reflect-y" },
5351         };
5352
5353         return drm_property_create_bitmask(dev, 0, "rotation",
5354                                            props, ARRAY_SIZE(props),
5355                                            supported_rotations);
5356 }
5357 EXPORT_SYMBOL(drm_mode_create_rotation_property);
5358
5359 /**
5360  * DOC: Tile group
5361  *
5362  * Tile groups are used to represent tiled monitors with a unique
5363  * integer identifier. Tiled monitors using DisplayID v1.3 have
5364  * a unique 8-byte handle, we store this in a tile group, so we
5365  * have a common identifier for all tiles in a monitor group.
5366  */
5367 static void drm_tile_group_free(struct kref *kref)
5368 {
5369         struct drm_tile_group *tg = container_of(kref, struct drm_tile_group, refcount);
5370         struct drm_device *dev = tg->dev;
5371         mutex_lock(&dev->mode_config.idr_mutex);
5372         idr_remove(&dev->mode_config.tile_idr, tg->id);
5373         mutex_unlock(&dev->mode_config.idr_mutex);
5374         kfree(tg);
5375 }
5376
5377 /**
5378  * drm_mode_put_tile_group - drop a reference to a tile group.
5379  * @dev: DRM device
5380  * @tg: tile group to drop reference to.
5381  *
5382  * drop reference to tile group and free if 0.
5383  */
5384 void drm_mode_put_tile_group(struct drm_device *dev,
5385                              struct drm_tile_group *tg)
5386 {
5387         kref_put(&tg->refcount, drm_tile_group_free);
5388 }
5389
5390 /**
5391  * drm_mode_get_tile_group - get a reference to an existing tile group
5392  * @dev: DRM device
5393  * @topology: 8-bytes unique per monitor.
5394  *
5395  * Use the unique bytes to get a reference to an existing tile group.
5396  *
5397  * RETURNS:
5398  * tile group or NULL if not found.
5399  */
5400 struct drm_tile_group *drm_mode_get_tile_group(struct drm_device *dev,
5401                                                char topology[8])
5402 {
5403         struct drm_tile_group *tg;
5404         int id;
5405         mutex_lock(&dev->mode_config.idr_mutex);
5406         idr_for_each_entry(&dev->mode_config.tile_idr, tg, id) {
5407                 if (!memcmp(tg->group_data, topology, 8)) {
5408                         if (!kref_get_unless_zero(&tg->refcount))
5409                                 tg = NULL;
5410                         mutex_unlock(&dev->mode_config.idr_mutex);
5411                         return tg;
5412                 }
5413         }
5414         mutex_unlock(&dev->mode_config.idr_mutex);
5415         return NULL;
5416 }
5417
5418 /**
5419  * drm_mode_create_tile_group - create a tile group from a displayid description
5420  * @dev: DRM device
5421  * @topology: 8-bytes unique per monitor.
5422  *
5423  * Create a tile group for the unique monitor, and get a unique
5424  * identifier for the tile group.
5425  *
5426  * RETURNS:
5427  * new tile group or error.
5428  */
5429 struct drm_tile_group *drm_mode_create_tile_group(struct drm_device *dev,
5430                                                   char topology[8])
5431 {
5432         struct drm_tile_group *tg;
5433         int ret;
5434
5435         tg = kzalloc(sizeof(*tg), GFP_KERNEL);
5436         if (!tg)
5437                 return ERR_PTR(-ENOMEM);
5438
5439         kref_init(&tg->refcount);
5440         memcpy(tg->group_data, topology, 8);
5441         tg->dev = dev;
5442
5443         mutex_lock(&dev->mode_config.idr_mutex);
5444         ret = idr_alloc(&dev->mode_config.tile_idr, tg, 1, 0, GFP_KERNEL);
5445         if (ret >= 0) {
5446                 tg->id = ret;
5447         } else {
5448                 kfree(tg);
5449                 tg = ERR_PTR(ret);
5450         }
5451
5452         mutex_unlock(&dev->mode_config.idr_mutex);
5453         return tg;
5454 }