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