xref: /dragonfly/sys/dev/drm/drm_framebuffer.c (revision 3f2dd94a)
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 
drm_framebuffer_check_src_coords(uint32_t src_x,uint32_t src_y,uint32_t src_w,uint32_t src_h,const struct drm_framebuffer * fb)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  */
drm_mode_addfb(struct drm_device * dev,void * data,struct drm_file * file_priv)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 
fb_plane_width(int width,const struct drm_format_info * format,int plane)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 
fb_plane_height(int height,const struct drm_format_info * format,int plane)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 
framebuffer_check(struct drm_device * dev,const struct drm_mode_fb_cmd2 * r)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 *
drm_internal_framebuffer_create(struct drm_device * dev,const struct drm_mode_fb_cmd2 * r,struct drm_file * file_priv)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  */
drm_mode_addfb2(struct drm_device * dev,void * data,struct drm_file * file_priv)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 
drm_mode_rmfb_work_fn(struct work_struct * w)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  */
drm_mode_rmfb(struct drm_device * dev,void * data,struct drm_file * file_priv)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, file_priv, *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  */
drm_mode_getfb(struct drm_device * dev,void * data,struct drm_file * file_priv)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, file_priv, 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  */
drm_mode_dirtyfb_ioctl(struct drm_device * dev,void * data,struct drm_file * file_priv)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, file_priv, 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  */
drm_fb_release(struct drm_file * priv)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 
drm_framebuffer_free(struct kref * kref)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  */
drm_framebuffer_init(struct drm_device * dev,struct drm_framebuffer * fb,const struct drm_framebuffer_funcs * funcs)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  * @file_priv: drm file to check for lease against.
696  * @id: id of the fb object
697  *
698  * If successful, this grabs an additional reference to the framebuffer -
699  * callers need to make sure to eventually unreference the returned framebuffer
700  * again, using drm_framebuffer_put().
701  */
drm_framebuffer_lookup(struct drm_device * dev,struct drm_file * file_priv,uint32_t id)702 struct drm_framebuffer *drm_framebuffer_lookup(struct drm_device *dev,
703 					       struct drm_file *file_priv,
704 					       uint32_t id)
705 {
706 	struct drm_mode_object *obj;
707 	struct drm_framebuffer *fb = NULL;
708 
709 	obj = __drm_mode_object_find(dev, file_priv, id, DRM_MODE_OBJECT_FB);
710 	if (obj)
711 		fb = obj_to_fb(obj);
712 	return fb;
713 }
714 EXPORT_SYMBOL(drm_framebuffer_lookup);
715 
716 /**
717  * drm_framebuffer_unregister_private - unregister a private fb from the lookup idr
718  * @fb: fb to unregister
719  *
720  * Drivers need to call this when cleaning up driver-private framebuffers, e.g.
721  * those used for fbdev. Note that the caller must hold a reference of it's own,
722  * i.e. the object may not be destroyed through this call (since it'll lead to a
723  * locking inversion).
724  *
725  * NOTE: This function is deprecated. For driver-private framebuffers it is not
726  * recommended to embed a framebuffer struct info fbdev struct, instead, a
727  * framebuffer pointer is preferred and drm_framebuffer_put() should be called
728  * when the framebuffer is to be cleaned up.
729  */
drm_framebuffer_unregister_private(struct drm_framebuffer * fb)730 void drm_framebuffer_unregister_private(struct drm_framebuffer *fb)
731 {
732 	struct drm_device *dev;
733 
734 	if (!fb)
735 		return;
736 
737 	dev = fb->dev;
738 
739 	/* Mark fb as reaped and drop idr ref. */
740 	drm_mode_object_unregister(dev, &fb->base);
741 }
742 EXPORT_SYMBOL(drm_framebuffer_unregister_private);
743 
744 /**
745  * drm_framebuffer_cleanup - remove a framebuffer object
746  * @fb: framebuffer to remove
747  *
748  * Cleanup framebuffer. This function is intended to be used from the drivers
749  * &drm_framebuffer_funcs.destroy callback. It can also be used to clean up
750  * driver private framebuffers embedded into a larger structure.
751  *
752  * Note that this function does not remove the fb from active usage - if it is
753  * still used anywhere, hilarity can ensue since userspace could call getfb on
754  * the id and get back -EINVAL. Obviously no concern at driver unload time.
755  *
756  * Also, the framebuffer will not be removed from the lookup idr - for
757  * user-created framebuffers this will happen in in the rmfb ioctl. For
758  * driver-private objects (e.g. for fbdev) drivers need to explicitly call
759  * drm_framebuffer_unregister_private.
760  */
drm_framebuffer_cleanup(struct drm_framebuffer * fb)761 void drm_framebuffer_cleanup(struct drm_framebuffer *fb)
762 {
763 	struct drm_device *dev = fb->dev;
764 
765 	mutex_lock(&dev->mode_config.fb_lock);
766 	list_del(&fb->head);
767 	dev->mode_config.num_fb--;
768 	mutex_unlock(&dev->mode_config.fb_lock);
769 }
770 EXPORT_SYMBOL(drm_framebuffer_cleanup);
771 
atomic_remove_fb(struct drm_framebuffer * fb)772 static int atomic_remove_fb(struct drm_framebuffer *fb)
773 {
774 	struct drm_modeset_acquire_ctx ctx;
775 	struct drm_device *dev = fb->dev;
776 	struct drm_atomic_state *state;
777 	struct drm_plane *plane;
778 	struct drm_connector *conn;
779 	struct drm_connector_state *conn_state;
780 	int i, ret = 0;
781 	unsigned plane_mask;
782 
783 	state = drm_atomic_state_alloc(dev);
784 	if (!state)
785 		return -ENOMEM;
786 
787 	drm_modeset_acquire_init(&ctx, 0);
788 	state->acquire_ctx = &ctx;
789 
790 retry:
791 	plane_mask = 0;
792 	ret = drm_modeset_lock_all_ctx(dev, &ctx);
793 	if (ret)
794 		goto unlock;
795 
796 	drm_for_each_plane(plane, dev) {
797 		struct drm_plane_state *plane_state;
798 
799 		if (plane->state->fb != fb)
800 			continue;
801 
802 		plane_state = drm_atomic_get_plane_state(state, plane);
803 		if (IS_ERR(plane_state)) {
804 			ret = PTR_ERR(plane_state);
805 			goto unlock;
806 		}
807 
808 		if (plane_state->crtc->primary == plane) {
809 			struct drm_crtc_state *crtc_state;
810 
811 			crtc_state = drm_atomic_get_existing_crtc_state(state, plane_state->crtc);
812 
813 			ret = drm_atomic_add_affected_connectors(state, plane_state->crtc);
814 			if (ret)
815 				goto unlock;
816 
817 			crtc_state->active = false;
818 			ret = drm_atomic_set_mode_for_crtc(crtc_state, NULL);
819 			if (ret)
820 				goto unlock;
821 		}
822 
823 		drm_atomic_set_fb_for_plane(plane_state, NULL);
824 		ret = drm_atomic_set_crtc_for_plane(plane_state, NULL);
825 		if (ret)
826 			goto unlock;
827 
828 		plane_mask |= BIT(drm_plane_index(plane));
829 
830 		plane->old_fb = plane->fb;
831 	}
832 
833 	for_each_new_connector_in_state(state, conn, conn_state, i) {
834 		ret = drm_atomic_set_crtc_for_connector(conn_state, NULL);
835 
836 		if (ret)
837 			goto unlock;
838 	}
839 
840 	if (plane_mask)
841 		ret = drm_atomic_commit(state);
842 
843 unlock:
844 	if (plane_mask)
845 		drm_atomic_clean_old_fb(dev, plane_mask, ret);
846 
847 	if (ret == -EDEADLK) {
848 		drm_atomic_state_clear(state);
849 		drm_modeset_backoff(&ctx);
850 		goto retry;
851 	}
852 
853 	drm_atomic_state_put(state);
854 
855 	drm_modeset_drop_locks(&ctx);
856 	drm_modeset_acquire_fini(&ctx);
857 
858 	return ret;
859 }
860 
legacy_remove_fb(struct drm_framebuffer * fb)861 static void legacy_remove_fb(struct drm_framebuffer *fb)
862 {
863 	struct drm_device *dev = fb->dev;
864 	struct drm_crtc *crtc;
865 	struct drm_plane *plane;
866 
867 	drm_modeset_lock_all(dev);
868 	/* remove from any CRTC */
869 	drm_for_each_crtc(crtc, dev) {
870 		if (crtc->primary->fb == fb) {
871 			/* should turn off the crtc */
872 			if (drm_crtc_force_disable(crtc))
873 				DRM_ERROR("failed to reset crtc %p when fb was deleted\n", crtc);
874 		}
875 	}
876 
877 	drm_for_each_plane(plane, dev) {
878 		if (plane->fb == fb)
879 			drm_plane_force_disable(plane);
880 	}
881 	drm_modeset_unlock_all(dev);
882 }
883 
884 /**
885  * drm_framebuffer_remove - remove and unreference a framebuffer object
886  * @fb: framebuffer to remove
887  *
888  * Scans all the CRTCs and planes in @dev's mode_config.  If they're
889  * using @fb, removes it, setting it to NULL. Then drops the reference to the
890  * passed-in framebuffer. Might take the modeset locks.
891  *
892  * Note that this function optimizes the cleanup away if the caller holds the
893  * last reference to the framebuffer. It is also guaranteed to not take the
894  * modeset locks in this case.
895  */
drm_framebuffer_remove(struct drm_framebuffer * fb)896 void drm_framebuffer_remove(struct drm_framebuffer *fb)
897 {
898 	struct drm_device *dev;
899 
900 	if (!fb)
901 		return;
902 
903 	dev = fb->dev;
904 
905 	WARN_ON(!list_empty(&fb->filp_head));
906 
907 	/*
908 	 * drm ABI mandates that we remove any deleted framebuffers from active
909 	 * useage. But since most sane clients only remove framebuffers they no
910 	 * longer need, try to optimize this away.
911 	 *
912 	 * Since we're holding a reference ourselves, observing a refcount of 1
913 	 * means that we're the last holder and can skip it. Also, the refcount
914 	 * can never increase from 1 again, so we don't need any barriers or
915 	 * locks.
916 	 *
917 	 * Note that userspace could try to race with use and instate a new
918 	 * usage _after_ we've cleared all current ones. End result will be an
919 	 * in-use fb with fb-id == 0. Userspace is allowed to shoot its own foot
920 	 * in this manner.
921 	 */
922 	if (drm_framebuffer_read_refcount(fb) > 1) {
923 		if (drm_drv_uses_atomic_modeset(dev)) {
924 			int ret = atomic_remove_fb(fb);
925 			WARN(ret, "atomic remove_fb failed with %i\n", ret);
926 		} else
927 			legacy_remove_fb(fb);
928 	}
929 
930 	drm_framebuffer_put(fb);
931 }
932 EXPORT_SYMBOL(drm_framebuffer_remove);
933 
934 /**
935  * drm_framebuffer_plane_width - width of the plane given the first plane
936  * @width: width of the first plane
937  * @fb: the framebuffer
938  * @plane: plane index
939  *
940  * Returns:
941  * The width of @plane, given that the width of the first plane is @width.
942  */
drm_framebuffer_plane_width(int width,const struct drm_framebuffer * fb,int plane)943 int drm_framebuffer_plane_width(int width,
944 				const struct drm_framebuffer *fb, int plane)
945 {
946 	if (plane >= fb->format->num_planes)
947 		return 0;
948 
949 	return fb_plane_width(width, fb->format, plane);
950 }
951 EXPORT_SYMBOL(drm_framebuffer_plane_width);
952 
953 /**
954  * drm_framebuffer_plane_height - height of the plane given the first plane
955  * @height: height of the first plane
956  * @fb: the framebuffer
957  * @plane: plane index
958  *
959  * Returns:
960  * The height of @plane, given that the height of the first plane is @height.
961  */
drm_framebuffer_plane_height(int height,const struct drm_framebuffer * fb,int plane)962 int drm_framebuffer_plane_height(int height,
963 				 const struct drm_framebuffer *fb, int plane)
964 {
965 	if (plane >= fb->format->num_planes)
966 		return 0;
967 
968 	return fb_plane_height(height, fb->format, plane);
969 }
970 EXPORT_SYMBOL(drm_framebuffer_plane_height);
971