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