vmwgfx_resource.c 41.9 KB
Newer Older
1 2
/**************************************************************************
 *
S
Sinclair Yeh 已提交
3
 * Copyright © 2009-2015 VMware, Inc., Palo Alto, CA., USA
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
 * All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sub license, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice (including the
 * next paragraph) shall be included in all copies or substantial portions
 * of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
 * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
 * USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 **************************************************************************/

#include "vmwgfx_drv.h"
29 30 31 32
#include <drm/vmwgfx_drm.h>
#include <drm/ttm/ttm_object.h>
#include <drm/ttm/ttm_placement.h>
#include <drm/drmP.h>
33
#include "vmwgfx_resource_priv.h"
34
#include "vmwgfx_binding.h"
35

36 37
#define VMW_RES_EVICT_ERR_COUNT 10

38
struct vmw_user_buffer_object {
39
	struct ttm_prime_object prime;
40
	struct vmw_buffer_object vbo;
41 42 43 44 45 46 47
};

struct vmw_bo_user_rep {
	uint32_t handle;
	uint64_t map_handle;
};

48 49
static inline struct vmw_buffer_object *
vmw_buffer_object(struct ttm_buffer_object *bo)
50
{
51
	return container_of(bo, struct vmw_buffer_object, base);
52 53
}

54 55
static inline struct vmw_user_buffer_object *
vmw_user_buffer_object(struct ttm_buffer_object *bo)
56
{
57 58 59
	struct vmw_buffer_object *vmw_bo = vmw_buffer_object(bo);

	return container_of(vmw_bo, struct vmw_user_buffer_object, vbo);
60 61 62 63 64 65 66 67
}

struct vmw_resource *vmw_resource_reference(struct vmw_resource *res)
{
	kref_get(&res->kref);
	return res;
}

68 69 70 71 72
struct vmw_resource *
vmw_resource_reference_unless_doomed(struct vmw_resource *res)
{
	return kref_get_unless_zero(&res->kref) ? res : NULL;
}
73 74 75 76 77 78 79 80

/**
 * vmw_resource_release_id - release a resource id to the id manager.
 *
 * @res: Pointer to the resource.
 *
 * Release the resource id to the resource id manager and set it to -1
 */
81
void vmw_resource_release_id(struct vmw_resource *res)
82 83
{
	struct vmw_private *dev_priv = res->dev_priv;
84
	struct idr *idr = &dev_priv->res_idr[res->func->res_type];
85 86 87

	write_lock(&dev_priv->resource_lock);
	if (res->id != -1)
88
		idr_remove(idr, res->id);
89 90 91 92
	res->id = -1;
	write_unlock(&dev_priv->resource_lock);
}

93 94 95 96 97
static void vmw_resource_release(struct kref *kref)
{
	struct vmw_resource *res =
	    container_of(kref, struct vmw_resource, kref);
	struct vmw_private *dev_priv = res->dev_priv;
98 99
	int id;
	struct idr *idr = &dev_priv->res_idr[res->func->res_type];
100

101
	write_lock(&dev_priv->resource_lock);
102
	res->avail = false;
103
	list_del_init(&res->lru_head);
104
	write_unlock(&dev_priv->resource_lock);
105 106 107
	if (res->backup) {
		struct ttm_buffer_object *bo = &res->backup->base;

108
		ttm_bo_reserve(bo, false, false, NULL);
109 110 111 112 113
		if (!list_empty(&res->mob_head) &&
		    res->func->unbind != NULL) {
			struct ttm_validate_buffer val_buf;

			val_buf.bo = bo;
114
			val_buf.shared = false;
115 116 117 118 119
			res->func->unbind(res, false, &val_buf);
		}
		res->backup_dirty = false;
		list_del_init(&res->mob_head);
		ttm_bo_unreserve(bo);
120
		vmw_bo_unreference(&res->backup);
121
	}
122

123 124
	if (likely(res->hw_destroy != NULL)) {
		mutex_lock(&dev_priv->binding_mutex);
125
		vmw_binding_res_list_kill(&res->binding_head);
126
		mutex_unlock(&dev_priv->binding_mutex);
127
		res->hw_destroy(res);
128
	}
129

130
	id = res->id;
131 132 133 134 135 136
	if (res->res_free != NULL)
		res->res_free(res);
	else
		kfree(res);

	write_lock(&dev_priv->resource_lock);
137 138
	if (id != -1)
		idr_remove(idr, id);
139
	write_unlock(&dev_priv->resource_lock);
140 141 142 143 144 145 146 147 148 149
}

void vmw_resource_unreference(struct vmw_resource **p_res)
{
	struct vmw_resource *res = *p_res;

	*p_res = NULL;
	kref_put(&res->kref, vmw_resource_release);
}

150 151 152 153 154 155 156 157 158

/**
 * vmw_resource_alloc_id - release a resource id to the id manager.
 *
 * @res: Pointer to the resource.
 *
 * Allocate the lowest free resource from the resource manager, and set
 * @res->id to that id. Returns 0 on success and -ENOMEM on failure.
 */
159
int vmw_resource_alloc_id(struct vmw_resource *res)
160
{
161
	struct vmw_private *dev_priv = res->dev_priv;
162
	int ret;
163
	struct idr *idr = &dev_priv->res_idr[res->func->res_type];
164 165 166

	BUG_ON(res->id != -1);

T
Tejun Heo 已提交
167 168
	idr_preload(GFP_KERNEL);
	write_lock(&dev_priv->resource_lock);
169

T
Tejun Heo 已提交
170 171 172
	ret = idr_alloc(idr, res, 1, 0, GFP_NOWAIT);
	if (ret >= 0)
		res->id = ret;
173

T
Tejun Heo 已提交
174 175 176
	write_unlock(&dev_priv->resource_lock);
	idr_preload_end();
	return ret < 0 ? ret : 0;
177 178
}

179 180 181 182 183 184 185 186 187 188 189
/**
 * vmw_resource_init - initialize a struct vmw_resource
 *
 * @dev_priv:       Pointer to a device private struct.
 * @res:            The struct vmw_resource to initialize.
 * @obj_type:       Resource object type.
 * @delay_id:       Boolean whether to defer device id allocation until
 *                  the first validation.
 * @res_free:       Resource destructor.
 * @func:           Resource function table.
 */
190 191 192 193
int vmw_resource_init(struct vmw_private *dev_priv, struct vmw_resource *res,
		      bool delay_id,
		      void (*res_free) (struct vmw_resource *res),
		      const struct vmw_res_func *func)
194 195 196 197 198 199
{
	kref_init(&res->kref);
	res->hw_destroy = NULL;
	res->res_free = res_free;
	res->avail = false;
	res->dev_priv = dev_priv;
200 201 202
	res->func = func;
	INIT_LIST_HEAD(&res->lru_head);
	INIT_LIST_HEAD(&res->mob_head);
203
	INIT_LIST_HEAD(&res->binding_head);
204
	res->id = -1;
205 206 207 208
	res->backup = NULL;
	res->backup_offset = 0;
	res->backup_dirty = false;
	res->res_dirty = false;
209 210 211
	if (delay_id)
		return 0;
	else
212
		return vmw_resource_alloc_id(res);
213 214 215 216 217 218 219 220 221 222 223 224 225 226
}

/**
 * vmw_resource_activate
 *
 * @res:        Pointer to the newly created resource
 * @hw_destroy: Destroy function. NULL if none.
 *
 * Activate a resource after the hardware has been made aware of it.
 * Set tye destroy function to @destroy. Typically this frees the
 * resource and destroys the hardware resources associated with it.
 * Activate basically means that the function vmw_resource_lookup will
 * find it.
 */
227 228
void vmw_resource_activate(struct vmw_resource *res,
			   void (*hw_destroy) (struct vmw_resource *))
229 230 231 232 233 234 235 236 237
{
	struct vmw_private *dev_priv = res->dev_priv;

	write_lock(&dev_priv->resource_lock);
	res->avail = true;
	res->hw_destroy = hw_destroy;
	write_unlock(&dev_priv->resource_lock);
}

238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
/**
 * vmw_user_resource_lookup_handle - lookup a struct resource from a
 * TTM user-space handle and perform basic type checks
 *
 * @dev_priv:     Pointer to a device private struct
 * @tfile:        Pointer to a struct ttm_object_file identifying the caller
 * @handle:       The TTM user-space handle
 * @converter:    Pointer to an object describing the resource type
 * @p_res:        On successful return the location pointed to will contain
 *                a pointer to a refcounted struct vmw_resource.
 *
 * If the handle can't be found or is associated with an incorrect resource
 * type, -EINVAL will be returned.
 */
int vmw_user_resource_lookup_handle(struct vmw_private *dev_priv,
				    struct ttm_object_file *tfile,
				    uint32_t handle,
				    const struct vmw_user_resource_conv
				    *converter,
				    struct vmw_resource **p_res)
258
{
259
	struct ttm_base_object *base;
260 261
	struct vmw_resource *res;
	int ret = -EINVAL;
262

263 264 265 266
	base = ttm_base_object_lookup(tfile, handle);
	if (unlikely(base == NULL))
		return -EINVAL;

267
	if (unlikely(ttm_base_object_type(base) != converter->object_type))
268
		goto out_bad_resource;
269

270
	res = converter->base_obj_to_res(base);
271

272 273 274 275 276
	read_lock(&dev_priv->resource_lock);
	if (!res->avail || res->res_free != converter->res_free) {
		read_unlock(&dev_priv->resource_lock);
		goto out_bad_resource;
	}
277

278 279 280 281 282 283 284
	kref_get(&res->kref);
	read_unlock(&dev_priv->resource_lock);

	*p_res = res;
	ret = 0;

out_bad_resource:
285
	ttm_base_object_unref(&base);
286 287 288 289 290

	return ret;
}

/**
291
 * Helper function that looks either a surface or bo.
292 293 294 295 296 297 298
 *
 * The pointer this pointed at by out_surf and out_buf needs to be null.
 */
int vmw_user_lookup_handle(struct vmw_private *dev_priv,
			   struct ttm_object_file *tfile,
			   uint32_t handle,
			   struct vmw_surface **out_surf,
299
			   struct vmw_buffer_object **out_buf)
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
{
	struct vmw_resource *res;
	int ret;

	BUG_ON(*out_surf || *out_buf);

	ret = vmw_user_resource_lookup_handle(dev_priv, tfile, handle,
					      user_surface_converter,
					      &res);
	if (!ret) {
		*out_surf = vmw_res_to_srf(res);
		return 0;
	}

	*out_surf = NULL;
315
	ret = vmw_user_bo_lookup(tfile, handle, out_buf, NULL);
316 317 318 319 320 321
	return ret;
}

/**
 * Buffer management.
 */
322 323

/**
324
 * vmw_bo_acc_size - Calculate the pinned memory usage of buffers
325 326 327 328 329
 *
 * @dev_priv: Pointer to a struct vmw_private identifying the device.
 * @size: The requested buffer size.
 * @user: Whether this is an ordinary dma buffer or a user dma buffer.
 */
330 331
static size_t vmw_bo_acc_size(struct vmw_private *dev_priv, size_t size,
			      bool user)
332 333 334 335 336 337 338 339 340
{
	static size_t struct_size, user_struct_size;
	size_t num_pages = PAGE_ALIGN(size) >> PAGE_SHIFT;
	size_t page_array_size = ttm_round_pot(num_pages * sizeof(void *));

	if (unlikely(struct_size == 0)) {
		size_t backend_size = ttm_round_pot(vmw_tt_size);

		struct_size = backend_size +
341
			ttm_round_pot(sizeof(struct vmw_buffer_object));
342
		user_struct_size = backend_size +
343
			ttm_round_pot(sizeof(struct vmw_user_buffer_object));
344 345 346 347 348 349 350 351 352 353
	}

	if (dev_priv->map_mode == vmw_dma_alloc_coherent)
		page_array_size +=
			ttm_round_pot(num_pages * sizeof(dma_addr_t));

	return ((user) ? user_struct_size : struct_size) +
		page_array_size;
}

354
void vmw_bo_bo_free(struct ttm_buffer_object *bo)
355
{
356
	struct vmw_buffer_object *vmw_bo = vmw_buffer_object(bo);
357

358
	vmw_buffer_object_unmap(vmw_bo);
359 360 361
	kfree(vmw_bo);
}

362
static void vmw_user_bo_destroy(struct ttm_buffer_object *bo)
363
{
364
	struct vmw_user_buffer_object *vmw_user_bo = vmw_user_buffer_object(bo);
365

366
	vmw_buffer_object_unmap(&vmw_user_bo->vbo);
367 368 369
	ttm_prime_object_kfree(vmw_user_bo, prime);
}

370 371 372 373 374
int vmw_bo_init(struct vmw_private *dev_priv,
		struct vmw_buffer_object *vmw_bo,
		size_t size, struct ttm_placement *placement,
		bool interruptible,
		void (*bo_free)(struct ttm_buffer_object *bo))
375 376 377 378
{
	struct ttm_bo_device *bdev = &dev_priv->bdev;
	size_t acc_size;
	int ret;
379
	bool user = (bo_free == &vmw_user_bo_destroy);
380

381
	WARN_ON_ONCE(!bo_free && (!user && (bo_free != vmw_bo_bo_free)));
382

383
	acc_size = vmw_bo_acc_size(dev_priv, size, user);
384 385
	memset(vmw_bo, 0, sizeof(*vmw_bo));

386
	INIT_LIST_HEAD(&vmw_bo->res_list);
387 388

	ret = ttm_bo_init(bdev, &vmw_bo->base, size,
389
			  ttm_bo_type_device, placement,
390 391
			  0, interruptible, acc_size,
			  NULL, NULL, bo_free);
392 393 394
	return ret;
}

395
static void vmw_user_bo_release(struct ttm_base_object **p_base)
396
{
397
	struct vmw_user_buffer_object *vmw_user_bo;
398 399 400 401 402 403 404 405
	struct ttm_base_object *base = *p_base;
	struct ttm_buffer_object *bo;

	*p_base = NULL;

	if (unlikely(base == NULL))
		return;

406
	vmw_user_bo = container_of(base, struct vmw_user_buffer_object,
407
				   prime.base);
408
	bo = &vmw_user_bo->vbo.base;
409 410 411
	ttm_bo_unref(&bo);
}

412 413
static void vmw_user_bo_ref_obj_release(struct ttm_base_object *base,
					enum ttm_ref_type ref_type)
414
{
415 416 417
	struct vmw_user_buffer_object *user_bo;

	user_bo = container_of(base, struct vmw_user_buffer_object, prime.base);
418 419 420

	switch (ref_type) {
	case TTM_REF_SYNCCPU_WRITE:
421
		ttm_bo_synccpu_write_release(&user_bo->vbo.base);
422 423 424 425 426 427
		break;
	default:
		BUG();
	}
}

428
/**
429
 * vmw_user_bo_alloc - Allocate a user dma buffer
430 431 432 433 434 435 436
 *
 * @dev_priv: Pointer to a struct device private.
 * @tfile: Pointer to a struct ttm_object_file on which to register the user
 * object.
 * @size: Size of the dma buffer.
 * @shareable: Boolean whether the buffer is shareable with other open files.
 * @handle: Pointer to where the handle value should be assigned.
437
 * @p_vbo: Pointer to where the refcounted struct vmw_buffer_object pointer
438 439
 * should be assigned.
 */
440 441 442 443 444 445 446
int vmw_user_bo_alloc(struct vmw_private *dev_priv,
		      struct ttm_object_file *tfile,
		      uint32_t size,
		      bool shareable,
		      uint32_t *handle,
		      struct vmw_buffer_object **p_vbo,
		      struct ttm_base_object **p_base)
447
{
448
	struct vmw_user_buffer_object *user_bo;
449 450 451 452
	struct ttm_buffer_object *tmp;
	int ret;

	user_bo = kzalloc(sizeof(*user_bo), GFP_KERNEL);
453
	if (unlikely(!user_bo)) {
454 455 456 457
		DRM_ERROR("Failed to allocate a buffer.\n");
		return -ENOMEM;
	}

458 459 460 461 462
	ret = vmw_bo_init(dev_priv, &user_bo->vbo, size,
			  (dev_priv->has_mob) ?
			  &vmw_sys_placement :
			  &vmw_vram_sys_placement, true,
			  &vmw_user_bo_destroy);
463 464 465
	if (unlikely(ret != 0))
		return ret;

466
	tmp = ttm_bo_reference(&user_bo->vbo.base);
467 468 469 470 471
	ret = ttm_prime_object_init(tfile,
				    size,
				    &user_bo->prime,
				    shareable,
				    ttm_buffer_type,
472 473
				    &vmw_user_bo_release,
				    &vmw_user_bo_ref_obj_release);
474 475 476 477 478
	if (unlikely(ret != 0)) {
		ttm_bo_unref(&tmp);
		goto out_no_base_object;
	}

479
	*p_vbo = &user_bo->vbo;
480 481 482 483
	if (p_base) {
		*p_base = &user_bo->prime.base;
		kref_get(&(*p_base)->refcount);
	}
484
	*handle = user_bo->prime.base.hash.key;
485 486 487 488 489

out_no_base_object:
	return ret;
}

490
/**
491
 * vmw_user_bo_verify_access - verify access permissions on this
492 493 494 495 496
 * buffer object.
 *
 * @bo: Pointer to the buffer object being accessed
 * @tfile: Identifying the caller.
 */
497
int vmw_user_bo_verify_access(struct ttm_buffer_object *bo,
498 499
				  struct ttm_object_file *tfile)
{
500
	struct vmw_user_buffer_object *vmw_user_bo;
501

502
	if (unlikely(bo->destroy != vmw_user_bo_destroy))
503 504
		return -EPERM;

505
	vmw_user_bo = vmw_user_buffer_object(bo);
506 507 508 509 510 511 512

	/* Check that the caller has opened the object. */
	if (likely(ttm_ref_object_exists(tfile, &vmw_user_bo->prime.base)))
		return 0;

	DRM_ERROR("Could not grant buffer access.\n");
	return -EPERM;
513 514
}

515
/**
516
 * vmw_user_bo_synccpu_grab - Grab a struct vmw_user_buffer_object for cpu
517 518 519 520 521 522 523 524 525
 * access, idling previous GPU operations on the buffer and optionally
 * blocking it for further command submissions.
 *
 * @user_bo: Pointer to the buffer object being grabbed for CPU access
 * @tfile: Identifying the caller.
 * @flags: Flags indicating how the grab should be performed.
 *
 * A blocking grab will be automatically released when @tfile is closed.
 */
526
static int vmw_user_bo_synccpu_grab(struct vmw_user_buffer_object *user_bo,
527 528 529
					struct ttm_object_file *tfile,
					uint32_t flags)
{
530
	struct ttm_buffer_object *bo = &user_bo->vbo.base;
531 532 533 534
	bool existed;
	int ret;

	if (flags & drm_vmw_synccpu_allow_cs) {
M
Maarten Lankhorst 已提交
535
		bool nonblock = !!(flags & drm_vmw_synccpu_dontblock);
536
		long lret;
537

538 539
		lret = reservation_object_wait_timeout_rcu(bo->resv, true, true,
							   nonblock ? 0 : MAX_SCHEDULE_TIMEOUT);
540 541 542 543 544
		if (!lret)
			return -EBUSY;
		else if (lret < 0)
			return lret;
		return 0;
545 546 547 548 549 550 551 552
	}

	ret = ttm_bo_synccpu_write_grab
		(bo, !!(flags & drm_vmw_synccpu_dontblock));
	if (unlikely(ret != 0))
		return ret;

	ret = ttm_ref_object_add(tfile, &user_bo->prime.base,
553
				 TTM_REF_SYNCCPU_WRITE, &existed, false);
554
	if (ret != 0 || existed)
555
		ttm_bo_synccpu_write_release(&user_bo->vbo.base);
556 557 558 559 560

	return ret;
}

/**
561
 * vmw_user_bo_synccpu_release - Release a previous grab for CPU access,
562 563 564 565 566 567
 * and unblock command submission on the buffer if blocked.
 *
 * @handle: Handle identifying the buffer object.
 * @tfile: Identifying the caller.
 * @flags: Flags indicating the type of release.
 */
568
static int vmw_user_bo_synccpu_release(uint32_t handle,
569 570 571 572 573 574 575 576 577 578 579
					   struct ttm_object_file *tfile,
					   uint32_t flags)
{
	if (!(flags & drm_vmw_synccpu_allow_cs))
		return ttm_ref_object_base_unref(tfile, handle,
						 TTM_REF_SYNCCPU_WRITE);

	return 0;
}

/**
580
 * vmw_user_bo_synccpu_release - ioctl function implementing the synccpu
581 582 583 584 585 586 587 588 589
 * functionality.
 *
 * @dev: Identifies the drm device.
 * @data: Pointer to the ioctl argument.
 * @file_priv: Identifies the caller.
 *
 * This function checks the ioctl arguments for validity and calls the
 * relevant synccpu functions.
 */
590
int vmw_user_bo_synccpu_ioctl(struct drm_device *dev, void *data,
591 592 593 594
				  struct drm_file *file_priv)
{
	struct drm_vmw_synccpu_arg *arg =
		(struct drm_vmw_synccpu_arg *) data;
595 596
	struct vmw_buffer_object *vbo;
	struct vmw_user_buffer_object *user_bo;
597
	struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile;
598
	struct ttm_base_object *buffer_base;
599 600 601 602 603 604 605 606 607 608 609 610
	int ret;

	if ((arg->flags & (drm_vmw_synccpu_read | drm_vmw_synccpu_write)) == 0
	    || (arg->flags & ~(drm_vmw_synccpu_read | drm_vmw_synccpu_write |
			       drm_vmw_synccpu_dontblock |
			       drm_vmw_synccpu_allow_cs)) != 0) {
		DRM_ERROR("Illegal synccpu flags.\n");
		return -EINVAL;
	}

	switch (arg->op) {
	case drm_vmw_synccpu_grab:
611
		ret = vmw_user_bo_lookup(tfile, arg->handle, &vbo,
612
					     &buffer_base);
613 614 615
		if (unlikely(ret != 0))
			return ret;

616 617 618 619
		user_bo = container_of(vbo, struct vmw_user_buffer_object,
				       vbo);
		ret = vmw_user_bo_synccpu_grab(user_bo, tfile, arg->flags);
		vmw_bo_unreference(&vbo);
620
		ttm_base_object_unref(&buffer_base);
621 622 623 624 625 626 627 628
		if (unlikely(ret != 0 && ret != -ERESTARTSYS &&
			     ret != -EBUSY)) {
			DRM_ERROR("Failed synccpu grab on handle 0x%08x.\n",
				  (unsigned int) arg->handle);
			return ret;
		}
		break;
	case drm_vmw_synccpu_release:
629 630
		ret = vmw_user_bo_synccpu_release(arg->handle, tfile,
						  arg->flags);
631 632 633 634 635 636 637 638 639 640 641 642 643 644
		if (unlikely(ret != 0)) {
			DRM_ERROR("Failed synccpu release on handle 0x%08x.\n",
				  (unsigned int) arg->handle);
			return ret;
		}
		break;
	default:
		DRM_ERROR("Invalid synccpu operation.\n");
		return -EINVAL;
	}

	return 0;
}

645 646
int vmw_bo_alloc_ioctl(struct drm_device *dev, void *data,
		       struct drm_file *file_priv)
647 648 649 650 651 652
{
	struct vmw_private *dev_priv = vmw_priv(dev);
	union drm_vmw_alloc_dmabuf_arg *arg =
	    (union drm_vmw_alloc_dmabuf_arg *)data;
	struct drm_vmw_alloc_dmabuf_req *req = &arg->req;
	struct drm_vmw_dmabuf_rep *rep = &arg->rep;
653
	struct vmw_buffer_object *vbo;
654
	uint32_t handle;
655 656
	int ret;

657
	ret = ttm_read_lock(&dev_priv->reservation_sem, true);
658
	if (unlikely(ret != 0))
659 660
		return ret;

661 662 663
	ret = vmw_user_bo_alloc(dev_priv, vmw_fpriv(file_priv)->tfile,
				req->size, false, &handle, &vbo,
				NULL);
664
	if (unlikely(ret != 0))
665
		goto out_no_bo;
666

667
	rep->handle = handle;
668
	rep->map_handle = drm_vma_node_offset_addr(&vbo->base.vma_node);
669 670 671
	rep->cur_gmr_id = handle;
	rep->cur_gmr_offset = 0;

672
	vmw_bo_unreference(&vbo);
673

674
out_no_bo:
675
	ttm_read_unlock(&dev_priv->reservation_sem);
676

677
	return ret;
678 679
}

680 681
int vmw_bo_unref_ioctl(struct drm_device *dev, void *data,
		       struct drm_file *file_priv)
682 683 684 685 686 687 688 689 690
{
	struct drm_vmw_unref_dmabuf_arg *arg =
	    (struct drm_vmw_unref_dmabuf_arg *)data;

	return ttm_ref_object_base_unref(vmw_fpriv(file_priv)->tfile,
					 arg->handle,
					 TTM_REF_USAGE);
}

691 692
int vmw_user_bo_lookup(struct ttm_object_file *tfile,
			   uint32_t handle, struct vmw_buffer_object **out,
693
			   struct ttm_base_object **p_base)
694
{
695
	struct vmw_user_buffer_object *vmw_user_bo;
696 697 698 699
	struct ttm_base_object *base;

	base = ttm_base_object_lookup(tfile, handle);
	if (unlikely(base == NULL)) {
700
		pr_err("Invalid buffer object handle 0x%08lx\n",
701 702 703 704
		       (unsigned long)handle);
		return -ESRCH;
	}

705
	if (unlikely(ttm_base_object_type(base) != ttm_buffer_type)) {
706
		ttm_base_object_unref(&base);
707
		pr_err("Invalid buffer object handle 0x%08lx\n",
708 709 710 711
		       (unsigned long)handle);
		return -EINVAL;
	}

712
	vmw_user_bo = container_of(base, struct vmw_user_buffer_object,
713
				   prime.base);
714
	(void)ttm_bo_reference(&vmw_user_bo->vbo.base);
715 716 717 718
	if (p_base)
		*p_base = base;
	else
		ttm_base_object_unref(&base);
719
	*out = &vmw_user_bo->vbo;
720 721 722 723

	return 0;
}

724 725
int vmw_user_bo_reference(struct ttm_object_file *tfile,
			      struct vmw_buffer_object *vbo,
726
			      uint32_t *handle)
727
{
728
	struct vmw_user_buffer_object *user_bo;
729

730
	if (vbo->base.destroy != vmw_user_bo_destroy)
731 732
		return -EINVAL;

733
	user_bo = container_of(vbo, struct vmw_user_buffer_object, vbo);
734 735

	*handle = user_bo->prime.base.hash.key;
736
	return ttm_ref_object_add(tfile, &user_bo->prime.base,
737
				  TTM_REF_USAGE, NULL, false);
738 739
}

740 741 742 743 744 745 746 747
/**
 * vmw_dumb_create - Create a dumb kms buffer
 *
 * @file_priv: Pointer to a struct drm_file identifying the caller.
 * @dev: Pointer to the drm device.
 * @args: Pointer to a struct drm_mode_create_dumb structure
 *
 * This is a driver callback for the core drm create_dumb functionality.
748
 * Note that this is very similar to the vmw_bo_alloc ioctl, except
749 750
 * that the arguments have a different format.
 */
D
Dave Airlie 已提交
751 752 753 754 755
int vmw_dumb_create(struct drm_file *file_priv,
		    struct drm_device *dev,
		    struct drm_mode_create_dumb *args)
{
	struct vmw_private *dev_priv = vmw_priv(dev);
756
	struct vmw_buffer_object *vbo;
D
Dave Airlie 已提交
757 758 759 760 761
	int ret;

	args->pitch = args->width * ((args->bpp + 7) / 8);
	args->size = args->pitch * args->height;

762
	ret = ttm_read_lock(&dev_priv->reservation_sem, true);
763
	if (unlikely(ret != 0))
D
Dave Airlie 已提交
764 765
		return ret;

766
	ret = vmw_user_bo_alloc(dev_priv, vmw_fpriv(file_priv)->tfile,
767
				    args->size, false, &args->handle,
768
				    &vbo, NULL);
D
Dave Airlie 已提交
769
	if (unlikely(ret != 0))
770
		goto out_no_bo;
D
Dave Airlie 已提交
771

772 773
	vmw_bo_unreference(&vbo);
out_no_bo:
774
	ttm_read_unlock(&dev_priv->reservation_sem);
D
Dave Airlie 已提交
775 776 777
	return ret;
}

778 779 780 781 782 783 784 785 786 787
/**
 * vmw_dumb_map_offset - Return the address space offset of a dumb buffer
 *
 * @file_priv: Pointer to a struct drm_file identifying the caller.
 * @dev: Pointer to the drm device.
 * @handle: Handle identifying the dumb buffer.
 * @offset: The address space offset returned.
 *
 * This is a driver callback for the core drm dumb_map_offset functionality.
 */
D
Dave Airlie 已提交
788 789 790 791 792
int vmw_dumb_map_offset(struct drm_file *file_priv,
			struct drm_device *dev, uint32_t handle,
			uint64_t *offset)
{
	struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile;
793
	struct vmw_buffer_object *out_buf;
D
Dave Airlie 已提交
794 795
	int ret;

796
	ret = vmw_user_bo_lookup(tfile, handle, &out_buf, NULL);
D
Dave Airlie 已提交
797 798 799
	if (ret != 0)
		return -EINVAL;

800
	*offset = drm_vma_node_offset_addr(&out_buf->base.vma_node);
801
	vmw_bo_unreference(&out_buf);
D
Dave Airlie 已提交
802 803 804
	return 0;
}

805 806 807 808 809 810 811 812 813
/**
 * vmw_dumb_destroy - Destroy a dumb boffer
 *
 * @file_priv: Pointer to a struct drm_file identifying the caller.
 * @dev: Pointer to the drm device.
 * @handle: Handle identifying the dumb buffer.
 *
 * This is a driver callback for the core drm dumb_destroy functionality.
 */
D
Dave Airlie 已提交
814 815 816 817 818 819 820
int vmw_dumb_destroy(struct drm_file *file_priv,
		     struct drm_device *dev,
		     uint32_t handle)
{
	return ttm_ref_object_base_unref(vmw_fpriv(file_priv)->tfile,
					 handle, TTM_REF_USAGE);
}
821 822 823 824 825 826 827 828 829 830 831 832 833

/**
 * vmw_resource_buf_alloc - Allocate a backup buffer for a resource.
 *
 * @res:            The resource for which to allocate a backup buffer.
 * @interruptible:  Whether any sleeps during allocation should be
 *                  performed while interruptible.
 */
static int vmw_resource_buf_alloc(struct vmw_resource *res,
				  bool interruptible)
{
	unsigned long size =
		(res->backup_size + PAGE_SIZE - 1) & PAGE_MASK;
834
	struct vmw_buffer_object *backup;
835 836 837 838 839 840 841 842
	int ret;

	if (likely(res->backup)) {
		BUG_ON(res->backup->base.num_pages * PAGE_SIZE < size);
		return 0;
	}

	backup = kzalloc(sizeof(*backup), GFP_KERNEL);
843
	if (unlikely(!backup))
844 845
		return -ENOMEM;

846
	ret = vmw_bo_init(res->dev_priv, backup, res->backup_size,
847 848
			      res->func->backup_placement,
			      interruptible,
849
			      &vmw_bo_bo_free);
850
	if (unlikely(ret != 0))
851
		goto out_no_bo;
852 853 854

	res->backup = backup;

855
out_no_bo:
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
	return ret;
}

/**
 * vmw_resource_do_validate - Make a resource up-to-date and visible
 *                            to the device.
 *
 * @res:            The resource to make visible to the device.
 * @val_buf:        Information about a buffer possibly
 *                  containing backup data if a bind operation is needed.
 *
 * On hardware resource shortage, this function returns -EBUSY and
 * should be retried once resources have been freed up.
 */
static int vmw_resource_do_validate(struct vmw_resource *res,
				    struct ttm_validate_buffer *val_buf)
{
	int ret = 0;
	const struct vmw_res_func *func = res->func;

	if (unlikely(res->id == -1)) {
		ret = func->create(res);
		if (unlikely(ret != 0))
			return ret;
	}

	if (func->bind &&
	    ((func->needs_backup && list_empty(&res->mob_head) &&
	      val_buf->bo != NULL) ||
	     (!func->needs_backup && val_buf->bo != NULL))) {
		ret = func->bind(res, val_buf);
		if (unlikely(ret != 0))
			goto out_bind_failed;
		if (func->needs_backup)
			list_add_tail(&res->mob_head, &res->backup->res_list);
	}

	/*
	 * Only do this on write operations, and move to
	 * vmw_resource_unreserve if it can be called after
	 * backup buffers have been unreserved. Otherwise
	 * sort out locking.
	 */
	res->res_dirty = true;

	return 0;

out_bind_failed:
	func->destroy(res);

	return ret;
}

/**
 * vmw_resource_unreserve - Unreserve a resource previously reserved for
 * command submission.
 *
 * @res:               Pointer to the struct vmw_resource to unreserve.
914
 * @switch_backup:     Backup buffer has been switched.
915
 * @new_backup:        Pointer to new backup buffer if command submission
916 917
 *                     switched. May be NULL.
 * @new_backup_offset: New backup offset if @switch_backup is true.
918 919 920 921 922
 *
 * Currently unreserving a resource means putting it back on the device's
 * resource lru list, so that it can be evicted if necessary.
 */
void vmw_resource_unreserve(struct vmw_resource *res,
923
			    bool switch_backup,
924
			    struct vmw_buffer_object *new_backup,
925 926 927 928 929 930 931
			    unsigned long new_backup_offset)
{
	struct vmw_private *dev_priv = res->dev_priv;

	if (!list_empty(&res->lru_head))
		return;

932
	if (switch_backup && new_backup != res->backup) {
933
		if (res->backup) {
934
			lockdep_assert_held(&res->backup->base.resv->lock.base);
935
			list_del_init(&res->mob_head);
936
			vmw_bo_unreference(&res->backup);
937 938
		}

939
		if (new_backup) {
940
			res->backup = vmw_bo_reference(new_backup);
941 942 943 944 945
			lockdep_assert_held(&new_backup->base.resv->lock.base);
			list_add_tail(&res->mob_head, &new_backup->res_list);
		} else {
			res->backup = NULL;
		}
946
	}
947
	if (switch_backup)
948 949
		res->backup_offset = new_backup_offset;

950
	if (!res->func->may_evict || res->id == -1 || res->pin_count)
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
		return;

	write_lock(&dev_priv->resource_lock);
	list_add_tail(&res->lru_head,
		      &res->dev_priv->res_lru[res->func->res_type]);
	write_unlock(&dev_priv->resource_lock);
}

/**
 * vmw_resource_check_buffer - Check whether a backup buffer is needed
 *                             for a resource and in that case, allocate
 *                             one, reserve and validate it.
 *
 * @res:            The resource for which to allocate a backup buffer.
 * @interruptible:  Whether any sleeps during allocation should be
 *                  performed while interruptible.
 * @val_buf:        On successful return contains data about the
 *                  reserved and validated backup buffer.
 */
970 971 972 973
static int
vmw_resource_check_buffer(struct vmw_resource *res,
			  bool interruptible,
			  struct ttm_validate_buffer *val_buf)
974
{
975
	struct ttm_operation_ctx ctx = { true, false };
976 977 978 979 980 981 982 983 984 985 986 987
	struct list_head val_list;
	bool backup_dirty = false;
	int ret;

	if (unlikely(res->backup == NULL)) {
		ret = vmw_resource_buf_alloc(res, interruptible);
		if (unlikely(ret != 0))
			return ret;
	}

	INIT_LIST_HEAD(&val_list);
	val_buf->bo = ttm_bo_reference(&res->backup->base);
988
	val_buf->shared = false;
989
	list_add_tail(&val_buf->head, &val_list);
990
	ret = ttm_eu_reserve_buffers(NULL, &val_list, interruptible, NULL);
991 992 993 994 995 996 997 998 999
	if (unlikely(ret != 0))
		goto out_no_reserve;

	if (res->func->needs_backup && list_empty(&res->mob_head))
		return 0;

	backup_dirty = res->backup_dirty;
	ret = ttm_bo_validate(&res->backup->base,
			      res->func->backup_placement,
1000
			      &ctx);
1001 1002 1003 1004 1005 1006 1007

	if (unlikely(ret != 0))
		goto out_no_validate;

	return 0;

out_no_validate:
1008
	ttm_eu_backoff_reservation(NULL, &val_list);
1009 1010 1011
out_no_reserve:
	ttm_bo_unref(&val_buf->bo);
	if (backup_dirty)
1012
		vmw_bo_unreference(&res->backup);
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026

	return ret;
}

/**
 * vmw_resource_reserve - Reserve a resource for command submission
 *
 * @res:            The resource to reserve.
 *
 * This function takes the resource off the LRU list and make sure
 * a backup buffer is present for guest-backed resources. However,
 * the buffer may not be bound to the resource at this point.
 *
 */
1027 1028
int vmw_resource_reserve(struct vmw_resource *res, bool interruptible,
			 bool no_backup)
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
{
	struct vmw_private *dev_priv = res->dev_priv;
	int ret;

	write_lock(&dev_priv->resource_lock);
	list_del_init(&res->lru_head);
	write_unlock(&dev_priv->resource_lock);

	if (res->func->needs_backup && res->backup == NULL &&
	    !no_backup) {
1039
		ret = vmw_resource_buf_alloc(res, interruptible);
1040 1041 1042 1043
		if (unlikely(ret != 0)) {
			DRM_ERROR("Failed to allocate a backup buffer "
				  "of size %lu. bytes\n",
				  (unsigned long) res->backup_size);
1044
			return ret;
1045
		}
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
	}

	return 0;
}

/**
 * vmw_resource_backoff_reservation - Unreserve and unreference a
 *                                    backup buffer
 *.
 * @val_buf:        Backup buffer information.
 */
1057
static void
1058
vmw_resource_backoff_reservation(struct ttm_validate_buffer *val_buf)
1059 1060 1061 1062 1063 1064 1065 1066
{
	struct list_head val_list;

	if (likely(val_buf->bo == NULL))
		return;

	INIT_LIST_HEAD(&val_list);
	list_add_tail(&val_buf->head, &val_list);
1067
	ttm_eu_backoff_reservation(NULL, &val_list);
1068 1069 1070 1071 1072 1073 1074 1075
	ttm_bo_unref(&val_buf->bo);
}

/**
 * vmw_resource_do_evict - Evict a resource, and transfer its data
 *                         to a backup buffer.
 *
 * @res:            The resource to evict.
1076
 * @interruptible:  Whether to wait interruptible.
1077
 */
1078
static int vmw_resource_do_evict(struct vmw_resource *res, bool interruptible)
1079 1080 1081 1082 1083 1084 1085 1086
{
	struct ttm_validate_buffer val_buf;
	const struct vmw_res_func *func = res->func;
	int ret;

	BUG_ON(!func->may_evict);

	val_buf.bo = NULL;
1087
	val_buf.shared = false;
1088
	ret = vmw_resource_check_buffer(res, interruptible, &val_buf);
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
	if (unlikely(ret != 0))
		return ret;

	if (unlikely(func->unbind != NULL &&
		     (!func->needs_backup || !list_empty(&res->mob_head)))) {
		ret = func->unbind(res, res->res_dirty, &val_buf);
		if (unlikely(ret != 0))
			goto out_no_unbind;
		list_del_init(&res->mob_head);
	}
	ret = func->destroy(res);
	res->backup_dirty = true;
	res->res_dirty = false;
out_no_unbind:
1103
	vmw_resource_backoff_reservation(&val_buf);
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126

	return ret;
}


/**
 * vmw_resource_validate - Make a resource up-to-date and visible
 *                         to the device.
 *
 * @res:            The resource to make visible to the device.
 *
 * On succesful return, any backup DMA buffer pointed to by @res->backup will
 * be reserved and validated.
 * On hardware resource shortage, this function will repeatedly evict
 * resources of the same type until the validation succeeds.
 */
int vmw_resource_validate(struct vmw_resource *res)
{
	int ret;
	struct vmw_resource *evict_res;
	struct vmw_private *dev_priv = res->dev_priv;
	struct list_head *lru_list = &dev_priv->res_lru[res->func->res_type];
	struct ttm_validate_buffer val_buf;
1127
	unsigned err_count = 0;
1128

1129
	if (!res->func->create)
1130 1131 1132
		return 0;

	val_buf.bo = NULL;
1133
	val_buf.shared = false;
1134 1135 1136 1137 1138 1139 1140 1141 1142
	if (res->backup)
		val_buf.bo = &res->backup->base;
	do {
		ret = vmw_resource_do_validate(res, &val_buf);
		if (likely(ret != -EBUSY))
			break;

		write_lock(&dev_priv->resource_lock);
		if (list_empty(lru_list) || !res->func->may_evict) {
1143
			DRM_ERROR("Out of device device resources "
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
				  "for %s.\n", res->func->type_name);
			ret = -EBUSY;
			write_unlock(&dev_priv->resource_lock);
			break;
		}

		evict_res = vmw_resource_reference
			(list_first_entry(lru_list, struct vmw_resource,
					  lru_head));
		list_del_init(&evict_res->lru_head);

		write_unlock(&dev_priv->resource_lock);
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168

		ret = vmw_resource_do_evict(evict_res, true);
		if (unlikely(ret != 0)) {
			write_lock(&dev_priv->resource_lock);
			list_add_tail(&evict_res->lru_head, lru_list);
			write_unlock(&dev_priv->resource_lock);
			if (ret == -ERESTARTSYS ||
			    ++err_count > VMW_RES_EVICT_ERR_COUNT) {
				vmw_resource_unreference(&evict_res);
				goto out_no_validate;
			}
		}

1169 1170 1171 1172 1173 1174 1175
		vmw_resource_unreference(&evict_res);
	} while (1);

	if (unlikely(ret != 0))
		goto out_no_validate;
	else if (!res->func->needs_backup && res->backup) {
		list_del_init(&res->mob_head);
1176
		vmw_bo_unreference(&res->backup);
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
	}

	return 0;

out_no_validate:
	return ret;
}

/**
 * vmw_fence_single_bo - Utility function to fence a single TTM buffer
 *                       object without unreserving it.
 *
 * @bo:             Pointer to the struct ttm_buffer_object to fence.
 * @fence:          Pointer to the fence. If NULL, this function will
 *                  insert a fence into the command stream..
 *
 * Contrary to the ttm_eu version of this function, it takes only
 * a single buffer object instead of a list, and it also doesn't
 * unreserve the buffer object, which needs to be done separately.
 */
void vmw_fence_single_bo(struct ttm_buffer_object *bo,
			 struct vmw_fence_obj *fence)
{
	struct ttm_bo_device *bdev = bo->bdev;
1201

1202 1203 1204
	struct vmw_private *dev_priv =
		container_of(bdev, struct vmw_private, bdev);

1205
	if (fence == NULL) {
1206
		vmw_execbuf_fence_commands(NULL, dev_priv, &fence, NULL);
1207
		reservation_object_add_excl_fence(bo->resv, &fence->base);
1208
		dma_fence_put(&fence->base);
1209
	} else
1210
		reservation_object_add_excl_fence(bo->resv, &fence->base);
1211 1212 1213 1214 1215
}

/**
 * vmw_resource_move_notify - TTM move_notify_callback
 *
1216 1217 1218
 * @bo: The TTM buffer object about to move.
 * @mem: The struct ttm_mem_reg indicating to what memory
 *       region the move is taking place.
1219
 *
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
 * Evicts the Guest Backed hardware resource if the backup
 * buffer is being moved out of MOB memory.
 * Note that this function should not race with the resource
 * validation code as long as it accesses only members of struct
 * resource that remain static while bo::res is !NULL and
 * while we have @bo reserved. struct resource::backup is *not* a
 * static member. The resource validation code will take care
 * to set @bo::res to NULL, while having @bo reserved when the
 * buffer is no longer bound to the resource, so @bo:res can be
 * used to determine whether there is a need to unbind and whether
 * it is safe to unbind.
1231 1232 1233 1234
 */
void vmw_resource_move_notify(struct ttm_buffer_object *bo,
			      struct ttm_mem_reg *mem)
{
1235
	struct vmw_buffer_object *vbo;
1236 1237 1238 1239

	if (mem == NULL)
		return;

1240 1241
	if (bo->destroy != vmw_bo_bo_free &&
	    bo->destroy != vmw_user_bo_destroy)
1242 1243
		return;

1244
	vbo = container_of(bo, struct vmw_buffer_object, base);
1245

1246 1247 1248 1249
	/*
	 * Kill any cached kernel maps before move. An optimization could
	 * be to do this iff source or destination memory type is VRAM.
	 */
1250
	vmw_buffer_object_unmap(vbo);
1251

1252 1253 1254 1255 1256
	if (mem->mem_type != VMW_PL_MOB) {
		struct vmw_resource *res, *n;
		struct ttm_validate_buffer val_buf;

		val_buf.bo = bo;
1257
		val_buf.shared = false;
1258

1259
		list_for_each_entry_safe(res, n, &vbo->res_list, mob_head) {
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269

			if (unlikely(res->func->unbind == NULL))
				continue;

			(void) res->func->unbind(res, true, &val_buf);
			res->backup_dirty = true;
			res->res_dirty = false;
			list_del_init(&res->mob_head);
		}

1270
		(void) ttm_bo_wait(bo, false, false);
1271
	}
1272 1273
}

1274

1275 1276 1277 1278 1279 1280 1281
/**
 * vmw_resource_swap_notify - swapout notify callback.
 *
 * @bo: The buffer object to be swapped out.
 */
void vmw_resource_swap_notify(struct ttm_buffer_object *bo)
{
1282 1283
	if (bo->destroy != vmw_bo_bo_free &&
	    bo->destroy != vmw_user_bo_destroy)
1284 1285 1286
		return;

	/* Kill any cached kernel maps before swapout */
1287
	vmw_buffer_object_unmap(vmw_buffer_object(bo));
1288 1289
}

1290 1291 1292 1293 1294 1295 1296 1297 1298

/**
 * vmw_query_readback_all - Read back cached query states
 *
 * @dx_query_mob: Buffer containing the DX query MOB
 *
 * Read back cached states from the device if they exist.  This function
 * assumings binding_mutex is held.
 */
1299
int vmw_query_readback_all(struct vmw_buffer_object *dx_query_mob)
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
{
	struct vmw_resource *dx_query_ctx;
	struct vmw_private *dev_priv;
	struct {
		SVGA3dCmdHeader header;
		SVGA3dCmdDXReadbackAllQuery body;
	} *cmd;


	/* No query bound, so do nothing */
	if (!dx_query_mob || !dx_query_mob->dx_query_ctx)
		return 0;

	dx_query_ctx = dx_query_mob->dx_query_ctx;
	dev_priv     = dx_query_ctx->dev_priv;

	cmd = vmw_fifo_reserve_dx(dev_priv, sizeof(*cmd), dx_query_ctx->id);
	if (unlikely(cmd == NULL)) {
		DRM_ERROR("Failed reserving FIFO space for "
			  "query MOB read back.\n");
		return -ENOMEM;
	}

	cmd->header.id   = SVGA_3D_CMD_DX_READBACK_ALL_QUERY;
	cmd->header.size = sizeof(cmd->body);
	cmd->body.cid    = dx_query_ctx->id;

	vmw_fifo_commit(dev_priv, sizeof(*cmd));

	/* Triggers a rebind the next time affected context is bound */
	dx_query_mob->dx_query_ctx = NULL;

	return 0;
}



/**
 * vmw_query_move_notify - Read back cached query states
 *
 * @bo: The TTM buffer object about to move.
 * @mem: The memory region @bo is moving to.
 *
 * Called before the query MOB is swapped out to read back cached query
 * states from the device.
 */
void vmw_query_move_notify(struct ttm_buffer_object *bo,
			   struct ttm_mem_reg *mem)
{
1349
	struct vmw_buffer_object *dx_query_mob;
1350 1351 1352 1353 1354 1355 1356 1357
	struct ttm_bo_device *bdev = bo->bdev;
	struct vmw_private *dev_priv;


	dev_priv = container_of(bdev, struct vmw_private, bdev);

	mutex_lock(&dev_priv->binding_mutex);

1358
	dx_query_mob = container_of(bo, struct vmw_buffer_object, base);
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
	if (mem == NULL || !dx_query_mob || !dx_query_mob->dx_query_ctx) {
		mutex_unlock(&dev_priv->binding_mutex);
		return;
	}

	/* If BO is being moved from MOB to system memory */
	if (mem->mem_type == TTM_PL_SYSTEM && bo->mem.mem_type == VMW_PL_MOB) {
		struct vmw_fence_obj *fence;

		(void) vmw_query_readback_all(dx_query_mob);
		mutex_unlock(&dev_priv->binding_mutex);

		/* Create a fence and attach the BO to it */
		(void) vmw_execbuf_fence_commands(NULL, dev_priv, &fence, NULL);
		vmw_fence_single_bo(bo, fence);

		if (fence != NULL)
			vmw_fence_obj_unreference(&fence);

1378
		(void) ttm_bo_wait(bo, false, false);
1379 1380 1381 1382 1383
	} else
		mutex_unlock(&dev_priv->binding_mutex);

}

1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
/**
 * vmw_resource_needs_backup - Return whether a resource needs a backup buffer.
 *
 * @res:            The resource being queried.
 */
bool vmw_resource_needs_backup(const struct vmw_resource *res)
{
	return res->func->needs_backup;
}

/**
 * vmw_resource_evict_type - Evict all resources of a specific type
 *
 * @dev_priv:       Pointer to a device private struct
 * @type:           The resource type to evict
 *
 * To avoid thrashing starvation or as part of the hibernation sequence,
1401
 * try to evict all evictable resources of a specific type.
1402 1403 1404 1405 1406 1407
 */
static void vmw_resource_evict_type(struct vmw_private *dev_priv,
				    enum vmw_res_type type)
{
	struct list_head *lru_list = &dev_priv->res_lru[type];
	struct vmw_resource *evict_res;
1408 1409
	unsigned err_count = 0;
	int ret;
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421

	do {
		write_lock(&dev_priv->resource_lock);

		if (list_empty(lru_list))
			goto out_unlock;

		evict_res = vmw_resource_reference(
			list_first_entry(lru_list, struct vmw_resource,
					 lru_head));
		list_del_init(&evict_res->lru_head);
		write_unlock(&dev_priv->resource_lock);
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433

		ret = vmw_resource_do_evict(evict_res, false);
		if (unlikely(ret != 0)) {
			write_lock(&dev_priv->resource_lock);
			list_add_tail(&evict_res->lru_head, lru_list);
			write_unlock(&dev_priv->resource_lock);
			if (++err_count > VMW_RES_EVICT_ERR_COUNT) {
				vmw_resource_unreference(&evict_res);
				return;
			}
		}

1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
		vmw_resource_unreference(&evict_res);
	} while (1);

out_unlock:
	write_unlock(&dev_priv->resource_lock);
}

/**
 * vmw_resource_evict_all - Evict all evictable resources
 *
 * @dev_priv:       Pointer to a device private struct
 *
 * To avoid thrashing starvation or as part of the hibernation sequence,
 * evict all evictable resources. In particular this means that all
 * guest-backed resources that are registered with the device are
 * evicted and the OTable becomes clean.
 */
void vmw_resource_evict_all(struct vmw_private *dev_priv)
{
	enum vmw_res_type type;

	mutex_lock(&dev_priv->cmdbuf_mutex);

	for (type = 0; type < vmw_res_max; ++type)
		vmw_resource_evict_type(dev_priv, type);

	mutex_unlock(&dev_priv->cmdbuf_mutex);
}
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472

/**
 * vmw_resource_pin - Add a pin reference on a resource
 *
 * @res: The resource to add a pin reference on
 *
 * This function adds a pin reference, and if needed validates the resource.
 * Having a pin reference means that the resource can never be evicted, and
 * its id will never change as long as there is a pin reference.
 * This function returns 0 on success and a negative error code on failure.
 */
1473
int vmw_resource_pin(struct vmw_resource *res, bool interruptible)
1474
{
1475
	struct ttm_operation_ctx ctx = { interruptible, false };
1476 1477 1478
	struct vmw_private *dev_priv = res->dev_priv;
	int ret;

1479
	ttm_write_lock(&dev_priv->reservation_sem, interruptible);
1480
	mutex_lock(&dev_priv->cmdbuf_mutex);
1481
	ret = vmw_resource_reserve(res, interruptible, false);
1482 1483 1484 1485
	if (ret)
		goto out_no_reserve;

	if (res->pin_count == 0) {
1486
		struct vmw_buffer_object *vbo = NULL;
1487 1488

		if (res->backup) {
1489 1490
			vbo = res->backup;

1491
			ttm_bo_reserve(&vbo->base, interruptible, false, NULL);
1492 1493 1494 1495
			if (!vbo->pin_count) {
				ret = ttm_bo_validate
					(&vbo->base,
					 res->func->backup_placement,
1496
					 &ctx);
1497 1498 1499 1500
				if (ret) {
					ttm_bo_unreserve(&vbo->base);
					goto out_no_validate;
				}
1501 1502 1503
			}

			/* Do we really need to pin the MOB as well? */
1504
			vmw_bo_pin_reserved(vbo, true);
1505 1506
		}
		ret = vmw_resource_validate(res);
1507 1508
		if (vbo)
			ttm_bo_unreserve(&vbo->base);
1509 1510 1511 1512 1513 1514
		if (ret)
			goto out_no_validate;
	}
	res->pin_count++;

out_no_validate:
1515
	vmw_resource_unreserve(res, false, NULL, 0UL);
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535
out_no_reserve:
	mutex_unlock(&dev_priv->cmdbuf_mutex);
	ttm_write_unlock(&dev_priv->reservation_sem);

	return ret;
}

/**
 * vmw_resource_unpin - Remove a pin reference from a resource
 *
 * @res: The resource to remove a pin reference from
 *
 * Having a pin reference means that the resource can never be evicted, and
 * its id will never change as long as there is a pin reference.
 */
void vmw_resource_unpin(struct vmw_resource *res)
{
	struct vmw_private *dev_priv = res->dev_priv;
	int ret;

1536
	(void) ttm_read_lock(&dev_priv->reservation_sem, false);
1537 1538
	mutex_lock(&dev_priv->cmdbuf_mutex);

1539
	ret = vmw_resource_reserve(res, false, true);
1540 1541 1542 1543
	WARN_ON(ret);

	WARN_ON(res->pin_count == 0);
	if (--res->pin_count == 0 && res->backup) {
1544
		struct vmw_buffer_object *vbo = res->backup;
1545

1546
		(void) ttm_bo_reserve(&vbo->base, false, false, NULL);
1547 1548
		vmw_bo_pin_reserved(vbo, false);
		ttm_bo_unreserve(&vbo->base);
1549 1550
	}

1551
	vmw_resource_unreserve(res, false, NULL, 0UL);
1552 1553 1554 1555

	mutex_unlock(&dev_priv->cmdbuf_mutex);
	ttm_read_unlock(&dev_priv->reservation_sem);
}
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565

/**
 * vmw_res_type - Return the resource type
 *
 * @res: Pointer to the resource
 */
enum vmw_res_type vmw_res_type(const struct vmw_resource *res)
{
	return res->func->res_type;
}