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