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