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