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