xref: /linux/drivers/gpu/drm/vmwgfx/vmwgfx_resource.c (revision c4b134969ce350cdd4e726b5102b85b8a2d6fad5)
1 // SPDX-License-Identifier: GPL-2.0 OR MIT
2 /**************************************************************************
3  *
4  * Copyright (c) 2009-2024 Broadcom. All Rights Reserved. The term
5  * “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a
8  * copy of this software and associated documentation files (the
9  * "Software"), to deal in the Software without restriction, including
10  * without limitation the rights to use, copy, modify, merge, publish,
11  * distribute, sub license, and/or sell copies of the Software, and to
12  * permit persons to whom the Software is furnished to do so, subject to
13  * the following conditions:
14  *
15  * The above copyright notice and this permission notice (including the
16  * next paragraph) shall be included in all copies or substantial portions
17  * of the Software.
18  *
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21  * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
22  * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
23  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
24  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
25  * USE OR OTHER DEALINGS IN THE SOFTWARE.
26  *
27  **************************************************************************/
28 
29 #include <drm/ttm/ttm_placement.h>
30 
31 #include "vmwgfx_binding.h"
32 #include "vmwgfx_bo.h"
33 #include "vmwgfx_drv.h"
34 #include "vmwgfx_resource_priv.h"
35 
36 #define VMW_RES_EVICT_ERR_COUNT 10
37 
38 /**
39  * vmw_resource_mob_attach - Mark a resource as attached to its backing mob
40  * @res: The resource
41  */
42 void vmw_resource_mob_attach(struct vmw_resource *res)
43 {
44 	struct vmw_bo *gbo = res->guest_memory_bo;
45 	struct rb_node **new = &gbo->res_tree.rb_node, *parent = NULL;
46 
47 	dma_resv_assert_held(gbo->tbo.base.resv);
48 	res->used_prio = (res->res_dirty) ? res->func->dirty_prio :
49 		res->func->prio;
50 
51 	while (*new) {
52 		struct vmw_resource *this =
53 			container_of(*new, struct vmw_resource, mob_node);
54 
55 		parent = *new;
56 		new = (res->guest_memory_offset < this->guest_memory_offset) ?
57 			&((*new)->rb_left) : &((*new)->rb_right);
58 	}
59 
60 	rb_link_node(&res->mob_node, parent, new);
61 	rb_insert_color(&res->mob_node, &gbo->res_tree);
62 	vmw_bo_del_detached_resource(gbo, res);
63 
64 	vmw_bo_prio_add(gbo, res->used_prio);
65 }
66 
67 /**
68  * vmw_resource_mob_detach - Mark a resource as detached from its backing mob
69  * @res: The resource
70  */
71 void vmw_resource_mob_detach(struct vmw_resource *res)
72 {
73 	struct vmw_bo *gbo = res->guest_memory_bo;
74 
75 	dma_resv_assert_held(gbo->tbo.base.resv);
76 	if (vmw_resource_mob_attached(res)) {
77 		rb_erase(&res->mob_node, &gbo->res_tree);
78 		RB_CLEAR_NODE(&res->mob_node);
79 		vmw_bo_prio_del(gbo, res->used_prio);
80 	}
81 }
82 
83 struct vmw_resource *vmw_resource_reference(struct vmw_resource *res)
84 {
85 	kref_get(&res->kref);
86 	return res;
87 }
88 
89 struct vmw_resource *
90 vmw_resource_reference_unless_doomed(struct vmw_resource *res)
91 {
92 	return kref_get_unless_zero(&res->kref) ? res : NULL;
93 }
94 
95 /**
96  * vmw_resource_release_id - release a resource id to the id manager.
97  *
98  * @res: Pointer to the resource.
99  *
100  * Release the resource id to the resource id manager and set it to -1
101  */
102 void vmw_resource_release_id(struct vmw_resource *res)
103 {
104 	struct vmw_private *dev_priv = res->dev_priv;
105 	struct idr *idr = &dev_priv->res_idr[res->func->res_type];
106 
107 	spin_lock(&dev_priv->resource_lock);
108 	if (res->id != -1)
109 		idr_remove(idr, res->id);
110 	res->id = -1;
111 	spin_unlock(&dev_priv->resource_lock);
112 }
113 
114 static void vmw_resource_release(struct kref *kref)
115 {
116 	struct vmw_resource *res =
117 	    container_of(kref, struct vmw_resource, kref);
118 	struct vmw_private *dev_priv = res->dev_priv;
119 	int id;
120 	int ret;
121 	struct idr *idr = &dev_priv->res_idr[res->func->res_type];
122 
123 	spin_lock(&dev_priv->resource_lock);
124 	list_del_init(&res->lru_head);
125 	spin_unlock(&dev_priv->resource_lock);
126 	if (res->guest_memory_bo) {
127 		struct ttm_buffer_object *bo = &res->guest_memory_bo->tbo;
128 
129 		ret = ttm_bo_reserve(bo, false, false, NULL);
130 		BUG_ON(ret);
131 		if (vmw_resource_mob_attached(res) &&
132 		    res->func->unbind != NULL) {
133 			struct ttm_validate_buffer val_buf;
134 
135 			val_buf.bo = bo;
136 			val_buf.num_shared = 0;
137 			res->func->unbind(res, false, &val_buf);
138 		}
139 		res->guest_memory_dirty = false;
140 		vmw_resource_mob_detach(res);
141 		vmw_bo_del_detached_resource(res->guest_memory_bo, res);
142 		if (res->dirty)
143 			res->func->dirty_free(res);
144 		if (res->coherent)
145 			vmw_bo_dirty_release(res->guest_memory_bo);
146 		ttm_bo_unreserve(bo);
147 		vmw_user_bo_unref(&res->guest_memory_bo);
148 	}
149 
150 	if (likely(res->hw_destroy != NULL)) {
151 		mutex_lock(&dev_priv->binding_mutex);
152 		vmw_binding_res_list_kill(&res->binding_head);
153 		mutex_unlock(&dev_priv->binding_mutex);
154 		res->hw_destroy(res);
155 	}
156 
157 	id = res->id;
158 	if (res->res_free != NULL)
159 		res->res_free(res);
160 	else
161 		kfree(res);
162 
163 	spin_lock(&dev_priv->resource_lock);
164 	if (id != -1)
165 		idr_remove(idr, id);
166 	spin_unlock(&dev_priv->resource_lock);
167 }
168 
169 void vmw_resource_unreference(struct vmw_resource **p_res)
170 {
171 	struct vmw_resource *res = *p_res;
172 
173 	*p_res = NULL;
174 	kref_put(&res->kref, vmw_resource_release);
175 }
176 
177 
178 /**
179  * vmw_resource_alloc_id - release a resource id to the id manager.
180  *
181  * @res: Pointer to the resource.
182  *
183  * Allocate the lowest free resource from the resource manager, and set
184  * @res->id to that id. Returns 0 on success and -ENOMEM on failure.
185  */
186 int vmw_resource_alloc_id(struct vmw_resource *res)
187 {
188 	struct vmw_private *dev_priv = res->dev_priv;
189 	int ret;
190 	struct idr *idr = &dev_priv->res_idr[res->func->res_type];
191 
192 	BUG_ON(res->id != -1);
193 
194 	idr_preload(GFP_KERNEL);
195 	spin_lock(&dev_priv->resource_lock);
196 
197 	ret = idr_alloc(idr, res, 1, 0, GFP_NOWAIT);
198 	if (ret >= 0)
199 		res->id = ret;
200 
201 	spin_unlock(&dev_priv->resource_lock);
202 	idr_preload_end();
203 	return ret < 0 ? ret : 0;
204 }
205 
206 /**
207  * vmw_resource_init - initialize a struct vmw_resource
208  *
209  * @dev_priv:       Pointer to a device private struct.
210  * @res:            The struct vmw_resource to initialize.
211  * @delay_id:       Boolean whether to defer device id allocation until
212  *                  the first validation.
213  * @res_free:       Resource destructor.
214  * @func:           Resource function table.
215  */
216 int vmw_resource_init(struct vmw_private *dev_priv, struct vmw_resource *res,
217 		      bool delay_id,
218 		      void (*res_free) (struct vmw_resource *res),
219 		      const struct vmw_res_func *func)
220 {
221 	kref_init(&res->kref);
222 	res->hw_destroy = NULL;
223 	res->res_free = res_free;
224 	res->dev_priv = dev_priv;
225 	res->func = func;
226 	RB_CLEAR_NODE(&res->mob_node);
227 	INIT_LIST_HEAD(&res->lru_head);
228 	INIT_LIST_HEAD(&res->binding_head);
229 	res->id = -1;
230 	res->guest_memory_bo = NULL;
231 	res->guest_memory_offset = 0;
232 	res->guest_memory_dirty = false;
233 	res->res_dirty = false;
234 	res->coherent = false;
235 	res->used_prio = 3;
236 	res->dirty = NULL;
237 	if (delay_id)
238 		return 0;
239 	else
240 		return vmw_resource_alloc_id(res);
241 }
242 
243 
244 /**
245  * vmw_user_resource_lookup_handle - lookup a struct resource from a
246  * TTM user-space handle and perform basic type checks
247  *
248  * @dev_priv:     Pointer to a device private struct
249  * @tfile:        Pointer to a struct ttm_object_file identifying the caller
250  * @handle:       The TTM user-space handle
251  * @converter:    Pointer to an object describing the resource type
252  * @p_res:        On successful return the location pointed to will contain
253  *                a pointer to a refcounted struct vmw_resource.
254  *
255  * If the handle can't be found or is associated with an incorrect resource
256  * type, -EINVAL will be returned.
257  */
258 int vmw_user_resource_lookup_handle(struct vmw_private *dev_priv,
259 				    struct ttm_object_file *tfile,
260 				    uint32_t handle,
261 				    const struct vmw_user_resource_conv
262 				    *converter,
263 				    struct vmw_resource **p_res)
264 {
265 	struct ttm_base_object *base;
266 	struct vmw_resource *res;
267 	int ret = -EINVAL;
268 
269 	base = ttm_base_object_lookup(tfile, handle);
270 	if (unlikely(!base))
271 		return -EINVAL;
272 
273 	if (unlikely(ttm_base_object_type(base) != converter->object_type))
274 		goto out_bad_resource;
275 
276 	res = converter->base_obj_to_res(base);
277 	vmw_resource_reference(res);
278 
279 	*p_res = res;
280 	ret = 0;
281 
282 out_bad_resource:
283 	ttm_base_object_unref(&base);
284 
285 	return ret;
286 }
287 
288 /*
289  * Helper function that looks either a surface or bo.
290  *
291  * The pointer this pointed at by out_surf and out_buf needs to be null.
292  */
293 int vmw_user_object_lookup(struct vmw_private *dev_priv,
294 			   struct drm_file *filp,
295 			   u32 handle,
296 			   struct vmw_user_object *uo)
297 {
298 	struct ttm_object_file *tfile = vmw_fpriv(filp)->tfile;
299 	struct vmw_resource *res;
300 	int ret;
301 
302 	WARN_ON(uo->surface || uo->buffer);
303 
304 	ret = vmw_user_resource_lookup_handle(dev_priv, tfile, handle,
305 					      user_surface_converter,
306 					      &res);
307 	if (!ret) {
308 		uo->surface = vmw_res_to_srf(res);
309 		return 0;
310 	}
311 
312 	uo->surface = NULL;
313 	ret = vmw_user_bo_lookup(filp, handle, &uo->buffer);
314 	if (!ret && !uo->buffer->is_dumb) {
315 		uo->surface = vmw_lookup_surface_for_buffer(dev_priv,
316 							    uo->buffer,
317 							    handle);
318 		if (uo->surface)
319 			vmw_user_bo_unref(&uo->buffer);
320 	}
321 
322 	return ret;
323 }
324 
325 /**
326  * vmw_resource_buf_alloc - Allocate a guest memory buffer for a resource.
327  *
328  * @res:            The resource for which to allocate a gbo buffer.
329  * @interruptible:  Whether any sleeps during allocation should be
330  *                  performed while interruptible.
331  */
332 static int vmw_resource_buf_alloc(struct vmw_resource *res,
333 				  bool interruptible)
334 {
335 	unsigned long size = PFN_ALIGN(res->guest_memory_size);
336 	struct vmw_bo *gbo;
337 	struct vmw_bo_params bo_params = {
338 		.domain = res->func->domain,
339 		.busy_domain = res->func->busy_domain,
340 		.bo_type = ttm_bo_type_device,
341 		.size = res->guest_memory_size,
342 		.pin = false
343 	};
344 	int ret;
345 
346 	if (likely(res->guest_memory_bo)) {
347 		BUG_ON(res->guest_memory_bo->tbo.base.size < size);
348 		return 0;
349 	}
350 
351 	ret = vmw_bo_create(res->dev_priv, &bo_params, &gbo);
352 	if (unlikely(ret != 0))
353 		goto out_no_bo;
354 
355 	res->guest_memory_bo = gbo;
356 
357 out_no_bo:
358 	return ret;
359 }
360 
361 /**
362  * vmw_resource_do_validate - Make a resource up-to-date and visible
363  *                            to the device.
364  *
365  * @res:            The resource to make visible to the device.
366  * @val_buf:        Information about a buffer possibly
367  *                  containing backup data if a bind operation is needed.
368  * @dirtying:       Transfer dirty regions.
369  *
370  * On hardware resource shortage, this function returns -EBUSY and
371  * should be retried once resources have been freed up.
372  */
373 static int vmw_resource_do_validate(struct vmw_resource *res,
374 				    struct ttm_validate_buffer *val_buf,
375 				    bool dirtying)
376 {
377 	int ret = 0;
378 	const struct vmw_res_func *func = res->func;
379 
380 	if (unlikely(res->id == -1)) {
381 		ret = func->create(res);
382 		if (unlikely(ret != 0))
383 			return ret;
384 	}
385 
386 	if (func->bind &&
387 	    ((func->needs_guest_memory && !vmw_resource_mob_attached(res) &&
388 	      val_buf->bo) ||
389 	     (!func->needs_guest_memory && val_buf->bo))) {
390 		ret = func->bind(res, val_buf);
391 		if (unlikely(ret != 0))
392 			goto out_bind_failed;
393 		if (func->needs_guest_memory)
394 			vmw_resource_mob_attach(res);
395 	}
396 
397 	/*
398 	 * Handle the case where the backup mob is marked coherent but
399 	 * the resource isn't.
400 	 */
401 	if (func->dirty_alloc && vmw_resource_mob_attached(res) &&
402 	    !res->coherent) {
403 		if (res->guest_memory_bo->dirty && !res->dirty) {
404 			ret = func->dirty_alloc(res);
405 			if (ret)
406 				return ret;
407 		} else if (!res->guest_memory_bo->dirty && res->dirty) {
408 			func->dirty_free(res);
409 		}
410 	}
411 
412 	/*
413 	 * Transfer the dirty regions to the resource and update
414 	 * the resource.
415 	 */
416 	if (res->dirty) {
417 		if (dirtying && !res->res_dirty) {
418 			pgoff_t start = res->guest_memory_offset >> PAGE_SHIFT;
419 			pgoff_t end = __KERNEL_DIV_ROUND_UP
420 				(res->guest_memory_offset + res->guest_memory_size,
421 				 PAGE_SIZE);
422 
423 			vmw_bo_dirty_unmap(res->guest_memory_bo, start, end);
424 		}
425 
426 		vmw_bo_dirty_transfer_to_res(res);
427 		return func->dirty_sync(res);
428 	}
429 
430 	return 0;
431 
432 out_bind_failed:
433 	func->destroy(res);
434 
435 	return ret;
436 }
437 
438 /**
439  * vmw_resource_unreserve - Unreserve a resource previously reserved for
440  * command submission.
441  *
442  * @res:               Pointer to the struct vmw_resource to unreserve.
443  * @dirty_set:         Change dirty status of the resource.
444  * @dirty:             When changing dirty status indicates the new status.
445  * @switch_guest_memory: Guest memory buffer has been switched.
446  * @new_guest_memory_bo: Pointer to new guest memory buffer if command submission
447  *                     switched. May be NULL.
448  * @new_guest_memory_offset: New gbo offset if @switch_guest_memory is true.
449  *
450  * Currently unreserving a resource means putting it back on the device's
451  * resource lru list, so that it can be evicted if necessary.
452  */
453 void vmw_resource_unreserve(struct vmw_resource *res,
454 			    bool dirty_set,
455 			    bool dirty,
456 			    bool switch_guest_memory,
457 			    struct vmw_bo *new_guest_memory_bo,
458 			    unsigned long new_guest_memory_offset)
459 {
460 	struct vmw_private *dev_priv = res->dev_priv;
461 
462 	if (!list_empty(&res->lru_head))
463 		return;
464 
465 	if (switch_guest_memory && new_guest_memory_bo != res->guest_memory_bo) {
466 		if (res->guest_memory_bo) {
467 			vmw_resource_mob_detach(res);
468 			if (res->coherent)
469 				vmw_bo_dirty_release(res->guest_memory_bo);
470 			vmw_user_bo_unref(&res->guest_memory_bo);
471 		}
472 
473 		if (new_guest_memory_bo) {
474 			res->guest_memory_bo = vmw_user_bo_ref(new_guest_memory_bo);
475 
476 			/*
477 			 * The validation code should already have added a
478 			 * dirty tracker here.
479 			 */
480 			WARN_ON(res->coherent && !new_guest_memory_bo->dirty);
481 
482 			vmw_resource_mob_attach(res);
483 		} else {
484 			res->guest_memory_bo = NULL;
485 		}
486 	} else if (switch_guest_memory && res->coherent) {
487 		vmw_bo_dirty_release(res->guest_memory_bo);
488 	}
489 
490 	if (switch_guest_memory)
491 		res->guest_memory_offset = new_guest_memory_offset;
492 
493 	if (dirty_set)
494 		res->res_dirty = dirty;
495 
496 	if (!res->func->may_evict || res->id == -1 || res->pin_count)
497 		return;
498 
499 	spin_lock(&dev_priv->resource_lock);
500 	list_add_tail(&res->lru_head,
501 		      &res->dev_priv->res_lru[res->func->res_type]);
502 	spin_unlock(&dev_priv->resource_lock);
503 }
504 
505 /**
506  * vmw_resource_check_buffer - Check whether a backup buffer is needed
507  *                             for a resource and in that case, allocate
508  *                             one, reserve and validate it.
509  *
510  * @ticket:         The ww acquire context to use, or NULL if trylocking.
511  * @res:            The resource for which to allocate a backup buffer.
512  * @interruptible:  Whether any sleeps during allocation should be
513  *                  performed while interruptible.
514  * @val_buf:        On successful return contains data about the
515  *                  reserved and validated backup buffer.
516  */
517 static int
518 vmw_resource_check_buffer(struct ww_acquire_ctx *ticket,
519 			  struct vmw_resource *res,
520 			  bool interruptible,
521 			  struct ttm_validate_buffer *val_buf)
522 {
523 	struct ttm_operation_ctx ctx = { true, false };
524 	struct list_head val_list;
525 	bool guest_memory_dirty = false;
526 	int ret;
527 
528 	if (unlikely(!res->guest_memory_bo)) {
529 		ret = vmw_resource_buf_alloc(res, interruptible);
530 		if (unlikely(ret != 0))
531 			return ret;
532 	}
533 
534 	INIT_LIST_HEAD(&val_list);
535 	val_buf->bo = &res->guest_memory_bo->tbo;
536 	val_buf->num_shared = 0;
537 	drm_gem_object_get(&val_buf->bo->base);
538 	list_add_tail(&val_buf->head, &val_list);
539 	ret = ttm_eu_reserve_buffers(ticket, &val_list, interruptible, NULL);
540 	if (unlikely(ret != 0))
541 		goto out_no_reserve;
542 
543 	if (res->func->needs_guest_memory && !vmw_resource_mob_attached(res))
544 		return 0;
545 
546 	guest_memory_dirty = res->guest_memory_dirty;
547 	vmw_bo_placement_set(res->guest_memory_bo, res->func->domain,
548 			     res->func->busy_domain);
549 	ret = ttm_bo_validate(&res->guest_memory_bo->tbo,
550 			      &res->guest_memory_bo->placement,
551 			      &ctx);
552 
553 	if (unlikely(ret != 0))
554 		goto out_no_validate;
555 
556 	return 0;
557 
558 out_no_validate:
559 	ttm_eu_backoff_reservation(ticket, &val_list);
560 out_no_reserve:
561 	drm_gem_object_put(&val_buf->bo->base);
562 	val_buf->bo = NULL;
563 	if (guest_memory_dirty)
564 		vmw_user_bo_unref(&res->guest_memory_bo);
565 
566 	return ret;
567 }
568 
569 /*
570  * vmw_resource_reserve - Reserve a resource for command submission
571  *
572  * @res:            The resource to reserve.
573  *
574  * This function takes the resource off the LRU list and make sure
575  * a guest memory buffer is present for guest-backed resources.
576  * However, the buffer may not be bound to the resource at this
577  * point.
578  *
579  */
580 int vmw_resource_reserve(struct vmw_resource *res, bool interruptible,
581 			 bool no_guest_memory)
582 {
583 	struct vmw_private *dev_priv = res->dev_priv;
584 	int ret;
585 
586 	spin_lock(&dev_priv->resource_lock);
587 	list_del_init(&res->lru_head);
588 	spin_unlock(&dev_priv->resource_lock);
589 
590 	if (res->func->needs_guest_memory && !res->guest_memory_bo &&
591 	    !no_guest_memory) {
592 		ret = vmw_resource_buf_alloc(res, interruptible);
593 		if (unlikely(ret != 0)) {
594 			DRM_ERROR("Failed to allocate a guest memory buffer "
595 				  "of size %lu. bytes\n",
596 				  (unsigned long) res->guest_memory_size);
597 			return ret;
598 		}
599 	}
600 
601 	return 0;
602 }
603 
604 /**
605  * vmw_resource_backoff_reservation - Unreserve and unreference a
606  *                                    guest memory buffer
607  *.
608  * @ticket:         The ww acquire ctx used for reservation.
609  * @val_buf:        Guest memory buffer information.
610  */
611 static void
612 vmw_resource_backoff_reservation(struct ww_acquire_ctx *ticket,
613 				 struct ttm_validate_buffer *val_buf)
614 {
615 	struct list_head val_list;
616 
617 	if (likely(val_buf->bo == NULL))
618 		return;
619 
620 	INIT_LIST_HEAD(&val_list);
621 	list_add_tail(&val_buf->head, &val_list);
622 	ttm_eu_backoff_reservation(ticket, &val_list);
623 	drm_gem_object_put(&val_buf->bo->base);
624 	val_buf->bo = NULL;
625 }
626 
627 /**
628  * vmw_resource_do_evict - Evict a resource, and transfer its data
629  *                         to a backup buffer.
630  *
631  * @ticket:         The ww acquire ticket to use, or NULL if trylocking.
632  * @res:            The resource to evict.
633  * @interruptible:  Whether to wait interruptible.
634  */
635 static int vmw_resource_do_evict(struct ww_acquire_ctx *ticket,
636 				 struct vmw_resource *res, bool interruptible)
637 {
638 	struct ttm_validate_buffer val_buf;
639 	const struct vmw_res_func *func = res->func;
640 	int ret;
641 
642 	BUG_ON(!func->may_evict);
643 
644 	val_buf.bo = NULL;
645 	val_buf.num_shared = 0;
646 	ret = vmw_resource_check_buffer(ticket, res, interruptible, &val_buf);
647 	if (unlikely(ret != 0))
648 		return ret;
649 
650 	if (unlikely(func->unbind != NULL &&
651 		     (!func->needs_guest_memory || vmw_resource_mob_attached(res)))) {
652 		ret = func->unbind(res, res->res_dirty, &val_buf);
653 		if (unlikely(ret != 0))
654 			goto out_no_unbind;
655 		vmw_resource_mob_detach(res);
656 	}
657 	ret = func->destroy(res);
658 	res->guest_memory_dirty = true;
659 	res->res_dirty = false;
660 out_no_unbind:
661 	vmw_resource_backoff_reservation(ticket, &val_buf);
662 
663 	return ret;
664 }
665 
666 
667 /**
668  * vmw_resource_validate - Make a resource up-to-date and visible
669  *                         to the device.
670  * @res: The resource to make visible to the device.
671  * @intr: Perform waits interruptible if possible.
672  * @dirtying: Pending GPU operation will dirty the resource
673  *
674  * On successful return, any backup DMA buffer pointed to by @res->backup will
675  * be reserved and validated.
676  * On hardware resource shortage, this function will repeatedly evict
677  * resources of the same type until the validation succeeds.
678  *
679  * Return: Zero on success, -ERESTARTSYS if interrupted, negative error code
680  * on failure.
681  */
682 int vmw_resource_validate(struct vmw_resource *res, bool intr,
683 			  bool dirtying)
684 {
685 	int ret;
686 	struct vmw_resource *evict_res;
687 	struct vmw_private *dev_priv = res->dev_priv;
688 	struct list_head *lru_list = &dev_priv->res_lru[res->func->res_type];
689 	struct ttm_validate_buffer val_buf;
690 	unsigned err_count = 0;
691 
692 	if (!res->func->create)
693 		return 0;
694 
695 	val_buf.bo = NULL;
696 	val_buf.num_shared = 0;
697 	if (res->guest_memory_bo)
698 		val_buf.bo = &res->guest_memory_bo->tbo;
699 	do {
700 		ret = vmw_resource_do_validate(res, &val_buf, dirtying);
701 		if (likely(ret != -EBUSY))
702 			break;
703 
704 		spin_lock(&dev_priv->resource_lock);
705 		if (list_empty(lru_list) || !res->func->may_evict) {
706 			DRM_ERROR("Out of device device resources "
707 				  "for %s.\n", res->func->type_name);
708 			ret = -EBUSY;
709 			spin_unlock(&dev_priv->resource_lock);
710 			break;
711 		}
712 
713 		evict_res = vmw_resource_reference
714 			(list_first_entry(lru_list, struct vmw_resource,
715 					  lru_head));
716 		list_del_init(&evict_res->lru_head);
717 
718 		spin_unlock(&dev_priv->resource_lock);
719 
720 		/* Trylock backup buffers with a NULL ticket. */
721 		ret = vmw_resource_do_evict(NULL, evict_res, intr);
722 		if (unlikely(ret != 0)) {
723 			spin_lock(&dev_priv->resource_lock);
724 			list_add_tail(&evict_res->lru_head, lru_list);
725 			spin_unlock(&dev_priv->resource_lock);
726 			if (ret == -ERESTARTSYS ||
727 			    ++err_count > VMW_RES_EVICT_ERR_COUNT) {
728 				vmw_resource_unreference(&evict_res);
729 				goto out_no_validate;
730 			}
731 		}
732 
733 		vmw_resource_unreference(&evict_res);
734 	} while (1);
735 
736 	if (unlikely(ret != 0))
737 		goto out_no_validate;
738 	else if (!res->func->needs_guest_memory && res->guest_memory_bo) {
739 		WARN_ON_ONCE(vmw_resource_mob_attached(res));
740 		vmw_user_bo_unref(&res->guest_memory_bo);
741 	}
742 
743 	return 0;
744 
745 out_no_validate:
746 	return ret;
747 }
748 
749 
750 /**
751  * vmw_resource_unbind_list
752  *
753  * @vbo: Pointer to the current backing MOB.
754  *
755  * Evicts the Guest Backed hardware resource if the backup
756  * buffer is being moved out of MOB memory.
757  * Note that this function will not race with the resource
758  * validation code, since resource validation and eviction
759  * both require the backup buffer to be reserved.
760  */
761 void vmw_resource_unbind_list(struct vmw_bo *vbo)
762 {
763 	struct ttm_validate_buffer val_buf = {
764 		.bo = &vbo->tbo,
765 		.num_shared = 0
766 	};
767 
768 	dma_resv_assert_held(vbo->tbo.base.resv);
769 	while (!RB_EMPTY_ROOT(&vbo->res_tree)) {
770 		struct rb_node *node = vbo->res_tree.rb_node;
771 		struct vmw_resource *res =
772 			container_of(node, struct vmw_resource, mob_node);
773 
774 		if (!WARN_ON_ONCE(!res->func->unbind))
775 			(void) res->func->unbind(res, res->res_dirty, &val_buf);
776 
777 		res->guest_memory_dirty = true;
778 		res->res_dirty = false;
779 		vmw_resource_mob_detach(res);
780 	}
781 
782 	(void) ttm_bo_wait(&vbo->tbo, false, false);
783 }
784 
785 
786 /**
787  * vmw_query_readback_all - Read back cached query states
788  *
789  * @dx_query_mob: Buffer containing the DX query MOB
790  *
791  * Read back cached states from the device if they exist.  This function
792  * assumes binding_mutex is held.
793  */
794 int vmw_query_readback_all(struct vmw_bo *dx_query_mob)
795 {
796 	struct vmw_resource *dx_query_ctx;
797 	struct vmw_private *dev_priv;
798 	struct {
799 		SVGA3dCmdHeader header;
800 		SVGA3dCmdDXReadbackAllQuery body;
801 	} *cmd;
802 
803 
804 	/* No query bound, so do nothing */
805 	if (!dx_query_mob || !dx_query_mob->dx_query_ctx)
806 		return 0;
807 
808 	dx_query_ctx = dx_query_mob->dx_query_ctx;
809 	dev_priv     = dx_query_ctx->dev_priv;
810 
811 	cmd = VMW_CMD_CTX_RESERVE(dev_priv, sizeof(*cmd), dx_query_ctx->id);
812 	if (unlikely(cmd == NULL))
813 		return -ENOMEM;
814 
815 	cmd->header.id   = SVGA_3D_CMD_DX_READBACK_ALL_QUERY;
816 	cmd->header.size = sizeof(cmd->body);
817 	cmd->body.cid    = dx_query_ctx->id;
818 
819 	vmw_cmd_commit(dev_priv, sizeof(*cmd));
820 
821 	/* Triggers a rebind the next time affected context is bound */
822 	dx_query_mob->dx_query_ctx = NULL;
823 
824 	return 0;
825 }
826 
827 
828 
829 /**
830  * vmw_query_move_notify - Read back cached query states
831  *
832  * @bo: The TTM buffer object about to move.
833  * @old_mem: The memory region @bo is moving from.
834  * @new_mem: The memory region @bo is moving to.
835  *
836  * Called before the query MOB is swapped out to read back cached query
837  * states from the device.
838  */
839 void vmw_query_move_notify(struct ttm_buffer_object *bo,
840 			   struct ttm_resource *old_mem,
841 			   struct ttm_resource *new_mem)
842 {
843 	struct vmw_bo *dx_query_mob;
844 	struct ttm_device *bdev = bo->bdev;
845 	struct vmw_private *dev_priv = vmw_priv_from_ttm(bdev);
846 
847 	mutex_lock(&dev_priv->binding_mutex);
848 
849 	/* If BO is being moved from MOB to system memory */
850 	if (old_mem &&
851 	    new_mem->mem_type == TTM_PL_SYSTEM &&
852 	    old_mem->mem_type == VMW_PL_MOB) {
853 		struct vmw_fence_obj *fence;
854 
855 		dx_query_mob = to_vmw_bo(&bo->base);
856 		if (!dx_query_mob || !dx_query_mob->dx_query_ctx) {
857 			mutex_unlock(&dev_priv->binding_mutex);
858 			return;
859 		}
860 
861 		(void) vmw_query_readback_all(dx_query_mob);
862 		mutex_unlock(&dev_priv->binding_mutex);
863 
864 		/* Create a fence and attach the BO to it */
865 		(void) vmw_execbuf_fence_commands(NULL, dev_priv, &fence, NULL);
866 		vmw_bo_fence_single(bo, fence);
867 
868 		if (fence != NULL)
869 			vmw_fence_obj_unreference(&fence);
870 
871 		(void) ttm_bo_wait(bo, false, false);
872 	} else
873 		mutex_unlock(&dev_priv->binding_mutex);
874 }
875 
876 /**
877  * vmw_resource_needs_backup - Return whether a resource needs a backup buffer.
878  *
879  * @res:            The resource being queried.
880  */
881 bool vmw_resource_needs_backup(const struct vmw_resource *res)
882 {
883 	return res->func->needs_guest_memory;
884 }
885 
886 /**
887  * vmw_resource_evict_type - Evict all resources of a specific type
888  *
889  * @dev_priv:       Pointer to a device private struct
890  * @type:           The resource type to evict
891  *
892  * To avoid thrashing starvation or as part of the hibernation sequence,
893  * try to evict all evictable resources of a specific type.
894  */
895 static void vmw_resource_evict_type(struct vmw_private *dev_priv,
896 				    enum vmw_res_type type)
897 {
898 	struct list_head *lru_list = &dev_priv->res_lru[type];
899 	struct vmw_resource *evict_res;
900 	unsigned err_count = 0;
901 	int ret;
902 	struct ww_acquire_ctx ticket;
903 
904 	do {
905 		spin_lock(&dev_priv->resource_lock);
906 
907 		if (list_empty(lru_list))
908 			goto out_unlock;
909 
910 		evict_res = vmw_resource_reference(
911 			list_first_entry(lru_list, struct vmw_resource,
912 					 lru_head));
913 		list_del_init(&evict_res->lru_head);
914 		spin_unlock(&dev_priv->resource_lock);
915 
916 		/* Wait lock backup buffers with a ticket. */
917 		ret = vmw_resource_do_evict(&ticket, evict_res, false);
918 		if (unlikely(ret != 0)) {
919 			spin_lock(&dev_priv->resource_lock);
920 			list_add_tail(&evict_res->lru_head, lru_list);
921 			spin_unlock(&dev_priv->resource_lock);
922 			if (++err_count > VMW_RES_EVICT_ERR_COUNT) {
923 				vmw_resource_unreference(&evict_res);
924 				return;
925 			}
926 		}
927 
928 		vmw_resource_unreference(&evict_res);
929 	} while (1);
930 
931 out_unlock:
932 	spin_unlock(&dev_priv->resource_lock);
933 }
934 
935 /**
936  * vmw_resource_evict_all - Evict all evictable resources
937  *
938  * @dev_priv:       Pointer to a device private struct
939  *
940  * To avoid thrashing starvation or as part of the hibernation sequence,
941  * evict all evictable resources. In particular this means that all
942  * guest-backed resources that are registered with the device are
943  * evicted and the OTable becomes clean.
944  */
945 void vmw_resource_evict_all(struct vmw_private *dev_priv)
946 {
947 	enum vmw_res_type type;
948 
949 	mutex_lock(&dev_priv->cmdbuf_mutex);
950 
951 	for (type = 0; type < vmw_res_max; ++type)
952 		vmw_resource_evict_type(dev_priv, type);
953 
954 	mutex_unlock(&dev_priv->cmdbuf_mutex);
955 }
956 
957 /*
958  * vmw_resource_pin - Add a pin reference on a resource
959  *
960  * @res: The resource to add a pin reference on
961  *
962  * This function adds a pin reference, and if needed validates the resource.
963  * Having a pin reference means that the resource can never be evicted, and
964  * its id will never change as long as there is a pin reference.
965  * This function returns 0 on success and a negative error code on failure.
966  */
967 int vmw_resource_pin(struct vmw_resource *res, bool interruptible)
968 {
969 	struct ttm_operation_ctx ctx = { interruptible, false };
970 	struct vmw_private *dev_priv = res->dev_priv;
971 	int ret;
972 
973 	mutex_lock(&dev_priv->cmdbuf_mutex);
974 	ret = vmw_resource_reserve(res, interruptible, false);
975 	if (ret)
976 		goto out_no_reserve;
977 
978 	if (res->pin_count == 0) {
979 		struct vmw_bo *vbo = NULL;
980 
981 		if (res->guest_memory_bo) {
982 			vbo = res->guest_memory_bo;
983 
984 			ret = ttm_bo_reserve(&vbo->tbo, interruptible, false, NULL);
985 			if (ret)
986 				goto out_no_validate;
987 			if (!vbo->tbo.pin_count) {
988 				vmw_bo_placement_set(vbo,
989 						     res->func->domain,
990 						     res->func->busy_domain);
991 				ret = ttm_bo_validate
992 					(&vbo->tbo,
993 					 &vbo->placement,
994 					 &ctx);
995 				if (ret) {
996 					ttm_bo_unreserve(&vbo->tbo);
997 					goto out_no_validate;
998 				}
999 			}
1000 
1001 			/* Do we really need to pin the MOB as well? */
1002 			vmw_bo_pin_reserved(vbo, true);
1003 		}
1004 		ret = vmw_resource_validate(res, interruptible, true);
1005 		if (vbo)
1006 			ttm_bo_unreserve(&vbo->tbo);
1007 		if (ret)
1008 			goto out_no_validate;
1009 	}
1010 	res->pin_count++;
1011 
1012 out_no_validate:
1013 	vmw_resource_unreserve(res, false, false, false, NULL, 0UL);
1014 out_no_reserve:
1015 	mutex_unlock(&dev_priv->cmdbuf_mutex);
1016 
1017 	return ret;
1018 }
1019 
1020 /**
1021  * vmw_resource_unpin - Remove a pin reference from a resource
1022  *
1023  * @res: The resource to remove a pin reference from
1024  *
1025  * Having a pin reference means that the resource can never be evicted, and
1026  * its id will never change as long as there is a pin reference.
1027  */
1028 void vmw_resource_unpin(struct vmw_resource *res)
1029 {
1030 	struct vmw_private *dev_priv = res->dev_priv;
1031 	int ret;
1032 
1033 	mutex_lock(&dev_priv->cmdbuf_mutex);
1034 
1035 	ret = vmw_resource_reserve(res, false, true);
1036 	WARN_ON(ret);
1037 
1038 	WARN_ON(res->pin_count == 0);
1039 	if (--res->pin_count == 0 && res->guest_memory_bo) {
1040 		struct vmw_bo *vbo = res->guest_memory_bo;
1041 
1042 		(void) ttm_bo_reserve(&vbo->tbo, false, false, NULL);
1043 		vmw_bo_pin_reserved(vbo, false);
1044 		ttm_bo_unreserve(&vbo->tbo);
1045 	}
1046 
1047 	vmw_resource_unreserve(res, false, false, false, NULL, 0UL);
1048 
1049 	mutex_unlock(&dev_priv->cmdbuf_mutex);
1050 }
1051 
1052 /**
1053  * vmw_res_type - Return the resource type
1054  *
1055  * @res: Pointer to the resource
1056  */
1057 enum vmw_res_type vmw_res_type(const struct vmw_resource *res)
1058 {
1059 	return res->func->res_type;
1060 }
1061 
1062 /**
1063  * vmw_resource_dirty_update - Update a resource's dirty tracker with a
1064  * sequential range of touched backing store memory.
1065  * @res: The resource.
1066  * @start: The first page touched.
1067  * @end: The last page touched + 1.
1068  */
1069 void vmw_resource_dirty_update(struct vmw_resource *res, pgoff_t start,
1070 			       pgoff_t end)
1071 {
1072 	if (res->dirty)
1073 		res->func->dirty_range_add(res, start << PAGE_SHIFT,
1074 					   end << PAGE_SHIFT);
1075 }
1076 
1077 int vmw_resource_clean(struct vmw_resource *res)
1078 {
1079 	int ret = 0;
1080 
1081 	if (res->res_dirty) {
1082 		if (!res->func->clean)
1083 			return -EINVAL;
1084 
1085 		ret = res->func->clean(res);
1086 		if (ret)
1087 			return ret;
1088 		res->res_dirty = false;
1089 	}
1090 	return ret;
1091 }
1092 
1093 /**
1094  * vmw_resources_clean - Clean resources intersecting a mob range
1095  * @vbo: The mob buffer object
1096  * @start: The mob page offset starting the range
1097  * @end: The mob page offset ending the range
1098  * @num_prefault: Returns how many pages including the first have been
1099  * cleaned and are ok to prefault
1100  */
1101 int vmw_resources_clean(struct vmw_bo *vbo, pgoff_t start,
1102 			pgoff_t end, pgoff_t *num_prefault)
1103 {
1104 	struct rb_node *cur = vbo->res_tree.rb_node;
1105 	struct vmw_resource *found = NULL;
1106 	unsigned long res_start = start << PAGE_SHIFT;
1107 	unsigned long res_end = end << PAGE_SHIFT;
1108 	unsigned long last_cleaned = 0;
1109 	int ret;
1110 
1111 	/*
1112 	 * Find the resource with lowest backup_offset that intersects the
1113 	 * range.
1114 	 */
1115 	while (cur) {
1116 		struct vmw_resource *cur_res =
1117 			container_of(cur, struct vmw_resource, mob_node);
1118 
1119 		if (cur_res->guest_memory_offset >= res_end) {
1120 			cur = cur->rb_left;
1121 		} else if (cur_res->guest_memory_offset + cur_res->guest_memory_size <=
1122 			   res_start) {
1123 			cur = cur->rb_right;
1124 		} else {
1125 			found = cur_res;
1126 			cur = cur->rb_left;
1127 			/* Continue to look for resources with lower offsets */
1128 		}
1129 	}
1130 
1131 	/*
1132 	 * In order of increasing guest_memory_offset, clean dirty resources
1133 	 * intersecting the range.
1134 	 */
1135 	while (found) {
1136 		ret = vmw_resource_clean(found);
1137 		if (ret)
1138 			return ret;
1139 		last_cleaned = found->guest_memory_offset + found->guest_memory_size;
1140 		cur = rb_next(&found->mob_node);
1141 		if (!cur)
1142 			break;
1143 
1144 		found = container_of(cur, struct vmw_resource, mob_node);
1145 		if (found->guest_memory_offset >= res_end)
1146 			break;
1147 	}
1148 
1149 	/*
1150 	 * Set number of pages allowed prefaulting and fence the buffer object
1151 	 */
1152 	*num_prefault = 1;
1153 	if (last_cleaned > res_start) {
1154 		struct ttm_buffer_object *bo = &vbo->tbo;
1155 
1156 		*num_prefault = __KERNEL_DIV_ROUND_UP(last_cleaned - res_start,
1157 						      PAGE_SIZE);
1158 		vmw_bo_fence_single(bo, NULL);
1159 	}
1160 
1161 	return 0;
1162 }
1163