Merge remote-tracking branch 'stable/linux-5.15.y' into rpi-5.15.y
[platform/kernel/linux-rpi.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 <linux/uaccess.h>
25
26 #include <drm/drm_atomic.h>
27 #include <drm/drm_atomic_uapi.h>
28 #include <drm/drm_auth.h>
29 #include <drm/drm_debugfs.h>
30 #include <drm/drm_drv.h>
31 #include <drm/drm_file.h>
32 #include <drm/drm_fourcc.h>
33 #include <drm/drm_framebuffer.h>
34 #include <drm/drm_gem.h>
35 #include <drm/drm_print.h>
36 #include <drm/drm_util.h>
37
38 #include "drm_crtc_internal.h"
39 #include "drm_internal.h"
40
41 /**
42  * DOC: overview
43  *
44  * Frame buffers are abstract memory objects that provide a source of pixels to
45  * scanout to a CRTC. Applications explicitly request the creation of frame
46  * buffers through the DRM_IOCTL_MODE_ADDFB(2) ioctls and receive an opaque
47  * handle that can be passed to the KMS CRTC control, plane configuration and
48  * page flip functions.
49  *
50  * Frame buffers rely on the underlying memory manager for allocating backing
51  * storage. When creating a frame buffer applications pass a memory handle
52  * (or a list of memory handles for multi-planar formats) through the
53  * &struct drm_mode_fb_cmd2 argument. For drivers using GEM as their userspace
54  * buffer management interface this would be a GEM handle.  Drivers are however
55  * free to use their own backing storage object handles, e.g. vmwgfx directly
56  * exposes special TTM handles to userspace and so expects TTM handles in the
57  * create ioctl and not GEM handles.
58  *
59  * Framebuffers are tracked with &struct drm_framebuffer. They are published
60  * using drm_framebuffer_init() - after calling that function userspace can use
61  * and access the framebuffer object. The helper function
62  * drm_helper_mode_fill_fb_struct() can be used to pre-fill the required
63  * metadata fields.
64  *
65  * The lifetime of a drm framebuffer is controlled with a reference count,
66  * drivers can grab additional references with drm_framebuffer_get() and drop
67  * them again with drm_framebuffer_put(). For driver-private framebuffers for
68  * which the last reference is never dropped (e.g. for the fbdev framebuffer
69  * when the struct &struct drm_framebuffer is embedded into the fbdev helper
70  * struct) drivers can manually clean up a framebuffer at module unload time
71  * with drm_framebuffer_unregister_private(). But doing this is not
72  * recommended, and it's better to have a normal free-standing &struct
73  * drm_framebuffer.
74  */
75
76 int drm_framebuffer_check_src_coords(uint32_t src_x, uint32_t src_y,
77                                      uint32_t src_w, uint32_t src_h,
78                                      const struct drm_framebuffer *fb)
79 {
80         unsigned int fb_width, fb_height;
81
82         fb_width = fb->width << 16;
83         fb_height = fb->height << 16;
84
85         /* Make sure source coordinates are inside the fb. */
86         if (src_w > fb_width ||
87             src_x > fb_width - src_w ||
88             src_h > fb_height ||
89             src_y > fb_height - src_h) {
90                 DRM_DEBUG_KMS("Invalid source coordinates "
91                               "%u.%06ux%u.%06u+%u.%06u+%u.%06u (fb %ux%u)\n",
92                               src_w >> 16, ((src_w & 0xffff) * 15625) >> 10,
93                               src_h >> 16, ((src_h & 0xffff) * 15625) >> 10,
94                               src_x >> 16, ((src_x & 0xffff) * 15625) >> 10,
95                               src_y >> 16, ((src_y & 0xffff) * 15625) >> 10,
96                               fb->width, fb->height);
97                 return -ENOSPC;
98         }
99
100         return 0;
101 }
102
103 /**
104  * drm_mode_addfb - add an FB to the graphics configuration
105  * @dev: drm device for the ioctl
106  * @or: pointer to request structure
107  * @file_priv: drm file
108  *
109  * Add a new FB to the specified CRTC, given a user request. This is the
110  * original addfb ioctl which only supported RGB formats.
111  *
112  * Called by the user via ioctl, or by an in-kernel client.
113  *
114  * Returns:
115  * Zero on success, negative errno on failure.
116  */
117 int drm_mode_addfb(struct drm_device *dev, struct drm_mode_fb_cmd *or,
118                    struct drm_file *file_priv)
119 {
120         struct drm_mode_fb_cmd2 r = {};
121         int ret;
122
123         if (!drm_core_check_feature(dev, DRIVER_MODESET))
124                 return -EOPNOTSUPP;
125
126         r.pixel_format = drm_driver_legacy_fb_format(dev, or->bpp, or->depth);
127         if (r.pixel_format == DRM_FORMAT_INVALID) {
128                 DRM_DEBUG("bad {bpp:%d, depth:%d}\n", or->bpp, or->depth);
129                 return -EINVAL;
130         }
131
132         /* convert to new format and call new ioctl */
133         r.fb_id = or->fb_id;
134         r.width = or->width;
135         r.height = or->height;
136         r.pitches[0] = or->pitch;
137         r.handles[0] = or->handle;
138
139         ret = drm_mode_addfb2(dev, &r, file_priv);
140         if (ret)
141                 return ret;
142
143         or->fb_id = r.fb_id;
144
145         return 0;
146 }
147
148 int drm_mode_addfb_ioctl(struct drm_device *dev,
149                          void *data, struct drm_file *file_priv)
150 {
151         return drm_mode_addfb(dev, data, file_priv);
152 }
153
154 static int fb_plane_width(int width,
155                           const struct drm_format_info *format, int plane)
156 {
157         if (plane == 0)
158                 return width;
159
160         return DIV_ROUND_UP(width, format->hsub);
161 }
162
163 static int fb_plane_height(int height,
164                            const struct drm_format_info *format, int plane)
165 {
166         if (plane == 0)
167                 return height;
168
169         return DIV_ROUND_UP(height, format->vsub);
170 }
171
172 static int framebuffer_check(struct drm_device *dev,
173                              const struct drm_mode_fb_cmd2 *r)
174 {
175         const struct drm_format_info *info;
176         int i;
177
178         /* check if the format is supported at all */
179         if (!__drm_format_info(r->pixel_format)) {
180                 DRM_DEBUG_KMS("bad framebuffer format %p4cc\n",
181                               &r->pixel_format);
182                 return -EINVAL;
183         }
184
185         if (r->width == 0) {
186                 DRM_DEBUG_KMS("bad framebuffer width %u\n", r->width);
187                 return -EINVAL;
188         }
189
190         if (r->height == 0) {
191                 DRM_DEBUG_KMS("bad framebuffer height %u\n", r->height);
192                 return -EINVAL;
193         }
194
195         /* now let the driver pick its own format info */
196         info = drm_get_format_info(dev, r);
197
198         for (i = 0; i < info->num_planes; i++) {
199                 unsigned int width = fb_plane_width(r->width, info, i);
200                 unsigned int height = fb_plane_height(r->height, info, i);
201                 unsigned int block_size = info->char_per_block[i];
202                 u64 min_pitch = drm_format_info_min_pitch(info, i, width);
203
204                 if (!block_size && (r->modifier[i] == DRM_FORMAT_MOD_LINEAR)) {
205                         DRM_DEBUG_KMS("Format requires non-linear modifier for plane %d\n", i);
206                         return -EINVAL;
207                 }
208
209                 if (!r->handles[i]) {
210                         DRM_DEBUG_KMS("no buffer object handle for plane %d\n", i);
211                         return -EINVAL;
212                 }
213
214                 if (min_pitch > UINT_MAX)
215                         return -ERANGE;
216
217                 if (r->modifier[i] == DRM_FORMAT_MOD_LINEAR) {
218                         if ((uint64_t)height * r->pitches[i] + r->offsets[i] >
219                                                                 UINT_MAX)
220                                 return -ERANGE;
221
222                         if (block_size && r->pitches[i] < min_pitch) {
223                                 DRM_DEBUG_KMS("bad pitch %u for plane %d\n",
224                                               r->pitches[i], i);
225                                 return -EINVAL;
226                         }
227                 }
228
229                 if (r->modifier[i] && !(r->flags & DRM_MODE_FB_MODIFIERS)) {
230                         DRM_DEBUG_KMS("bad fb modifier %llu for plane %d\n",
231                                       r->modifier[i], i);
232                         return -EINVAL;
233                 }
234
235                 if (r->flags & DRM_MODE_FB_MODIFIERS &&
236                     r->modifier[i] != r->modifier[0]) {
237                         DRM_DEBUG_KMS("bad fb modifier %llu for plane %d\n",
238                                       r->modifier[i], i);
239                         return -EINVAL;
240                 }
241
242                 /* modifier specific checks: */
243                 switch (r->modifier[i]) {
244                 case DRM_FORMAT_MOD_SAMSUNG_64_32_TILE:
245                         /* NOTE: the pitch restriction may be lifted later if it turns
246                          * out that no hw has this restriction:
247                          */
248                         if (r->pixel_format != DRM_FORMAT_NV12 ||
249                                         width % 128 || height % 32 ||
250                                         r->pitches[i] % 128) {
251                                 DRM_DEBUG_KMS("bad modifier data for plane %d\n", i);
252                                 return -EINVAL;
253                         }
254                         break;
255
256                 default:
257                         break;
258                 }
259         }
260
261         for (i = info->num_planes; i < 4; i++) {
262                 if (r->modifier[i]) {
263                         DRM_DEBUG_KMS("non-zero modifier for unused plane %d\n", i);
264                         return -EINVAL;
265                 }
266
267                 /* Pre-FB_MODIFIERS userspace didn't clear the structs properly. */
268                 if (!(r->flags & DRM_MODE_FB_MODIFIERS))
269                         continue;
270
271                 if (r->handles[i]) {
272                         DRM_DEBUG_KMS("buffer object handle for unused plane %d\n", i);
273                         return -EINVAL;
274                 }
275
276                 if (r->pitches[i]) {
277                         DRM_DEBUG_KMS("non-zero pitch for unused plane %d\n", i);
278                         return -EINVAL;
279                 }
280
281                 if (r->offsets[i]) {
282                         DRM_DEBUG_KMS("non-zero offset for unused plane %d\n", i);
283                         return -EINVAL;
284                 }
285         }
286
287         return 0;
288 }
289
290 struct drm_framebuffer *
291 drm_internal_framebuffer_create(struct drm_device *dev,
292                                 const struct drm_mode_fb_cmd2 *r,
293                                 struct drm_file *file_priv)
294 {
295         struct drm_mode_config *config = &dev->mode_config;
296         struct drm_framebuffer *fb;
297         int ret;
298
299         if (r->flags & ~(DRM_MODE_FB_INTERLACED | DRM_MODE_FB_MODIFIERS)) {
300                 DRM_DEBUG_KMS("bad framebuffer flags 0x%08x\n", r->flags);
301                 return ERR_PTR(-EINVAL);
302         }
303
304         if ((config->min_width > r->width) || (r->width > config->max_width)) {
305                 DRM_DEBUG_KMS("bad framebuffer width %d, should be >= %d && <= %d\n",
306                           r->width, config->min_width, config->max_width);
307                 return ERR_PTR(-EINVAL);
308         }
309         if ((config->min_height > r->height) || (r->height > config->max_height)) {
310                 DRM_DEBUG_KMS("bad framebuffer height %d, should be >= %d && <= %d\n",
311                           r->height, config->min_height, config->max_height);
312                 return ERR_PTR(-EINVAL);
313         }
314
315         if (r->flags & DRM_MODE_FB_MODIFIERS &&
316             !dev->mode_config.allow_fb_modifiers) {
317                 DRM_DEBUG_KMS("driver does not support fb modifiers\n");
318                 return ERR_PTR(-EINVAL);
319         }
320
321         ret = framebuffer_check(dev, r);
322         if (ret)
323                 return ERR_PTR(ret);
324
325         fb = dev->mode_config.funcs->fb_create(dev, file_priv, r);
326         if (IS_ERR(fb)) {
327                 DRM_DEBUG_KMS("could not create framebuffer\n");
328                 return fb;
329         }
330
331         return fb;
332 }
333 EXPORT_SYMBOL_FOR_TESTS_ONLY(drm_internal_framebuffer_create);
334
335 /**
336  * drm_mode_addfb2 - add an FB to the graphics configuration
337  * @dev: drm device for the ioctl
338  * @data: data pointer for the ioctl
339  * @file_priv: drm file for the ioctl call
340  *
341  * Add a new FB to the specified CRTC, given a user request with format. This is
342  * the 2nd version of the addfb ioctl, which supports multi-planar framebuffers
343  * and uses fourcc codes as pixel format specifiers.
344  *
345  * Called by the user via ioctl.
346  *
347  * Returns:
348  * Zero on success, negative errno on failure.
349  */
350 int drm_mode_addfb2(struct drm_device *dev,
351                     void *data, struct drm_file *file_priv)
352 {
353         struct drm_mode_fb_cmd2 *r = data;
354         struct drm_framebuffer *fb;
355
356         if (!drm_core_check_feature(dev, DRIVER_MODESET))
357                 return -EOPNOTSUPP;
358
359         fb = drm_internal_framebuffer_create(dev, r, file_priv);
360         if (IS_ERR(fb))
361                 return PTR_ERR(fb);
362
363         DRM_DEBUG_KMS("[FB:%d]\n", fb->base.id);
364         r->fb_id = fb->base.id;
365
366         /* Transfer ownership to the filp for reaping on close */
367         mutex_lock(&file_priv->fbs_lock);
368         list_add(&fb->filp_head, &file_priv->fbs);
369         mutex_unlock(&file_priv->fbs_lock);
370
371         return 0;
372 }
373
374 int drm_mode_addfb2_ioctl(struct drm_device *dev,
375                           void *data, struct drm_file *file_priv)
376 {
377 #ifdef __BIG_ENDIAN
378         if (!dev->mode_config.quirk_addfb_prefer_host_byte_order) {
379                 /*
380                  * Drivers must set the
381                  * quirk_addfb_prefer_host_byte_order quirk to make
382                  * the drm_mode_addfb() compat code work correctly on
383                  * bigendian machines.
384                  *
385                  * If they don't they interpret pixel_format values
386                  * incorrectly for bug compatibility, which in turn
387                  * implies the ADDFB2 ioctl does not work correctly
388                  * then.  So block it to make userspace fallback to
389                  * ADDFB.
390                  */
391                 DRM_DEBUG_KMS("addfb2 broken on bigendian");
392                 return -EOPNOTSUPP;
393         }
394 #endif
395         return drm_mode_addfb2(dev, data, file_priv);
396 }
397
398 struct drm_mode_rmfb_work {
399         struct work_struct work;
400         struct list_head fbs;
401 };
402
403 static void drm_mode_rmfb_work_fn(struct work_struct *w)
404 {
405         struct drm_mode_rmfb_work *arg = container_of(w, typeof(*arg), work);
406
407         while (!list_empty(&arg->fbs)) {
408                 struct drm_framebuffer *fb =
409                         list_first_entry(&arg->fbs, typeof(*fb), filp_head);
410
411                 drm_dbg_kms(fb->dev,
412                             "Removing [FB:%d] from all active usage due to RMFB ioctl\n",
413                             fb->base.id);
414                 list_del_init(&fb->filp_head);
415                 drm_framebuffer_remove(fb);
416         }
417 }
418
419 /**
420  * drm_mode_rmfb - remove an FB from the configuration
421  * @dev: drm device
422  * @fb_id: id of framebuffer to remove
423  * @file_priv: drm file
424  *
425  * Remove the specified FB.
426  *
427  * Called by the user via ioctl, or by an in-kernel client.
428  *
429  * Returns:
430  * Zero on success, negative errno on failure.
431  */
432 int drm_mode_rmfb(struct drm_device *dev, u32 fb_id,
433                   struct drm_file *file_priv)
434 {
435         struct drm_framebuffer *fb = NULL;
436         struct drm_framebuffer *fbl = NULL;
437         int found = 0;
438
439         if (!drm_core_check_feature(dev, DRIVER_MODESET))
440                 return -EOPNOTSUPP;
441
442         fb = drm_framebuffer_lookup(dev, file_priv, fb_id);
443         if (!fb)
444                 return -ENOENT;
445
446         mutex_lock(&file_priv->fbs_lock);
447         list_for_each_entry(fbl, &file_priv->fbs, filp_head)
448                 if (fb == fbl)
449                         found = 1;
450         if (!found) {
451                 mutex_unlock(&file_priv->fbs_lock);
452                 goto fail_unref;
453         }
454
455         list_del_init(&fb->filp_head);
456         mutex_unlock(&file_priv->fbs_lock);
457
458         /* drop the reference we picked up in framebuffer lookup */
459         drm_framebuffer_put(fb);
460
461         /*
462          * we now own the reference that was stored in the fbs list
463          *
464          * drm_framebuffer_remove may fail with -EINTR on pending signals,
465          * so run this in a separate stack as there's no way to correctly
466          * handle this after the fb is already removed from the lookup table.
467          */
468         if (drm_framebuffer_read_refcount(fb) > 1) {
469                 struct drm_mode_rmfb_work arg;
470
471                 INIT_WORK_ONSTACK(&arg.work, drm_mode_rmfb_work_fn);
472                 INIT_LIST_HEAD(&arg.fbs);
473                 list_add_tail(&fb->filp_head, &arg.fbs);
474
475                 schedule_work(&arg.work);
476                 flush_work(&arg.work);
477                 destroy_work_on_stack(&arg.work);
478         } else
479                 drm_framebuffer_put(fb);
480
481         return 0;
482
483 fail_unref:
484         drm_framebuffer_put(fb);
485         return -ENOENT;
486 }
487
488 int drm_mode_rmfb_ioctl(struct drm_device *dev,
489                         void *data, struct drm_file *file_priv)
490 {
491         uint32_t *fb_id = data;
492
493         return drm_mode_rmfb(dev, *fb_id, file_priv);
494 }
495
496 /**
497  * drm_mode_getfb - get FB info
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 given its ID and return info about it.
503  *
504  * Called by the user via ioctl.
505  *
506  * Returns:
507  * Zero on success, negative errno on failure.
508  */
509 int drm_mode_getfb(struct drm_device *dev,
510                    void *data, struct drm_file *file_priv)
511 {
512         struct drm_mode_fb_cmd *r = data;
513         struct drm_framebuffer *fb;
514         int ret;
515
516         if (!drm_core_check_feature(dev, DRIVER_MODESET))
517                 return -EOPNOTSUPP;
518
519         fb = drm_framebuffer_lookup(dev, file_priv, r->fb_id);
520         if (!fb)
521                 return -ENOENT;
522
523         /* Multi-planar framebuffers need getfb2. */
524         if (fb->format->num_planes > 1) {
525                 ret = -EINVAL;
526                 goto out;
527         }
528
529         if (!fb->funcs->create_handle) {
530                 ret = -ENODEV;
531                 goto out;
532         }
533
534         r->height = fb->height;
535         r->width = fb->width;
536         r->depth = fb->format->depth;
537         r->bpp = fb->format->cpp[0] * 8;
538         r->pitch = fb->pitches[0];
539
540         /* GET_FB() is an unprivileged ioctl so we must not return a
541          * buffer-handle to non-master processes! For
542          * backwards-compatibility reasons, we cannot make GET_FB() privileged,
543          * so just return an invalid handle for non-masters.
544          */
545         if (!drm_is_current_master(file_priv) && !capable(CAP_SYS_ADMIN)) {
546                 r->handle = 0;
547                 ret = 0;
548                 goto out;
549         }
550
551         ret = fb->funcs->create_handle(fb, file_priv, &r->handle);
552
553 out:
554         drm_framebuffer_put(fb);
555         return ret;
556 }
557
558 /**
559  * drm_mode_getfb2_ioctl - get extended FB info
560  * @dev: drm device for the ioctl
561  * @data: data pointer for the ioctl
562  * @file_priv: drm file for the ioctl call
563  *
564  * Lookup the FB given its ID and return info about it.
565  *
566  * Called by the user via ioctl.
567  *
568  * Returns:
569  * Zero on success, negative errno on failure.
570  */
571 int drm_mode_getfb2_ioctl(struct drm_device *dev,
572                           void *data, struct drm_file *file_priv)
573 {
574         struct drm_mode_fb_cmd2 *r = data;
575         struct drm_framebuffer *fb;
576         unsigned int i;
577         int ret;
578
579         if (!drm_core_check_feature(dev, DRIVER_MODESET))
580                 return -EINVAL;
581
582         fb = drm_framebuffer_lookup(dev, file_priv, r->fb_id);
583         if (!fb)
584                 return -ENOENT;
585
586         /* For multi-plane framebuffers, we require the driver to place the
587          * GEM objects directly in the drm_framebuffer. For single-plane
588          * framebuffers, we can fall back to create_handle.
589          */
590         if (!fb->obj[0] &&
591             (fb->format->num_planes > 1 || !fb->funcs->create_handle)) {
592                 ret = -ENODEV;
593                 goto out;
594         }
595
596         r->height = fb->height;
597         r->width = fb->width;
598         r->pixel_format = fb->format->format;
599
600         r->flags = 0;
601         if (dev->mode_config.allow_fb_modifiers)
602                 r->flags |= DRM_MODE_FB_MODIFIERS;
603
604         for (i = 0; i < ARRAY_SIZE(r->handles); i++) {
605                 r->handles[i] = 0;
606                 r->pitches[i] = 0;
607                 r->offsets[i] = 0;
608                 r->modifier[i] = 0;
609         }
610
611         for (i = 0; i < fb->format->num_planes; i++) {
612                 r->pitches[i] = fb->pitches[i];
613                 r->offsets[i] = fb->offsets[i];
614                 if (dev->mode_config.allow_fb_modifiers)
615                         r->modifier[i] = fb->modifier;
616         }
617
618         /* GET_FB2() is an unprivileged ioctl so we must not return a
619          * buffer-handle to non master/root processes! To match GET_FB()
620          * just return invalid handles (0) for non masters/root
621          * rather than making GET_FB2() privileged.
622          */
623         if (!drm_is_current_master(file_priv) && !capable(CAP_SYS_ADMIN)) {
624                 ret = 0;
625                 goto out;
626         }
627
628         for (i = 0; i < fb->format->num_planes; i++) {
629                 int j;
630
631                 /* If we reuse the same object for multiple planes, also
632                  * return the same handle.
633                  */
634                 for (j = 0; j < i; j++) {
635                         if (fb->obj[i] == fb->obj[j]) {
636                                 r->handles[i] = r->handles[j];
637                                 break;
638                         }
639                 }
640
641                 if (r->handles[i])
642                         continue;
643
644                 if (fb->obj[i]) {
645                         ret = drm_gem_handle_create(file_priv, fb->obj[i],
646                                                     &r->handles[i]);
647                 } else {
648                         WARN_ON(i > 0);
649                         ret = fb->funcs->create_handle(fb, file_priv,
650                                                        &r->handles[i]);
651                 }
652
653                 if (ret != 0)
654                         goto out;
655         }
656
657 out:
658         if (ret != 0) {
659                 /* Delete any previously-created handles on failure. */
660                 for (i = 0; i < ARRAY_SIZE(r->handles); i++) {
661                         int j;
662
663                         if (r->handles[i])
664                                 drm_gem_handle_delete(file_priv, r->handles[i]);
665
666                         /* Zero out any handles identical to the one we just
667                          * deleted.
668                          */
669                         for (j = i + 1; j < ARRAY_SIZE(r->handles); j++) {
670                                 if (r->handles[j] == r->handles[i])
671                                         r->handles[j] = 0;
672                         }
673                 }
674         }
675
676         drm_framebuffer_put(fb);
677         return ret;
678 }
679
680 /**
681  * drm_mode_dirtyfb_ioctl - flush frontbuffer rendering on an FB
682  * @dev: drm device for the ioctl
683  * @data: data pointer for the ioctl
684  * @file_priv: drm file for the ioctl call
685  *
686  * Lookup the FB and flush out the damaged area supplied by userspace as a clip
687  * rectangle list. Generic userspace which does frontbuffer rendering must call
688  * this ioctl to flush out the changes on manual-update display outputs, e.g.
689  * usb display-link, mipi manual update panels or edp panel self refresh modes.
690  *
691  * Modesetting drivers which always update the frontbuffer do not need to
692  * implement the corresponding &drm_framebuffer_funcs.dirty callback.
693  *
694  * Called by the user via ioctl.
695  *
696  * Returns:
697  * Zero on success, negative errno on failure.
698  */
699 int drm_mode_dirtyfb_ioctl(struct drm_device *dev,
700                            void *data, struct drm_file *file_priv)
701 {
702         struct drm_clip_rect __user *clips_ptr;
703         struct drm_clip_rect *clips = NULL;
704         struct drm_mode_fb_dirty_cmd *r = data;
705         struct drm_framebuffer *fb;
706         unsigned flags;
707         int num_clips;
708         int ret;
709
710         if (!drm_core_check_feature(dev, DRIVER_MODESET))
711                 return -EOPNOTSUPP;
712
713         fb = drm_framebuffer_lookup(dev, file_priv, r->fb_id);
714         if (!fb)
715                 return -ENOENT;
716
717         num_clips = r->num_clips;
718         clips_ptr = (struct drm_clip_rect __user *)(unsigned long)r->clips_ptr;
719
720         if (!num_clips != !clips_ptr) {
721                 ret = -EINVAL;
722                 goto out_err1;
723         }
724
725         flags = DRM_MODE_FB_DIRTY_FLAGS & r->flags;
726
727         /* If userspace annotates copy, clips must come in pairs */
728         if (flags & DRM_MODE_FB_DIRTY_ANNOTATE_COPY && (num_clips % 2)) {
729                 ret = -EINVAL;
730                 goto out_err1;
731         }
732
733         if (num_clips && clips_ptr) {
734                 if (num_clips < 0 || num_clips > DRM_MODE_FB_DIRTY_MAX_CLIPS) {
735                         ret = -EINVAL;
736                         goto out_err1;
737                 }
738                 clips = kcalloc(num_clips, sizeof(*clips), GFP_KERNEL);
739                 if (!clips) {
740                         ret = -ENOMEM;
741                         goto out_err1;
742                 }
743
744                 ret = copy_from_user(clips, clips_ptr,
745                                      num_clips * sizeof(*clips));
746                 if (ret) {
747                         ret = -EFAULT;
748                         goto out_err2;
749                 }
750         }
751
752         if (fb->funcs->dirty) {
753                 ret = fb->funcs->dirty(fb, file_priv, flags, r->color,
754                                        clips, num_clips);
755         } else {
756                 ret = -ENOSYS;
757         }
758
759 out_err2:
760         kfree(clips);
761 out_err1:
762         drm_framebuffer_put(fb);
763
764         return ret;
765 }
766
767 /**
768  * drm_fb_release - remove and free the FBs on this file
769  * @priv: drm file for the ioctl
770  *
771  * Destroy all the FBs associated with @filp.
772  *
773  * Called by the user via ioctl.
774  *
775  * Returns:
776  * Zero on success, negative errno on failure.
777  */
778 void drm_fb_release(struct drm_file *priv)
779 {
780         struct drm_framebuffer *fb, *tfb;
781         struct drm_mode_rmfb_work arg;
782
783         INIT_LIST_HEAD(&arg.fbs);
784
785         /*
786          * When the file gets released that means no one else can access the fb
787          * list any more, so no need to grab fpriv->fbs_lock. And we need to
788          * avoid upsetting lockdep since the universal cursor code adds a
789          * framebuffer while holding mutex locks.
790          *
791          * Note that a real deadlock between fpriv->fbs_lock and the modeset
792          * locks is impossible here since no one else but this function can get
793          * at it any more.
794          */
795         list_for_each_entry_safe(fb, tfb, &priv->fbs, filp_head) {
796                 if (drm_framebuffer_read_refcount(fb) > 1) {
797                         list_move_tail(&fb->filp_head, &arg.fbs);
798                 } else {
799                         list_del_init(&fb->filp_head);
800
801                         /* This drops the fpriv->fbs reference. */
802                         drm_framebuffer_put(fb);
803                 }
804         }
805
806         if (!list_empty(&arg.fbs)) {
807                 INIT_WORK_ONSTACK(&arg.work, drm_mode_rmfb_work_fn);
808
809                 schedule_work(&arg.work);
810                 flush_work(&arg.work);
811                 destroy_work_on_stack(&arg.work);
812         }
813 }
814
815 void drm_framebuffer_free(struct kref *kref)
816 {
817         struct drm_framebuffer *fb =
818                         container_of(kref, struct drm_framebuffer, base.refcount);
819         struct drm_device *dev = fb->dev;
820
821         /*
822          * The lookup idr holds a weak reference, which has not necessarily been
823          * removed at this point. Check for that.
824          */
825         drm_mode_object_unregister(dev, &fb->base);
826
827         fb->funcs->destroy(fb);
828 }
829
830 /**
831  * drm_framebuffer_init - initialize a framebuffer
832  * @dev: DRM device
833  * @fb: framebuffer to be initialized
834  * @funcs: ... with these functions
835  *
836  * Allocates an ID for the framebuffer's parent mode object, sets its mode
837  * functions & device file and adds it to the master fd list.
838  *
839  * IMPORTANT:
840  * This functions publishes the fb and makes it available for concurrent access
841  * by other users. Which means by this point the fb _must_ be fully set up -
842  * since all the fb attributes are invariant over its lifetime, no further
843  * locking but only correct reference counting is required.
844  *
845  * Returns:
846  * Zero on success, error code on failure.
847  */
848 int drm_framebuffer_init(struct drm_device *dev, struct drm_framebuffer *fb,
849                          const struct drm_framebuffer_funcs *funcs)
850 {
851         int ret;
852
853         if (WARN_ON_ONCE(fb->dev != dev || !fb->format))
854                 return -EINVAL;
855
856         INIT_LIST_HEAD(&fb->filp_head);
857
858         fb->funcs = funcs;
859         strcpy(fb->comm, current->comm);
860
861         ret = __drm_mode_object_add(dev, &fb->base, DRM_MODE_OBJECT_FB,
862                                     false, drm_framebuffer_free);
863         if (ret)
864                 goto out;
865
866         mutex_lock(&dev->mode_config.fb_lock);
867         dev->mode_config.num_fb++;
868         list_add(&fb->head, &dev->mode_config.fb_list);
869         mutex_unlock(&dev->mode_config.fb_lock);
870
871         drm_mode_object_register(dev, &fb->base);
872 out:
873         return ret;
874 }
875 EXPORT_SYMBOL(drm_framebuffer_init);
876
877 /**
878  * drm_framebuffer_lookup - look up a drm framebuffer and grab a reference
879  * @dev: drm device
880  * @file_priv: drm file to check for lease against.
881  * @id: id of the fb object
882  *
883  * If successful, this grabs an additional reference to the framebuffer -
884  * callers need to make sure to eventually unreference the returned framebuffer
885  * again, using drm_framebuffer_put().
886  */
887 struct drm_framebuffer *drm_framebuffer_lookup(struct drm_device *dev,
888                                                struct drm_file *file_priv,
889                                                uint32_t id)
890 {
891         struct drm_mode_object *obj;
892         struct drm_framebuffer *fb = NULL;
893
894         obj = __drm_mode_object_find(dev, file_priv, id, DRM_MODE_OBJECT_FB);
895         if (obj)
896                 fb = obj_to_fb(obj);
897         return fb;
898 }
899 EXPORT_SYMBOL(drm_framebuffer_lookup);
900
901 /**
902  * drm_framebuffer_unregister_private - unregister a private fb from the lookup idr
903  * @fb: fb to unregister
904  *
905  * Drivers need to call this when cleaning up driver-private framebuffers, e.g.
906  * those used for fbdev. Note that the caller must hold a reference of its own,
907  * i.e. the object may not be destroyed through this call (since it'll lead to a
908  * locking inversion).
909  *
910  * NOTE: This function is deprecated. For driver-private framebuffers it is not
911  * recommended to embed a framebuffer struct info fbdev struct, instead, a
912  * framebuffer pointer is preferred and drm_framebuffer_put() should be called
913  * when the framebuffer is to be cleaned up.
914  */
915 void drm_framebuffer_unregister_private(struct drm_framebuffer *fb)
916 {
917         struct drm_device *dev;
918
919         if (!fb)
920                 return;
921
922         dev = fb->dev;
923
924         /* Mark fb as reaped and drop idr ref. */
925         drm_mode_object_unregister(dev, &fb->base);
926 }
927 EXPORT_SYMBOL(drm_framebuffer_unregister_private);
928
929 /**
930  * drm_framebuffer_cleanup - remove a framebuffer object
931  * @fb: framebuffer to remove
932  *
933  * Cleanup framebuffer. This function is intended to be used from the drivers
934  * &drm_framebuffer_funcs.destroy callback. It can also be used to clean up
935  * driver private framebuffers embedded into a larger structure.
936  *
937  * Note that this function does not remove the fb from active usage - if it is
938  * still used anywhere, hilarity can ensue since userspace could call getfb on
939  * the id and get back -EINVAL. Obviously no concern at driver unload time.
940  *
941  * Also, the framebuffer will not be removed from the lookup idr - for
942  * user-created framebuffers this will happen in in the rmfb ioctl. For
943  * driver-private objects (e.g. for fbdev) drivers need to explicitly call
944  * drm_framebuffer_unregister_private.
945  */
946 void drm_framebuffer_cleanup(struct drm_framebuffer *fb)
947 {
948         struct drm_device *dev = fb->dev;
949
950         mutex_lock(&dev->mode_config.fb_lock);
951         list_del(&fb->head);
952         dev->mode_config.num_fb--;
953         mutex_unlock(&dev->mode_config.fb_lock);
954 }
955 EXPORT_SYMBOL(drm_framebuffer_cleanup);
956
957 static int atomic_remove_fb(struct drm_framebuffer *fb)
958 {
959         struct drm_modeset_acquire_ctx ctx;
960         struct drm_device *dev = fb->dev;
961         struct drm_atomic_state *state;
962         struct drm_plane *plane;
963         struct drm_connector *conn __maybe_unused;
964         struct drm_connector_state *conn_state;
965         int i, ret;
966         unsigned plane_mask;
967         bool disable_crtcs = false;
968
969 retry_disable:
970         drm_modeset_acquire_init(&ctx, 0);
971
972         state = drm_atomic_state_alloc(dev);
973         if (!state) {
974                 ret = -ENOMEM;
975                 goto out;
976         }
977         state->acquire_ctx = &ctx;
978
979 retry:
980         plane_mask = 0;
981         ret = drm_modeset_lock_all_ctx(dev, &ctx);
982         if (ret)
983                 goto unlock;
984
985         drm_for_each_plane(plane, dev) {
986                 struct drm_plane_state *plane_state;
987
988                 if (plane->state->fb != fb)
989                         continue;
990
991                 drm_dbg_kms(dev,
992                             "Disabling [PLANE:%d:%s] because [FB:%d] is removed\n",
993                             plane->base.id, plane->name, fb->base.id);
994
995                 plane_state = drm_atomic_get_plane_state(state, plane);
996                 if (IS_ERR(plane_state)) {
997                         ret = PTR_ERR(plane_state);
998                         goto unlock;
999                 }
1000
1001                 if (disable_crtcs && plane_state->crtc->primary == plane) {
1002                         struct drm_crtc_state *crtc_state;
1003
1004                         drm_dbg_kms(dev,
1005                                     "Disabling [CRTC:%d:%s] because [FB:%d] is removed\n",
1006                                     plane_state->crtc->base.id,
1007                                     plane_state->crtc->name, fb->base.id);
1008
1009                         crtc_state = drm_atomic_get_existing_crtc_state(state, plane_state->crtc);
1010
1011                         ret = drm_atomic_add_affected_connectors(state, plane_state->crtc);
1012                         if (ret)
1013                                 goto unlock;
1014
1015                         crtc_state->active = false;
1016                         ret = drm_atomic_set_mode_for_crtc(crtc_state, NULL);
1017                         if (ret)
1018                                 goto unlock;
1019                 }
1020
1021                 drm_atomic_set_fb_for_plane(plane_state, NULL);
1022                 ret = drm_atomic_set_crtc_for_plane(plane_state, NULL);
1023                 if (ret)
1024                         goto unlock;
1025
1026                 plane_mask |= drm_plane_mask(plane);
1027         }
1028
1029         /* This list is only filled when disable_crtcs is set. */
1030         for_each_new_connector_in_state(state, conn, conn_state, i) {
1031                 ret = drm_atomic_set_crtc_for_connector(conn_state, NULL);
1032
1033                 if (ret)
1034                         goto unlock;
1035         }
1036
1037         if (plane_mask)
1038                 ret = drm_atomic_commit(state);
1039
1040 unlock:
1041         if (ret == -EDEADLK) {
1042                 drm_atomic_state_clear(state);
1043                 drm_modeset_backoff(&ctx);
1044                 goto retry;
1045         }
1046
1047         drm_atomic_state_put(state);
1048
1049 out:
1050         drm_modeset_drop_locks(&ctx);
1051         drm_modeset_acquire_fini(&ctx);
1052
1053         if (ret == -EINVAL && !disable_crtcs) {
1054                 disable_crtcs = true;
1055                 goto retry_disable;
1056         }
1057
1058         return ret;
1059 }
1060
1061 static void legacy_remove_fb(struct drm_framebuffer *fb)
1062 {
1063         struct drm_device *dev = fb->dev;
1064         struct drm_crtc *crtc;
1065         struct drm_plane *plane;
1066
1067         drm_modeset_lock_all(dev);
1068         /* remove from any CRTC */
1069         drm_for_each_crtc(crtc, dev) {
1070                 if (crtc->primary->fb == fb) {
1071                         drm_dbg_kms(dev,
1072                                     "Disabling [CRTC:%d:%s] because [FB:%d] is removed\n",
1073                                     crtc->base.id, crtc->name, fb->base.id);
1074
1075                         /* should turn off the crtc */
1076                         if (drm_crtc_force_disable(crtc))
1077                                 DRM_ERROR("failed to reset crtc %p when fb was deleted\n", crtc);
1078                 }
1079         }
1080
1081         drm_for_each_plane(plane, dev) {
1082                 if (plane->fb == fb) {
1083                         drm_dbg_kms(dev,
1084                                     "Disabling [PLANE:%d:%s] because [FB:%d] is removed\n",
1085                                     plane->base.id, plane->name, fb->base.id);
1086                         drm_plane_force_disable(plane);
1087                 }
1088         }
1089         drm_modeset_unlock_all(dev);
1090 }
1091
1092 /**
1093  * drm_framebuffer_remove - remove and unreference a framebuffer object
1094  * @fb: framebuffer to remove
1095  *
1096  * Scans all the CRTCs and planes in @dev's mode_config.  If they're
1097  * using @fb, removes it, setting it to NULL. Then drops the reference to the
1098  * passed-in framebuffer. Might take the modeset locks.
1099  *
1100  * Note that this function optimizes the cleanup away if the caller holds the
1101  * last reference to the framebuffer. It is also guaranteed to not take the
1102  * modeset locks in this case.
1103  */
1104 void drm_framebuffer_remove(struct drm_framebuffer *fb)
1105 {
1106         struct drm_device *dev;
1107
1108         if (!fb)
1109                 return;
1110
1111         dev = fb->dev;
1112
1113         WARN_ON(!list_empty(&fb->filp_head));
1114
1115         /*
1116          * drm ABI mandates that we remove any deleted framebuffers from active
1117          * usage. But since most sane clients only remove framebuffers they no
1118          * longer need, try to optimize this away.
1119          *
1120          * Since we're holding a reference ourselves, observing a refcount of 1
1121          * means that we're the last holder and can skip it. Also, the refcount
1122          * can never increase from 1 again, so we don't need any barriers or
1123          * locks.
1124          *
1125          * Note that userspace could try to race with use and instate a new
1126          * usage _after_ we've cleared all current ones. End result will be an
1127          * in-use fb with fb-id == 0. Userspace is allowed to shoot its own foot
1128          * in this manner.
1129          */
1130         if (drm_framebuffer_read_refcount(fb) > 1) {
1131                 if (drm_drv_uses_atomic_modeset(dev)) {
1132                         int ret = atomic_remove_fb(fb);
1133
1134                         WARN(ret, "atomic remove_fb failed with %i\n", ret);
1135                 } else
1136                         legacy_remove_fb(fb);
1137         }
1138
1139         drm_framebuffer_put(fb);
1140 }
1141 EXPORT_SYMBOL(drm_framebuffer_remove);
1142
1143 /**
1144  * drm_framebuffer_plane_width - width of the plane given the first plane
1145  * @width: width of the first plane
1146  * @fb: the framebuffer
1147  * @plane: plane index
1148  *
1149  * Returns:
1150  * The width of @plane, given that the width of the first plane is @width.
1151  */
1152 int drm_framebuffer_plane_width(int width,
1153                                 const struct drm_framebuffer *fb, int plane)
1154 {
1155         if (plane >= fb->format->num_planes)
1156                 return 0;
1157
1158         return fb_plane_width(width, fb->format, plane);
1159 }
1160 EXPORT_SYMBOL(drm_framebuffer_plane_width);
1161
1162 /**
1163  * drm_framebuffer_plane_height - height of the plane given the first plane
1164  * @height: height of the first plane
1165  * @fb: the framebuffer
1166  * @plane: plane index
1167  *
1168  * Returns:
1169  * The height of @plane, given that the height of the first plane is @height.
1170  */
1171 int drm_framebuffer_plane_height(int height,
1172                                  const struct drm_framebuffer *fb, int plane)
1173 {
1174         if (plane >= fb->format->num_planes)
1175                 return 0;
1176
1177         return fb_plane_height(height, fb->format, plane);
1178 }
1179 EXPORT_SYMBOL(drm_framebuffer_plane_height);
1180
1181 void drm_framebuffer_print_info(struct drm_printer *p, unsigned int indent,
1182                                 const struct drm_framebuffer *fb)
1183 {
1184         unsigned int i;
1185
1186         drm_printf_indent(p, indent, "allocated by = %s\n", fb->comm);
1187         drm_printf_indent(p, indent, "refcount=%u\n",
1188                           drm_framebuffer_read_refcount(fb));
1189         drm_printf_indent(p, indent, "format=%p4cc\n", &fb->format->format);
1190         drm_printf_indent(p, indent, "modifier=0x%llx\n", fb->modifier);
1191         drm_printf_indent(p, indent, "size=%ux%u\n", fb->width, fb->height);
1192         drm_printf_indent(p, indent, "layers:\n");
1193
1194         for (i = 0; i < fb->format->num_planes; i++) {
1195                 drm_printf_indent(p, indent + 1, "size[%u]=%dx%d\n", i,
1196                                   drm_framebuffer_plane_width(fb->width, fb, i),
1197                                   drm_framebuffer_plane_height(fb->height, fb, i));
1198                 drm_printf_indent(p, indent + 1, "pitch[%u]=%u\n", i, fb->pitches[i]);
1199                 drm_printf_indent(p, indent + 1, "offset[%u]=%u\n", i, fb->offsets[i]);
1200                 drm_printf_indent(p, indent + 1, "obj[%u]:%s\n", i,
1201                                   fb->obj[i] ? "" : "(null)");
1202                 if (fb->obj[i])
1203                         drm_gem_print_info(p, indent + 2, fb->obj[i]);
1204         }
1205 }
1206
1207 #ifdef CONFIG_DEBUG_FS
1208 static int drm_framebuffer_info(struct seq_file *m, void *data)
1209 {
1210         struct drm_info_node *node = m->private;
1211         struct drm_device *dev = node->minor->dev;
1212         struct drm_printer p = drm_seq_file_printer(m);
1213         struct drm_framebuffer *fb;
1214
1215         mutex_lock(&dev->mode_config.fb_lock);
1216         drm_for_each_fb(fb, dev) {
1217                 drm_printf(&p, "framebuffer[%u]:\n", fb->base.id);
1218                 drm_framebuffer_print_info(&p, 1, fb);
1219         }
1220         mutex_unlock(&dev->mode_config.fb_lock);
1221
1222         return 0;
1223 }
1224
1225 static const struct drm_info_list drm_framebuffer_debugfs_list[] = {
1226         { "framebuffer", drm_framebuffer_info, 0 },
1227 };
1228
1229 void drm_framebuffer_debugfs_init(struct drm_minor *minor)
1230 {
1231         drm_debugfs_create_files(drm_framebuffer_debugfs_list,
1232                                  ARRAY_SIZE(drm_framebuffer_debugfs_list),
1233                                  minor->debugfs_root, minor);
1234 }
1235 #endif