GNU Linux-libre 4.14.313-gnu1
[releases.git] / drivers / gpu / drm / drm_framebuffer.c
1 /*
2  * Copyright (c) 2016 Intel Corporation
3  *
4  * Permission to use, copy, modify, distribute, and sell this software and its
5  * documentation for any purpose is hereby granted without fee, provided that
6  * the above copyright notice appear in all copies and that both that copyright
7  * notice and this permission notice appear in supporting documentation, and
8  * that the name of the copyright holders not be used in advertising or
9  * publicity pertaining to distribution of the software without specific,
10  * written prior permission.  The copyright holders make no representations
11  * about the suitability of this software for any purpose.  It is provided "as
12  * is" without express or implied warranty.
13  *
14  * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
15  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
16  * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
17  * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
18  * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
19  * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
20  * OF THIS SOFTWARE.
21  */
22
23 #include <linux/export.h>
24 #include <drm/drmP.h>
25 #include <drm/drm_auth.h>
26 #include <drm/drm_framebuffer.h>
27 #include <drm/drm_atomic.h>
28
29 #include "drm_crtc_internal.h"
30
31 /**
32  * DOC: overview
33  *
34  * Frame buffers are abstract memory objects that provide a source of pixels to
35  * scanout to a CRTC. Applications explicitly request the creation of frame
36  * buffers through the DRM_IOCTL_MODE_ADDFB(2) ioctls and receive an opaque
37  * handle that can be passed to the KMS CRTC control, plane configuration and
38  * page flip functions.
39  *
40  * Frame buffers rely on the underlying memory manager for allocating backing
41  * storage. When creating a frame buffer applications pass a memory handle
42  * (or a list of memory handles for multi-planar formats) through the
43  * &struct drm_mode_fb_cmd2 argument. For drivers using GEM as their userspace
44  * buffer management interface this would be a GEM handle.  Drivers are however
45  * free to use their own backing storage object handles, e.g. vmwgfx directly
46  * exposes special TTM handles to userspace and so expects TTM handles in the
47  * create ioctl and not GEM handles.
48  *
49  * Framebuffers are tracked with &struct drm_framebuffer. They are published
50  * using drm_framebuffer_init() - after calling that function userspace can use
51  * and access the framebuffer object. The helper function
52  * drm_helper_mode_fill_fb_struct() can be used to pre-fill the required
53  * metadata fields.
54  *
55  * The lifetime of a drm framebuffer is controlled with a reference count,
56  * drivers can grab additional references with drm_framebuffer_get() and drop
57  * them again with drm_framebuffer_put(). For driver-private framebuffers for
58  * which the last reference is never dropped (e.g. for the fbdev framebuffer
59  * when the struct &struct drm_framebuffer is embedded into the fbdev helper
60  * struct) drivers can manually clean up a framebuffer at module unload time
61  * with drm_framebuffer_unregister_private(). But doing this is not
62  * recommended, and it's better to have a normal free-standing &struct
63  * drm_framebuffer.
64  */
65
66 int drm_framebuffer_check_src_coords(uint32_t src_x, uint32_t src_y,
67                                      uint32_t src_w, uint32_t src_h,
68                                      const struct drm_framebuffer *fb)
69 {
70         unsigned int fb_width, fb_height;
71
72         fb_width = fb->width << 16;
73         fb_height = fb->height << 16;
74
75         /* Make sure source coordinates are inside the fb. */
76         if (src_w > fb_width ||
77             src_x > fb_width - src_w ||
78             src_h > fb_height ||
79             src_y > fb_height - src_h) {
80                 DRM_DEBUG_KMS("Invalid source coordinates "
81                               "%u.%06ux%u.%06u+%u.%06u+%u.%06u\n",
82                               src_w >> 16, ((src_w & 0xffff) * 15625) >> 10,
83                               src_h >> 16, ((src_h & 0xffff) * 15625) >> 10,
84                               src_x >> 16, ((src_x & 0xffff) * 15625) >> 10,
85                               src_y >> 16, ((src_y & 0xffff) * 15625) >> 10);
86                 return -ENOSPC;
87         }
88
89         return 0;
90 }
91
92 /**
93  * drm_mode_addfb - add an FB to the graphics configuration
94  * @dev: drm device for the ioctl
95  * @data: data pointer for the ioctl
96  * @file_priv: drm file for the ioctl call
97  *
98  * Add a new FB to the specified CRTC, given a user request. This is the
99  * original addfb ioctl which only supported RGB formats.
100  *
101  * Called by the user via ioctl.
102  *
103  * Returns:
104  * Zero on success, negative errno on failure.
105  */
106 int drm_mode_addfb(struct drm_device *dev,
107                    void *data, struct drm_file *file_priv)
108 {
109         struct drm_mode_fb_cmd *or = data;
110         struct drm_mode_fb_cmd2 r = {};
111         int ret;
112
113         /* convert to new format and call new ioctl */
114         r.fb_id = or->fb_id;
115         r.width = or->width;
116         r.height = or->height;
117         r.pitches[0] = or->pitch;
118         r.pixel_format = drm_mode_legacy_fb_format(or->bpp, or->depth);
119         r.handles[0] = or->handle;
120
121         if (r.pixel_format == DRM_FORMAT_XRGB2101010 &&
122             dev->driver->driver_features & DRIVER_PREFER_XBGR_30BPP)
123                 r.pixel_format = DRM_FORMAT_XBGR2101010;
124
125         ret = drm_mode_addfb2(dev, &r, file_priv);
126         if (ret)
127                 return ret;
128
129         or->fb_id = r.fb_id;
130
131         return 0;
132 }
133
134 static int fb_plane_width(int width,
135                           const struct drm_format_info *format, int plane)
136 {
137         if (plane == 0)
138                 return width;
139
140         return DIV_ROUND_UP(width, format->hsub);
141 }
142
143 static int fb_plane_height(int height,
144                            const struct drm_format_info *format, int plane)
145 {
146         if (plane == 0)
147                 return height;
148
149         return DIV_ROUND_UP(height, format->vsub);
150 }
151
152 static int framebuffer_check(struct drm_device *dev,
153                              const struct drm_mode_fb_cmd2 *r)
154 {
155         const struct drm_format_info *info;
156         int i;
157
158         /* check if the format is supported at all */
159         info = __drm_format_info(r->pixel_format & ~DRM_FORMAT_BIG_ENDIAN);
160         if (!info) {
161                 struct drm_format_name_buf format_name;
162                 DRM_DEBUG_KMS("bad framebuffer format %s\n",
163                               drm_get_format_name(r->pixel_format,
164                                                   &format_name));
165                 return -EINVAL;
166         }
167
168         /* now let the driver pick its own format info */
169         info = drm_get_format_info(dev, r);
170
171         if (r->width == 0) {
172                 DRM_DEBUG_KMS("bad framebuffer width %u\n", r->width);
173                 return -EINVAL;
174         }
175
176         if (r->height == 0) {
177                 DRM_DEBUG_KMS("bad framebuffer height %u\n", r->height);
178                 return -EINVAL;
179         }
180
181         for (i = 0; i < info->num_planes; i++) {
182                 unsigned int width = fb_plane_width(r->width, info, i);
183                 unsigned int height = fb_plane_height(r->height, info, i);
184                 unsigned int cpp = info->cpp[i];
185
186                 if (!r->handles[i]) {
187                         DRM_DEBUG_KMS("no buffer object handle for plane %d\n", i);
188                         return -EINVAL;
189                 }
190
191                 if ((uint64_t) width * cpp > UINT_MAX)
192                         return -ERANGE;
193
194                 if ((uint64_t) height * r->pitches[i] + r->offsets[i] > UINT_MAX)
195                         return -ERANGE;
196
197                 if (r->pitches[i] < width * cpp) {
198                         DRM_DEBUG_KMS("bad pitch %u for plane %d\n", r->pitches[i], i);
199                         return -EINVAL;
200                 }
201
202                 if (r->modifier[i] && !(r->flags & DRM_MODE_FB_MODIFIERS)) {
203                         DRM_DEBUG_KMS("bad fb modifier %llu for plane %d\n",
204                                       r->modifier[i], i);
205                         return -EINVAL;
206                 }
207
208                 if (r->flags & DRM_MODE_FB_MODIFIERS &&
209                     r->modifier[i] != r->modifier[0]) {
210                         DRM_DEBUG_KMS("bad fb modifier %llu for plane %d\n",
211                                       r->modifier[i], i);
212                         return -EINVAL;
213                 }
214
215                 /* modifier specific checks: */
216                 switch (r->modifier[i]) {
217                 case DRM_FORMAT_MOD_SAMSUNG_64_32_TILE:
218                         /* NOTE: the pitch restriction may be lifted later if it turns
219                          * out that no hw has this restriction:
220                          */
221                         if (r->pixel_format != DRM_FORMAT_NV12 ||
222                                         width % 128 || height % 32 ||
223                                         r->pitches[i] % 128) {
224                                 DRM_DEBUG_KMS("bad modifier data for plane %d\n", i);
225                                 return -EINVAL;
226                         }
227                         break;
228
229                 default:
230                         break;
231                 }
232         }
233
234         for (i = info->num_planes; i < 4; i++) {
235                 if (r->modifier[i]) {
236                         DRM_DEBUG_KMS("non-zero modifier for unused plane %d\n", i);
237                         return -EINVAL;
238                 }
239
240                 /* Pre-FB_MODIFIERS userspace didn't clear the structs properly. */
241                 if (!(r->flags & DRM_MODE_FB_MODIFIERS))
242                         continue;
243
244                 if (r->handles[i]) {
245                         DRM_DEBUG_KMS("buffer object handle for unused plane %d\n", i);
246                         return -EINVAL;
247                 }
248
249                 if (r->pitches[i]) {
250                         DRM_DEBUG_KMS("non-zero pitch for unused plane %d\n", i);
251                         return -EINVAL;
252                 }
253
254                 if (r->offsets[i]) {
255                         DRM_DEBUG_KMS("non-zero offset for unused plane %d\n", i);
256                         return -EINVAL;
257                 }
258         }
259
260         return 0;
261 }
262
263 struct drm_framebuffer *
264 drm_internal_framebuffer_create(struct drm_device *dev,
265                                 const struct drm_mode_fb_cmd2 *r,
266                                 struct drm_file *file_priv)
267 {
268         struct drm_mode_config *config = &dev->mode_config;
269         struct drm_framebuffer *fb;
270         int ret;
271
272         if (r->flags & ~(DRM_MODE_FB_INTERLACED | DRM_MODE_FB_MODIFIERS)) {
273                 DRM_DEBUG_KMS("bad framebuffer flags 0x%08x\n", r->flags);
274                 return ERR_PTR(-EINVAL);
275         }
276
277         if ((config->min_width > r->width) || (r->width > config->max_width)) {
278                 DRM_DEBUG_KMS("bad framebuffer width %d, should be >= %d && <= %d\n",
279                           r->width, config->min_width, config->max_width);
280                 return ERR_PTR(-EINVAL);
281         }
282         if ((config->min_height > r->height) || (r->height > config->max_height)) {
283                 DRM_DEBUG_KMS("bad framebuffer height %d, should be >= %d && <= %d\n",
284                           r->height, config->min_height, config->max_height);
285                 return ERR_PTR(-EINVAL);
286         }
287
288         if (r->flags & DRM_MODE_FB_MODIFIERS &&
289             !dev->mode_config.allow_fb_modifiers) {
290                 DRM_DEBUG_KMS("driver does not support fb modifiers\n");
291                 return ERR_PTR(-EINVAL);
292         }
293
294         ret = framebuffer_check(dev, r);
295         if (ret)
296                 return ERR_PTR(ret);
297
298         fb = dev->mode_config.funcs->fb_create(dev, file_priv, r);
299         if (IS_ERR(fb)) {
300                 DRM_DEBUG_KMS("could not create framebuffer\n");
301                 return fb;
302         }
303
304         return fb;
305 }
306
307 /**
308  * drm_mode_addfb2 - add an FB to the graphics configuration
309  * @dev: drm device for the ioctl
310  * @data: data pointer for the ioctl
311  * @file_priv: drm file for the ioctl call
312  *
313  * Add a new FB to the specified CRTC, given a user request with format. This is
314  * the 2nd version of the addfb ioctl, which supports multi-planar framebuffers
315  * and uses fourcc codes as pixel format specifiers.
316  *
317  * Called by the user via ioctl.
318  *
319  * Returns:
320  * Zero on success, negative errno on failure.
321  */
322 int drm_mode_addfb2(struct drm_device *dev,
323                     void *data, struct drm_file *file_priv)
324 {
325         struct drm_mode_fb_cmd2 *r = data;
326         struct drm_framebuffer *fb;
327
328         if (!drm_core_check_feature(dev, DRIVER_MODESET))
329                 return -EINVAL;
330
331         fb = drm_internal_framebuffer_create(dev, r, file_priv);
332         if (IS_ERR(fb))
333                 return PTR_ERR(fb);
334
335         DRM_DEBUG_KMS("[FB:%d]\n", fb->base.id);
336         r->fb_id = fb->base.id;
337
338         /* Transfer ownership to the filp for reaping on close */
339         mutex_lock(&file_priv->fbs_lock);
340         list_add(&fb->filp_head, &file_priv->fbs);
341         mutex_unlock(&file_priv->fbs_lock);
342
343         return 0;
344 }
345
346 struct drm_mode_rmfb_work {
347         struct work_struct work;
348         struct list_head fbs;
349 };
350
351 static void drm_mode_rmfb_work_fn(struct work_struct *w)
352 {
353         struct drm_mode_rmfb_work *arg = container_of(w, typeof(*arg), work);
354
355         while (!list_empty(&arg->fbs)) {
356                 struct drm_framebuffer *fb =
357                         list_first_entry(&arg->fbs, typeof(*fb), filp_head);
358
359                 list_del_init(&fb->filp_head);
360                 drm_framebuffer_remove(fb);
361         }
362 }
363
364 /**
365  * drm_mode_rmfb - remove an FB from the configuration
366  * @dev: drm device for the ioctl
367  * @data: data pointer for the ioctl
368  * @file_priv: drm file for the ioctl call
369  *
370  * Remove the FB specified by the user.
371  *
372  * Called by the user via ioctl.
373  *
374  * Returns:
375  * Zero on success, negative errno on failure.
376  */
377 int drm_mode_rmfb(struct drm_device *dev,
378                    void *data, struct drm_file *file_priv)
379 {
380         struct drm_framebuffer *fb = NULL;
381         struct drm_framebuffer *fbl = NULL;
382         uint32_t *id = data;
383         int found = 0;
384
385         if (!drm_core_check_feature(dev, DRIVER_MODESET))
386                 return -EINVAL;
387
388         fb = drm_framebuffer_lookup(dev, *id);
389         if (!fb)
390                 return -ENOENT;
391
392         mutex_lock(&file_priv->fbs_lock);
393         list_for_each_entry(fbl, &file_priv->fbs, filp_head)
394                 if (fb == fbl)
395                         found = 1;
396         if (!found) {
397                 mutex_unlock(&file_priv->fbs_lock);
398                 goto fail_unref;
399         }
400
401         list_del_init(&fb->filp_head);
402         mutex_unlock(&file_priv->fbs_lock);
403
404         /* drop the reference we picked up in framebuffer lookup */
405         drm_framebuffer_put(fb);
406
407         /*
408          * we now own the reference that was stored in the fbs list
409          *
410          * drm_framebuffer_remove may fail with -EINTR on pending signals,
411          * so run this in a separate stack as there's no way to correctly
412          * handle this after the fb is already removed from the lookup table.
413          */
414         if (drm_framebuffer_read_refcount(fb) > 1) {
415                 struct drm_mode_rmfb_work arg;
416
417                 INIT_WORK_ONSTACK(&arg.work, drm_mode_rmfb_work_fn);
418                 INIT_LIST_HEAD(&arg.fbs);
419                 list_add_tail(&fb->filp_head, &arg.fbs);
420
421                 schedule_work(&arg.work);
422                 flush_work(&arg.work);
423                 destroy_work_on_stack(&arg.work);
424         } else
425                 drm_framebuffer_put(fb);
426
427         return 0;
428
429 fail_unref:
430         drm_framebuffer_put(fb);
431         return -ENOENT;
432 }
433
434 /**
435  * drm_mode_getfb - get FB info
436  * @dev: drm device for the ioctl
437  * @data: data pointer for the ioctl
438  * @file_priv: drm file for the ioctl call
439  *
440  * Lookup the FB given its ID and return info about it.
441  *
442  * Called by the user via ioctl.
443  *
444  * Returns:
445  * Zero on success, negative errno on failure.
446  */
447 int drm_mode_getfb(struct drm_device *dev,
448                    void *data, struct drm_file *file_priv)
449 {
450         struct drm_mode_fb_cmd *r = data;
451         struct drm_framebuffer *fb;
452         int ret;
453
454         if (!drm_core_check_feature(dev, DRIVER_MODESET))
455                 return -EINVAL;
456
457         fb = drm_framebuffer_lookup(dev, r->fb_id);
458         if (!fb)
459                 return -ENOENT;
460
461         /* Multi-planar framebuffers need getfb2. */
462         if (fb->format->num_planes > 1) {
463                 ret = -EINVAL;
464                 goto out;
465         }
466
467         r->height = fb->height;
468         r->width = fb->width;
469         r->depth = fb->format->depth;
470         r->bpp = fb->format->cpp[0] * 8;
471         r->pitch = fb->pitches[0];
472         if (fb->funcs->create_handle) {
473                 if (drm_is_current_master(file_priv) || capable(CAP_SYS_ADMIN) ||
474                     drm_is_control_client(file_priv)) {
475                         ret = fb->funcs->create_handle(fb, file_priv,
476                                                        &r->handle);
477                 } else {
478                         /* GET_FB() is an unprivileged ioctl so we must not
479                          * return a buffer-handle to non-master processes! For
480                          * backwards-compatibility reasons, we cannot make
481                          * GET_FB() privileged, so just return an invalid handle
482                          * for non-masters. */
483                         r->handle = 0;
484                         ret = 0;
485                 }
486         } else {
487                 ret = -ENODEV;
488         }
489
490 out:
491         drm_framebuffer_put(fb);
492
493         return ret;
494 }
495
496 /**
497  * drm_mode_dirtyfb_ioctl - flush frontbuffer rendering on an FB
498  * @dev: drm device for the ioctl
499  * @data: data pointer for the ioctl
500  * @file_priv: drm file for the ioctl call
501  *
502  * Lookup the FB and flush out the damaged area supplied by userspace as a clip
503  * rectangle list. Generic userspace which does frontbuffer rendering must call
504  * this ioctl to flush out the changes on manual-update display outputs, e.g.
505  * usb display-link, mipi manual update panels or edp panel self refresh modes.
506  *
507  * Modesetting drivers which always update the frontbuffer do not need to
508  * implement the corresponding &drm_framebuffer_funcs.dirty callback.
509  *
510  * Called by the user via ioctl.
511  *
512  * Returns:
513  * Zero on success, negative errno on failure.
514  */
515 int drm_mode_dirtyfb_ioctl(struct drm_device *dev,
516                            void *data, struct drm_file *file_priv)
517 {
518         struct drm_clip_rect __user *clips_ptr;
519         struct drm_clip_rect *clips = NULL;
520         struct drm_mode_fb_dirty_cmd *r = data;
521         struct drm_framebuffer *fb;
522         unsigned flags;
523         int num_clips;
524         int ret;
525
526         if (!drm_core_check_feature(dev, DRIVER_MODESET))
527                 return -EINVAL;
528
529         fb = drm_framebuffer_lookup(dev, r->fb_id);
530         if (!fb)
531                 return -ENOENT;
532
533         num_clips = r->num_clips;
534         clips_ptr = (struct drm_clip_rect __user *)(unsigned long)r->clips_ptr;
535
536         if (!num_clips != !clips_ptr) {
537                 ret = -EINVAL;
538                 goto out_err1;
539         }
540
541         flags = DRM_MODE_FB_DIRTY_FLAGS & r->flags;
542
543         /* If userspace annotates copy, clips must come in pairs */
544         if (flags & DRM_MODE_FB_DIRTY_ANNOTATE_COPY && (num_clips % 2)) {
545                 ret = -EINVAL;
546                 goto out_err1;
547         }
548
549         if (num_clips && clips_ptr) {
550                 if (num_clips < 0 || num_clips > DRM_MODE_FB_DIRTY_MAX_CLIPS) {
551                         ret = -EINVAL;
552                         goto out_err1;
553                 }
554                 clips = kcalloc(num_clips, sizeof(*clips), GFP_KERNEL);
555                 if (!clips) {
556                         ret = -ENOMEM;
557                         goto out_err1;
558                 }
559
560                 ret = copy_from_user(clips, clips_ptr,
561                                      num_clips * sizeof(*clips));
562                 if (ret) {
563                         ret = -EFAULT;
564                         goto out_err2;
565                 }
566         }
567
568         if (fb->funcs->dirty) {
569                 ret = fb->funcs->dirty(fb, file_priv, flags, r->color,
570                                        clips, num_clips);
571         } else {
572                 ret = -ENOSYS;
573         }
574
575 out_err2:
576         kfree(clips);
577 out_err1:
578         drm_framebuffer_put(fb);
579
580         return ret;
581 }
582
583 /**
584  * drm_fb_release - remove and free the FBs on this file
585  * @priv: drm file for the ioctl
586  *
587  * Destroy all the FBs associated with @filp.
588  *
589  * Called by the user via ioctl.
590  *
591  * Returns:
592  * Zero on success, negative errno on failure.
593  */
594 void drm_fb_release(struct drm_file *priv)
595 {
596         struct drm_framebuffer *fb, *tfb;
597         struct drm_mode_rmfb_work arg;
598
599         INIT_LIST_HEAD(&arg.fbs);
600
601         /*
602          * When the file gets released that means no one else can access the fb
603          * list any more, so no need to grab fpriv->fbs_lock. And we need to
604          * avoid upsetting lockdep since the universal cursor code adds a
605          * framebuffer while holding mutex locks.
606          *
607          * Note that a real deadlock between fpriv->fbs_lock and the modeset
608          * locks is impossible here since no one else but this function can get
609          * at it any more.
610          */
611         list_for_each_entry_safe(fb, tfb, &priv->fbs, filp_head) {
612                 if (drm_framebuffer_read_refcount(fb) > 1) {
613                         list_move_tail(&fb->filp_head, &arg.fbs);
614                 } else {
615                         list_del_init(&fb->filp_head);
616
617                         /* This drops the fpriv->fbs reference. */
618                         drm_framebuffer_put(fb);
619                 }
620         }
621
622         if (!list_empty(&arg.fbs)) {
623                 INIT_WORK_ONSTACK(&arg.work, drm_mode_rmfb_work_fn);
624
625                 schedule_work(&arg.work);
626                 flush_work(&arg.work);
627                 destroy_work_on_stack(&arg.work);
628         }
629 }
630
631 void drm_framebuffer_free(struct kref *kref)
632 {
633         struct drm_framebuffer *fb =
634                         container_of(kref, struct drm_framebuffer, base.refcount);
635         struct drm_device *dev = fb->dev;
636
637         /*
638          * The lookup idr holds a weak reference, which has not necessarily been
639          * removed at this point. Check for that.
640          */
641         drm_mode_object_unregister(dev, &fb->base);
642
643         fb->funcs->destroy(fb);
644 }
645
646 /**
647  * drm_framebuffer_init - initialize a framebuffer
648  * @dev: DRM device
649  * @fb: framebuffer to be initialized
650  * @funcs: ... with these functions
651  *
652  * Allocates an ID for the framebuffer's parent mode object, sets its mode
653  * functions & device file and adds it to the master fd list.
654  *
655  * IMPORTANT:
656  * This functions publishes the fb and makes it available for concurrent access
657  * by other users. Which means by this point the fb _must_ be fully set up -
658  * since all the fb attributes are invariant over its lifetime, no further
659  * locking but only correct reference counting is required.
660  *
661  * Returns:
662  * Zero on success, error code on failure.
663  */
664 int drm_framebuffer_init(struct drm_device *dev, struct drm_framebuffer *fb,
665                          const struct drm_framebuffer_funcs *funcs)
666 {
667         int ret;
668
669         if (WARN_ON_ONCE(fb->dev != dev || !fb->format))
670                 return -EINVAL;
671
672         INIT_LIST_HEAD(&fb->filp_head);
673
674         fb->funcs = funcs;
675
676         ret = __drm_mode_object_add(dev, &fb->base, DRM_MODE_OBJECT_FB,
677                                     false, drm_framebuffer_free);
678         if (ret)
679                 goto out;
680
681         mutex_lock(&dev->mode_config.fb_lock);
682         dev->mode_config.num_fb++;
683         list_add(&fb->head, &dev->mode_config.fb_list);
684         mutex_unlock(&dev->mode_config.fb_lock);
685
686         drm_mode_object_register(dev, &fb->base);
687 out:
688         return ret;
689 }
690 EXPORT_SYMBOL(drm_framebuffer_init);
691
692 /**
693  * drm_framebuffer_lookup - look up a drm framebuffer and grab a reference
694  * @dev: drm device
695  * @id: id of the fb object
696  *
697  * If successful, this grabs an additional reference to the framebuffer -
698  * callers need to make sure to eventually unreference the returned framebuffer
699  * again, using drm_framebuffer_put().
700  */
701 struct drm_framebuffer *drm_framebuffer_lookup(struct drm_device *dev,
702                                                uint32_t id)
703 {
704         struct drm_mode_object *obj;
705         struct drm_framebuffer *fb = NULL;
706
707         obj = __drm_mode_object_find(dev, id, DRM_MODE_OBJECT_FB);
708         if (obj)
709                 fb = obj_to_fb(obj);
710         return fb;
711 }
712 EXPORT_SYMBOL(drm_framebuffer_lookup);
713
714 /**
715  * drm_framebuffer_unregister_private - unregister a private fb from the lookup idr
716  * @fb: fb to unregister
717  *
718  * Drivers need to call this when cleaning up driver-private framebuffers, e.g.
719  * those used for fbdev. Note that the caller must hold a reference of it's own,
720  * i.e. the object may not be destroyed through this call (since it'll lead to a
721  * locking inversion).
722  *
723  * NOTE: This function is deprecated. For driver-private framebuffers it is not
724  * recommended to embed a framebuffer struct info fbdev struct, instead, a
725  * framebuffer pointer is preferred and drm_framebuffer_put() should be called
726  * when the framebuffer is to be cleaned up.
727  */
728 void drm_framebuffer_unregister_private(struct drm_framebuffer *fb)
729 {
730         struct drm_device *dev;
731
732         if (!fb)
733                 return;
734
735         dev = fb->dev;
736
737         /* Mark fb as reaped and drop idr ref. */
738         drm_mode_object_unregister(dev, &fb->base);
739 }
740 EXPORT_SYMBOL(drm_framebuffer_unregister_private);
741
742 /**
743  * drm_framebuffer_cleanup - remove a framebuffer object
744  * @fb: framebuffer to remove
745  *
746  * Cleanup framebuffer. This function is intended to be used from the drivers
747  * &drm_framebuffer_funcs.destroy callback. It can also be used to clean up
748  * driver private framebuffers embedded into a larger structure.
749  *
750  * Note that this function does not remove the fb from active usage - if it is
751  * still used anywhere, hilarity can ensue since userspace could call getfb on
752  * the id and get back -EINVAL. Obviously no concern at driver unload time.
753  *
754  * Also, the framebuffer will not be removed from the lookup idr - for
755  * user-created framebuffers this will happen in in the rmfb ioctl. For
756  * driver-private objects (e.g. for fbdev) drivers need to explicitly call
757  * drm_framebuffer_unregister_private.
758  */
759 void drm_framebuffer_cleanup(struct drm_framebuffer *fb)
760 {
761         struct drm_device *dev = fb->dev;
762
763         mutex_lock(&dev->mode_config.fb_lock);
764         list_del(&fb->head);
765         dev->mode_config.num_fb--;
766         mutex_unlock(&dev->mode_config.fb_lock);
767 }
768 EXPORT_SYMBOL(drm_framebuffer_cleanup);
769
770 static int atomic_remove_fb(struct drm_framebuffer *fb)
771 {
772         struct drm_modeset_acquire_ctx ctx;
773         struct drm_device *dev = fb->dev;
774         struct drm_atomic_state *state;
775         struct drm_plane *plane;
776         struct drm_connector *conn __maybe_unused;
777         struct drm_connector_state *conn_state;
778         int i, ret = 0;
779         unsigned plane_mask;
780
781         state = drm_atomic_state_alloc(dev);
782         if (!state)
783                 return -ENOMEM;
784
785         drm_modeset_acquire_init(&ctx, 0);
786         state->acquire_ctx = &ctx;
787
788 retry:
789         plane_mask = 0;
790         ret = drm_modeset_lock_all_ctx(dev, &ctx);
791         if (ret)
792                 goto unlock;
793
794         drm_for_each_plane(plane, dev) {
795                 struct drm_plane_state *plane_state;
796
797                 if (plane->state->fb != fb)
798                         continue;
799
800                 plane_state = drm_atomic_get_plane_state(state, plane);
801                 if (IS_ERR(plane_state)) {
802                         ret = PTR_ERR(plane_state);
803                         goto unlock;
804                 }
805
806                 if (plane_state->crtc->primary == plane) {
807                         struct drm_crtc_state *crtc_state;
808
809                         crtc_state = drm_atomic_get_existing_crtc_state(state, plane_state->crtc);
810
811                         ret = drm_atomic_add_affected_connectors(state, plane_state->crtc);
812                         if (ret)
813                                 goto unlock;
814
815                         crtc_state->active = false;
816                         ret = drm_atomic_set_mode_for_crtc(crtc_state, NULL);
817                         if (ret)
818                                 goto unlock;
819                 }
820
821                 drm_atomic_set_fb_for_plane(plane_state, NULL);
822                 ret = drm_atomic_set_crtc_for_plane(plane_state, NULL);
823                 if (ret)
824                         goto unlock;
825
826                 plane_mask |= BIT(drm_plane_index(plane));
827
828                 plane->old_fb = plane->fb;
829         }
830
831         for_each_new_connector_in_state(state, conn, conn_state, i) {
832                 ret = drm_atomic_set_crtc_for_connector(conn_state, NULL);
833
834                 if (ret)
835                         goto unlock;
836         }
837
838         if (plane_mask)
839                 ret = drm_atomic_commit(state);
840
841 unlock:
842         if (plane_mask)
843                 drm_atomic_clean_old_fb(dev, plane_mask, ret);
844
845         if (ret == -EDEADLK) {
846                 drm_atomic_state_clear(state);
847                 drm_modeset_backoff(&ctx);
848                 goto retry;
849         }
850
851         drm_atomic_state_put(state);
852
853         drm_modeset_drop_locks(&ctx);
854         drm_modeset_acquire_fini(&ctx);
855
856         return ret;
857 }
858
859 static void legacy_remove_fb(struct drm_framebuffer *fb)
860 {
861         struct drm_device *dev = fb->dev;
862         struct drm_crtc *crtc;
863         struct drm_plane *plane;
864
865         drm_modeset_lock_all(dev);
866         /* remove from any CRTC */
867         drm_for_each_crtc(crtc, dev) {
868                 if (crtc->primary->fb == fb) {
869                         /* should turn off the crtc */
870                         if (drm_crtc_force_disable(crtc))
871                                 DRM_ERROR("failed to reset crtc %p when fb was deleted\n", crtc);
872                 }
873         }
874
875         drm_for_each_plane(plane, dev) {
876                 if (plane->fb == fb)
877                         drm_plane_force_disable(plane);
878         }
879         drm_modeset_unlock_all(dev);
880 }
881
882 /**
883  * drm_framebuffer_remove - remove and unreference a framebuffer object
884  * @fb: framebuffer to remove
885  *
886  * Scans all the CRTCs and planes in @dev's mode_config.  If they're
887  * using @fb, removes it, setting it to NULL. Then drops the reference to the
888  * passed-in framebuffer. Might take the modeset locks.
889  *
890  * Note that this function optimizes the cleanup away if the caller holds the
891  * last reference to the framebuffer. It is also guaranteed to not take the
892  * modeset locks in this case.
893  */
894 void drm_framebuffer_remove(struct drm_framebuffer *fb)
895 {
896         struct drm_device *dev;
897
898         if (!fb)
899                 return;
900
901         dev = fb->dev;
902
903         WARN_ON(!list_empty(&fb->filp_head));
904
905         /*
906          * drm ABI mandates that we remove any deleted framebuffers from active
907          * useage. But since most sane clients only remove framebuffers they no
908          * longer need, try to optimize this away.
909          *
910          * Since we're holding a reference ourselves, observing a refcount of 1
911          * means that we're the last holder and can skip it. Also, the refcount
912          * can never increase from 1 again, so we don't need any barriers or
913          * locks.
914          *
915          * Note that userspace could try to race with use and instate a new
916          * usage _after_ we've cleared all current ones. End result will be an
917          * in-use fb with fb-id == 0. Userspace is allowed to shoot its own foot
918          * in this manner.
919          */
920         if (drm_framebuffer_read_refcount(fb) > 1) {
921                 if (drm_drv_uses_atomic_modeset(dev)) {
922                         int ret = atomic_remove_fb(fb);
923                         WARN(ret, "atomic remove_fb failed with %i\n", ret);
924                 } else
925                         legacy_remove_fb(fb);
926         }
927
928         drm_framebuffer_put(fb);
929 }
930 EXPORT_SYMBOL(drm_framebuffer_remove);
931
932 /**
933  * drm_framebuffer_plane_width - width of the plane given the first plane
934  * @width: width of the first plane
935  * @fb: the framebuffer
936  * @plane: plane index
937  *
938  * Returns:
939  * The width of @plane, given that the width of the first plane is @width.
940  */
941 int drm_framebuffer_plane_width(int width,
942                                 const struct drm_framebuffer *fb, int plane)
943 {
944         if (plane >= fb->format->num_planes)
945                 return 0;
946
947         return fb_plane_width(width, fb->format, plane);
948 }
949 EXPORT_SYMBOL(drm_framebuffer_plane_width);
950
951 /**
952  * drm_framebuffer_plane_height - height of the plane given the first plane
953  * @height: height of the first plane
954  * @fb: the framebuffer
955  * @plane: plane index
956  *
957  * Returns:
958  * The height of @plane, given that the height of the first plane is @height.
959  */
960 int drm_framebuffer_plane_height(int height,
961                                  const struct drm_framebuffer *fb, int plane)
962 {
963         if (plane >= fb->format->num_planes)
964                 return 0;
965
966         return fb_plane_height(height, fb->format, plane);
967 }
968 EXPORT_SYMBOL(drm_framebuffer_plane_height);