1 // SPDX-License-Identifier: GPL-2.0 OR MIT
2 /**************************************************************************
3  *
4  * Copyright 2009-2015 VMware, Inc., Palo Alto, CA., USA
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the
8  * "Software"), to deal in the Software without restriction, including
9  * without limitation the rights to use, copy, modify, merge, publish,
10  * distribute, sub license, and/or sell copies of the Software, and to
11  * permit persons to whom the Software is furnished to do so, subject to
12  * the following conditions:
13  *
14  * The above copyright notice and this permission notice (including the
15  * next paragraph) shall be included in all copies or substantial portions
16  * of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20  * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
21  * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
22  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
23  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
24  * USE OR OTHER DEALINGS IN THE SOFTWARE.
25  *
26  **************************************************************************/
27 
28 #include <drm/ttm/ttm_placement.h>
29 
30 #include "vmwgfx_drv.h"
31 #include "vmwgfx_resource_priv.h"
32 #include "vmwgfx_so.h"
33 #include "vmwgfx_binding.h"
34 #include "vmw_surface_cache.h"
35 #include "device_include/svga3d_surfacedefs.h"
36 
37 #define SVGA3D_FLAGS_64(upper32, lower32) (((uint64_t)upper32 << 32) | lower32)
38 #define SVGA3D_FLAGS_UPPER_32(svga3d_flags) (svga3d_flags >> 32)
39 #define SVGA3D_FLAGS_LOWER_32(svga3d_flags) \
40 	(svga3d_flags & ((uint64_t)U32_MAX))
41 
42 /**
43  * struct vmw_user_surface - User-space visible surface resource
44  *
45  * @prime:          The TTM prime object.
46  * @base:           The TTM base object handling user-space visibility.
47  * @srf:            The surface metadata.
48  * @master:         Master of the creating client. Used for security check.
49  */
50 struct vmw_user_surface {
51 	struct ttm_prime_object prime;
52 	struct vmw_surface srf;
53 	struct drm_master *master;
54 };
55 
56 /**
57  * struct vmw_surface_offset - Backing store mip level offset info
58  *
59  * @face:           Surface face.
60  * @mip:            Mip level.
61  * @bo_offset:      Offset into backing store of this mip level.
62  *
63  */
64 struct vmw_surface_offset {
65 	uint32_t face;
66 	uint32_t mip;
67 	uint32_t bo_offset;
68 };
69 
70 /**
71  * struct vmw_surface_dirty - Surface dirty-tracker
72  * @cache: Cached layout information of the surface.
73  * @num_subres: Number of subresources.
74  * @boxes: Array of SVGA3dBoxes indicating dirty regions. One per subresource.
75  */
76 struct vmw_surface_dirty {
77 	struct vmw_surface_cache cache;
78 	u32 num_subres;
79 	SVGA3dBox boxes[];
80 };
81 
82 static void vmw_user_surface_free(struct vmw_resource *res);
83 static struct vmw_resource *
84 vmw_user_surface_base_to_res(struct ttm_base_object *base);
85 static int vmw_legacy_srf_bind(struct vmw_resource *res,
86 			       struct ttm_validate_buffer *val_buf);
87 static int vmw_legacy_srf_unbind(struct vmw_resource *res,
88 				 bool readback,
89 				 struct ttm_validate_buffer *val_buf);
90 static int vmw_legacy_srf_create(struct vmw_resource *res);
91 static int vmw_legacy_srf_destroy(struct vmw_resource *res);
92 static int vmw_gb_surface_create(struct vmw_resource *res);
93 static int vmw_gb_surface_bind(struct vmw_resource *res,
94 			       struct ttm_validate_buffer *val_buf);
95 static int vmw_gb_surface_unbind(struct vmw_resource *res,
96 				 bool readback,
97 				 struct ttm_validate_buffer *val_buf);
98 static int vmw_gb_surface_destroy(struct vmw_resource *res);
99 static int
100 vmw_gb_surface_define_internal(struct drm_device *dev,
101 			       struct drm_vmw_gb_surface_create_ext_req *req,
102 			       struct drm_vmw_gb_surface_create_rep *rep,
103 			       struct drm_file *file_priv);
104 static int
105 vmw_gb_surface_reference_internal(struct drm_device *dev,
106 				  struct drm_vmw_surface_arg *req,
107 				  struct drm_vmw_gb_surface_ref_ext_rep *rep,
108 				  struct drm_file *file_priv);
109 
110 static void vmw_surface_dirty_free(struct vmw_resource *res);
111 static int vmw_surface_dirty_alloc(struct vmw_resource *res);
112 static int vmw_surface_dirty_sync(struct vmw_resource *res);
113 static void vmw_surface_dirty_range_add(struct vmw_resource *res, size_t start,
114 					size_t end);
115 static int vmw_surface_clean(struct vmw_resource *res);
116 
117 static const struct vmw_user_resource_conv user_surface_conv = {
118 	.object_type = VMW_RES_SURFACE,
119 	.base_obj_to_res = vmw_user_surface_base_to_res,
120 	.res_free = vmw_user_surface_free
121 };
122 
123 const struct vmw_user_resource_conv *user_surface_converter =
124 	&user_surface_conv;
125 
126 static const struct vmw_res_func vmw_legacy_surface_func = {
127 	.res_type = vmw_res_surface,
128 	.needs_backup = false,
129 	.may_evict = true,
130 	.prio = 1,
131 	.dirty_prio = 1,
132 	.type_name = "legacy surfaces",
133 	.backup_placement = &vmw_srf_placement,
134 	.create = &vmw_legacy_srf_create,
135 	.destroy = &vmw_legacy_srf_destroy,
136 	.bind = &vmw_legacy_srf_bind,
137 	.unbind = &vmw_legacy_srf_unbind
138 };
139 
140 static const struct vmw_res_func vmw_gb_surface_func = {
141 	.res_type = vmw_res_surface,
142 	.needs_backup = true,
143 	.may_evict = true,
144 	.prio = 1,
145 	.dirty_prio = 2,
146 	.type_name = "guest backed surfaces",
147 	.backup_placement = &vmw_mob_placement,
148 	.create = vmw_gb_surface_create,
149 	.destroy = vmw_gb_surface_destroy,
150 	.bind = vmw_gb_surface_bind,
151 	.unbind = vmw_gb_surface_unbind,
152 	.dirty_alloc = vmw_surface_dirty_alloc,
153 	.dirty_free = vmw_surface_dirty_free,
154 	.dirty_sync = vmw_surface_dirty_sync,
155 	.dirty_range_add = vmw_surface_dirty_range_add,
156 	.clean = vmw_surface_clean,
157 };
158 
159 /*
160  * struct vmw_surface_dma - SVGA3D DMA command
161  */
162 struct vmw_surface_dma {
163 	SVGA3dCmdHeader header;
164 	SVGA3dCmdSurfaceDMA body;
165 	SVGA3dCopyBox cb;
166 	SVGA3dCmdSurfaceDMASuffix suffix;
167 };
168 
169 /*
170  * struct vmw_surface_define - SVGA3D Surface Define command
171  */
172 struct vmw_surface_define {
173 	SVGA3dCmdHeader header;
174 	SVGA3dCmdDefineSurface body;
175 };
176 
177 /*
178  * struct vmw_surface_destroy - SVGA3D Surface Destroy command
179  */
180 struct vmw_surface_destroy {
181 	SVGA3dCmdHeader header;
182 	SVGA3dCmdDestroySurface body;
183 };
184 
185 
186 /**
187  * vmw_surface_dma_size - Compute fifo size for a dma command.
188  *
189  * @srf: Pointer to a struct vmw_surface
190  *
191  * Computes the required size for a surface dma command for backup or
192  * restoration of the surface represented by @srf.
193  */
194 static inline uint32_t vmw_surface_dma_size(const struct vmw_surface *srf)
195 {
196 	return srf->metadata.num_sizes * sizeof(struct vmw_surface_dma);
197 }
198 
199 
200 /**
201  * vmw_surface_define_size - Compute fifo size for a surface define command.
202  *
203  * @srf: Pointer to a struct vmw_surface
204  *
205  * Computes the required size for a surface define command for the definition
206  * of the surface represented by @srf.
207  */
208 static inline uint32_t vmw_surface_define_size(const struct vmw_surface *srf)
209 {
210 	return sizeof(struct vmw_surface_define) + srf->metadata.num_sizes *
211 		sizeof(SVGA3dSize);
212 }
213 
214 
215 /**
216  * vmw_surface_destroy_size - Compute fifo size for a surface destroy command.
217  *
218  * Computes the required size for a surface destroy command for the destruction
219  * of a hw surface.
220  */
221 static inline uint32_t vmw_surface_destroy_size(void)
222 {
223 	return sizeof(struct vmw_surface_destroy);
224 }
225 
226 /**
227  * vmw_surface_destroy_encode - Encode a surface_destroy command.
228  *
229  * @id: The surface id
230  * @cmd_space: Pointer to memory area in which the commands should be encoded.
231  */
232 static void vmw_surface_destroy_encode(uint32_t id,
233 				       void *cmd_space)
234 {
235 	struct vmw_surface_destroy *cmd = (struct vmw_surface_destroy *)
236 		cmd_space;
237 
238 	cmd->header.id = SVGA_3D_CMD_SURFACE_DESTROY;
239 	cmd->header.size = sizeof(cmd->body);
240 	cmd->body.sid = id;
241 }
242 
243 /**
244  * vmw_surface_define_encode - Encode a surface_define command.
245  *
246  * @srf: Pointer to a struct vmw_surface object.
247  * @cmd_space: Pointer to memory area in which the commands should be encoded.
248  */
249 static void vmw_surface_define_encode(const struct vmw_surface *srf,
250 				      void *cmd_space)
251 {
252 	struct vmw_surface_define *cmd = (struct vmw_surface_define *)
253 		cmd_space;
254 	struct drm_vmw_size *src_size;
255 	SVGA3dSize *cmd_size;
256 	uint32_t cmd_len;
257 	int i;
258 
259 	cmd_len = sizeof(cmd->body) + srf->metadata.num_sizes *
260 		sizeof(SVGA3dSize);
261 
262 	cmd->header.id = SVGA_3D_CMD_SURFACE_DEFINE;
263 	cmd->header.size = cmd_len;
264 	cmd->body.sid = srf->res.id;
265 	/*
266 	 * Downcast of surfaceFlags, was upcasted when received from user-space,
267 	 * since driver internally stores as 64 bit.
268 	 * For legacy surface define only 32 bit flag is supported.
269 	 */
270 	cmd->body.surfaceFlags = (SVGA3dSurface1Flags)srf->metadata.flags;
271 	cmd->body.format = srf->metadata.format;
272 	for (i = 0; i < DRM_VMW_MAX_SURFACE_FACES; ++i)
273 		cmd->body.face[i].numMipLevels = srf->metadata.mip_levels[i];
274 
275 	cmd += 1;
276 	cmd_size = (SVGA3dSize *) cmd;
277 	src_size = srf->metadata.sizes;
278 
279 	for (i = 0; i < srf->metadata.num_sizes; ++i, cmd_size++, src_size++) {
280 		cmd_size->width = src_size->width;
281 		cmd_size->height = src_size->height;
282 		cmd_size->depth = src_size->depth;
283 	}
284 }
285 
286 /**
287  * vmw_surface_dma_encode - Encode a surface_dma command.
288  *
289  * @srf: Pointer to a struct vmw_surface object.
290  * @cmd_space: Pointer to memory area in which the commands should be encoded.
291  * @ptr: Pointer to an SVGAGuestPtr indicating where the surface contents
292  * should be placed or read from.
293  * @to_surface: Boolean whether to DMA to the surface or from the surface.
294  */
295 static void vmw_surface_dma_encode(struct vmw_surface *srf,
296 				   void *cmd_space,
297 				   const SVGAGuestPtr *ptr,
298 				   bool to_surface)
299 {
300 	uint32_t i;
301 	struct vmw_surface_dma *cmd = (struct vmw_surface_dma *)cmd_space;
302 	const struct SVGA3dSurfaceDesc *desc =
303 		vmw_surface_get_desc(srf->metadata.format);
304 
305 	for (i = 0; i < srf->metadata.num_sizes; ++i) {
306 		SVGA3dCmdHeader *header = &cmd->header;
307 		SVGA3dCmdSurfaceDMA *body = &cmd->body;
308 		SVGA3dCopyBox *cb = &cmd->cb;
309 		SVGA3dCmdSurfaceDMASuffix *suffix = &cmd->suffix;
310 		const struct vmw_surface_offset *cur_offset = &srf->offsets[i];
311 		const struct drm_vmw_size *cur_size = &srf->metadata.sizes[i];
312 
313 		header->id = SVGA_3D_CMD_SURFACE_DMA;
314 		header->size = sizeof(*body) + sizeof(*cb) + sizeof(*suffix);
315 
316 		body->guest.ptr = *ptr;
317 		body->guest.ptr.offset += cur_offset->bo_offset;
318 		body->guest.pitch = vmw_surface_calculate_pitch(desc, cur_size);
319 		body->host.sid = srf->res.id;
320 		body->host.face = cur_offset->face;
321 		body->host.mipmap = cur_offset->mip;
322 		body->transfer = ((to_surface) ?  SVGA3D_WRITE_HOST_VRAM :
323 				  SVGA3D_READ_HOST_VRAM);
324 		cb->x = 0;
325 		cb->y = 0;
326 		cb->z = 0;
327 		cb->srcx = 0;
328 		cb->srcy = 0;
329 		cb->srcz = 0;
330 		cb->w = cur_size->width;
331 		cb->h = cur_size->height;
332 		cb->d = cur_size->depth;
333 
334 		suffix->suffixSize = sizeof(*suffix);
335 		suffix->maximumOffset =
336 			vmw_surface_get_image_buffer_size(desc, cur_size,
337 							    body->guest.pitch);
338 		suffix->flags.discard = 0;
339 		suffix->flags.unsynchronized = 0;
340 		suffix->flags.reserved = 0;
341 		++cmd;
342 	}
343 };
344 
345 
346 /**
347  * vmw_hw_surface_destroy - destroy a Device surface
348  *
349  * @res:        Pointer to a struct vmw_resource embedded in a struct
350  *              vmw_surface.
351  *
352  * Destroys a the device surface associated with a struct vmw_surface if
353  * any, and adjusts resource count accordingly.
354  */
355 static void vmw_hw_surface_destroy(struct vmw_resource *res)
356 {
357 
358 	struct vmw_private *dev_priv = res->dev_priv;
359 	void *cmd;
360 
361 	if (res->func->destroy == vmw_gb_surface_destroy) {
362 		(void) vmw_gb_surface_destroy(res);
363 		return;
364 	}
365 
366 	if (res->id != -1) {
367 
368 		cmd = VMW_CMD_RESERVE(dev_priv, vmw_surface_destroy_size());
369 		if (unlikely(!cmd))
370 			return;
371 
372 		vmw_surface_destroy_encode(res->id, cmd);
373 		vmw_cmd_commit(dev_priv, vmw_surface_destroy_size());
374 
375 		/*
376 		 * used_memory_size_atomic, or separate lock
377 		 * to avoid taking dev_priv::cmdbuf_mutex in
378 		 * the destroy path.
379 		 */
380 
381 		mutex_lock(&dev_priv->cmdbuf_mutex);
382 		dev_priv->used_memory_size -= res->backup_size;
383 		mutex_unlock(&dev_priv->cmdbuf_mutex);
384 	}
385 }
386 
387 /**
388  * vmw_legacy_srf_create - Create a device surface as part of the
389  * resource validation process.
390  *
391  * @res: Pointer to a struct vmw_surface.
392  *
393  * If the surface doesn't have a hw id.
394  *
395  * Returns -EBUSY if there wasn't sufficient device resources to
396  * complete the validation. Retry after freeing up resources.
397  *
398  * May return other errors if the kernel is out of guest resources.
399  */
400 static int vmw_legacy_srf_create(struct vmw_resource *res)
401 {
402 	struct vmw_private *dev_priv = res->dev_priv;
403 	struct vmw_surface *srf;
404 	uint32_t submit_size;
405 	uint8_t *cmd;
406 	int ret;
407 
408 	if (likely(res->id != -1))
409 		return 0;
410 
411 	srf = vmw_res_to_srf(res);
412 	if (unlikely(dev_priv->used_memory_size + res->backup_size >=
413 		     dev_priv->memory_size))
414 		return -EBUSY;
415 
416 	/*
417 	 * Alloc id for the resource.
418 	 */
419 
420 	ret = vmw_resource_alloc_id(res);
421 	if (unlikely(ret != 0)) {
422 		DRM_ERROR("Failed to allocate a surface id.\n");
423 		goto out_no_id;
424 	}
425 
426 	if (unlikely(res->id >= SVGA3D_HB_MAX_SURFACE_IDS)) {
427 		ret = -EBUSY;
428 		goto out_no_fifo;
429 	}
430 
431 	/*
432 	 * Encode surface define- commands.
433 	 */
434 
435 	submit_size = vmw_surface_define_size(srf);
436 	cmd = VMW_CMD_RESERVE(dev_priv, submit_size);
437 	if (unlikely(!cmd)) {
438 		ret = -ENOMEM;
439 		goto out_no_fifo;
440 	}
441 
442 	vmw_surface_define_encode(srf, cmd);
443 	vmw_cmd_commit(dev_priv, submit_size);
444 	vmw_fifo_resource_inc(dev_priv);
445 
446 	/*
447 	 * Surface memory usage accounting.
448 	 */
449 
450 	dev_priv->used_memory_size += res->backup_size;
451 	return 0;
452 
453 out_no_fifo:
454 	vmw_resource_release_id(res);
455 out_no_id:
456 	return ret;
457 }
458 
459 /**
460  * vmw_legacy_srf_dma - Copy backup data to or from a legacy surface.
461  *
462  * @res:            Pointer to a struct vmw_res embedded in a struct
463  *                  vmw_surface.
464  * @val_buf:        Pointer to a struct ttm_validate_buffer containing
465  *                  information about the backup buffer.
466  * @bind:           Boolean wether to DMA to the surface.
467  *
468  * Transfer backup data to or from a legacy surface as part of the
469  * validation process.
470  * May return other errors if the kernel is out of guest resources.
471  * The backup buffer will be fenced or idle upon successful completion,
472  * and if the surface needs persistent backup storage, the backup buffer
473  * will also be returned reserved iff @bind is true.
474  */
475 static int vmw_legacy_srf_dma(struct vmw_resource *res,
476 			      struct ttm_validate_buffer *val_buf,
477 			      bool bind)
478 {
479 	SVGAGuestPtr ptr;
480 	struct vmw_fence_obj *fence;
481 	uint32_t submit_size;
482 	struct vmw_surface *srf = vmw_res_to_srf(res);
483 	uint8_t *cmd;
484 	struct vmw_private *dev_priv = res->dev_priv;
485 
486 	BUG_ON(!val_buf->bo);
487 	submit_size = vmw_surface_dma_size(srf);
488 	cmd = VMW_CMD_RESERVE(dev_priv, submit_size);
489 	if (unlikely(!cmd))
490 		return -ENOMEM;
491 
492 	vmw_bo_get_guest_ptr(val_buf->bo, &ptr);
493 	vmw_surface_dma_encode(srf, cmd, &ptr, bind);
494 
495 	vmw_cmd_commit(dev_priv, submit_size);
496 
497 	/*
498 	 * Create a fence object and fence the backup buffer.
499 	 */
500 
501 	(void) vmw_execbuf_fence_commands(NULL, dev_priv,
502 					  &fence, NULL);
503 
504 	vmw_bo_fence_single(val_buf->bo, fence);
505 
506 	if (likely(fence != NULL))
507 		vmw_fence_obj_unreference(&fence);
508 
509 	return 0;
510 }
511 
512 /**
513  * vmw_legacy_srf_bind - Perform a legacy surface bind as part of the
514  *                       surface validation process.
515  *
516  * @res:            Pointer to a struct vmw_res embedded in a struct
517  *                  vmw_surface.
518  * @val_buf:        Pointer to a struct ttm_validate_buffer containing
519  *                  information about the backup buffer.
520  *
521  * This function will copy backup data to the surface if the
522  * backup buffer is dirty.
523  */
524 static int vmw_legacy_srf_bind(struct vmw_resource *res,
525 			       struct ttm_validate_buffer *val_buf)
526 {
527 	if (!res->backup_dirty)
528 		return 0;
529 
530 	return vmw_legacy_srf_dma(res, val_buf, true);
531 }
532 
533 
534 /**
535  * vmw_legacy_srf_unbind - Perform a legacy surface unbind as part of the
536  *                         surface eviction process.
537  *
538  * @res:            Pointer to a struct vmw_res embedded in a struct
539  *                  vmw_surface.
540  * @readback:       Readback - only true if dirty
541  * @val_buf:        Pointer to a struct ttm_validate_buffer containing
542  *                  information about the backup buffer.
543  *
544  * This function will copy backup data from the surface.
545  */
546 static int vmw_legacy_srf_unbind(struct vmw_resource *res,
547 				 bool readback,
548 				 struct ttm_validate_buffer *val_buf)
549 {
550 	if (unlikely(readback))
551 		return vmw_legacy_srf_dma(res, val_buf, false);
552 	return 0;
553 }
554 
555 /**
556  * vmw_legacy_srf_destroy - Destroy a device surface as part of a
557  *                          resource eviction process.
558  *
559  * @res:            Pointer to a struct vmw_res embedded in a struct
560  *                  vmw_surface.
561  */
562 static int vmw_legacy_srf_destroy(struct vmw_resource *res)
563 {
564 	struct vmw_private *dev_priv = res->dev_priv;
565 	uint32_t submit_size;
566 	uint8_t *cmd;
567 
568 	BUG_ON(res->id == -1);
569 
570 	/*
571 	 * Encode the dma- and surface destroy commands.
572 	 */
573 
574 	submit_size = vmw_surface_destroy_size();
575 	cmd = VMW_CMD_RESERVE(dev_priv, submit_size);
576 	if (unlikely(!cmd))
577 		return -ENOMEM;
578 
579 	vmw_surface_destroy_encode(res->id, cmd);
580 	vmw_cmd_commit(dev_priv, submit_size);
581 
582 	/*
583 	 * Surface memory usage accounting.
584 	 */
585 
586 	dev_priv->used_memory_size -= res->backup_size;
587 
588 	/*
589 	 * Release the surface ID.
590 	 */
591 
592 	vmw_resource_release_id(res);
593 	vmw_fifo_resource_dec(dev_priv);
594 
595 	return 0;
596 }
597 
598 
599 /**
600  * vmw_surface_init - initialize a struct vmw_surface
601  *
602  * @dev_priv:       Pointer to a device private struct.
603  * @srf:            Pointer to the struct vmw_surface to initialize.
604  * @res_free:       Pointer to a resource destructor used to free
605  *                  the object.
606  */
607 static int vmw_surface_init(struct vmw_private *dev_priv,
608 			    struct vmw_surface *srf,
609 			    void (*res_free) (struct vmw_resource *res))
610 {
611 	int ret;
612 	struct vmw_resource *res = &srf->res;
613 
614 	BUG_ON(!res_free);
615 	ret = vmw_resource_init(dev_priv, res, true, res_free,
616 				(dev_priv->has_mob) ? &vmw_gb_surface_func :
617 				&vmw_legacy_surface_func);
618 
619 	if (unlikely(ret != 0)) {
620 		res_free(res);
621 		return ret;
622 	}
623 
624 	/*
625 	 * The surface won't be visible to hardware until a
626 	 * surface validate.
627 	 */
628 
629 	INIT_LIST_HEAD(&srf->view_list);
630 	res->hw_destroy = vmw_hw_surface_destroy;
631 	return ret;
632 }
633 
634 /**
635  * vmw_user_surface_base_to_res - TTM base object to resource converter for
636  *                                user visible surfaces
637  *
638  * @base:           Pointer to a TTM base object
639  *
640  * Returns the struct vmw_resource embedded in a struct vmw_surface
641  * for the user-visible object identified by the TTM base object @base.
642  */
643 static struct vmw_resource *
644 vmw_user_surface_base_to_res(struct ttm_base_object *base)
645 {
646 	return &(container_of(base, struct vmw_user_surface,
647 			      prime.base)->srf.res);
648 }
649 
650 /**
651  * vmw_user_surface_free - User visible surface resource destructor
652  *
653  * @res:            A struct vmw_resource embedded in a struct vmw_surface.
654  */
655 static void vmw_user_surface_free(struct vmw_resource *res)
656 {
657 	struct vmw_surface *srf = vmw_res_to_srf(res);
658 	struct vmw_user_surface *user_srf =
659 	    container_of(srf, struct vmw_user_surface, srf);
660 
661 	WARN_ON_ONCE(res->dirty);
662 	if (user_srf->master)
663 		drm_master_put(&user_srf->master);
664 	kfree(srf->offsets);
665 	kfree(srf->metadata.sizes);
666 	kfree(srf->snooper.image);
667 	ttm_prime_object_kfree(user_srf, prime);
668 }
669 
670 /**
671  * vmw_user_surface_base_release - User visible surface TTM base object destructor
672  *
673  * @p_base:         Pointer to a pointer to a TTM base object
674  *                  embedded in a struct vmw_user_surface.
675  *
676  * Drops the base object's reference on its resource, and the
677  * pointer pointed to by *p_base is set to NULL.
678  */
679 static void vmw_user_surface_base_release(struct ttm_base_object **p_base)
680 {
681 	struct ttm_base_object *base = *p_base;
682 	struct vmw_user_surface *user_srf =
683 	    container_of(base, struct vmw_user_surface, prime.base);
684 	struct vmw_resource *res = &user_srf->srf.res;
685 
686 	*p_base = NULL;
687 	vmw_resource_unreference(&res);
688 }
689 
690 /**
691  * vmw_surface_destroy_ioctl - Ioctl function implementing
692  *                                  the user surface destroy functionality.
693  *
694  * @dev:            Pointer to a struct drm_device.
695  * @data:           Pointer to data copied from / to user-space.
696  * @file_priv:      Pointer to a drm file private structure.
697  */
698 int vmw_surface_destroy_ioctl(struct drm_device *dev, void *data,
699 			      struct drm_file *file_priv)
700 {
701 	struct drm_vmw_surface_arg *arg = (struct drm_vmw_surface_arg *)data;
702 	struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile;
703 
704 	return ttm_ref_object_base_unref(tfile, arg->sid);
705 }
706 
707 /**
708  * vmw_surface_define_ioctl - Ioctl function implementing
709  *                                  the user surface define functionality.
710  *
711  * @dev:            Pointer to a struct drm_device.
712  * @data:           Pointer to data copied from / to user-space.
713  * @file_priv:      Pointer to a drm file private structure.
714  */
715 int vmw_surface_define_ioctl(struct drm_device *dev, void *data,
716 			     struct drm_file *file_priv)
717 {
718 	struct vmw_private *dev_priv = vmw_priv(dev);
719 	struct vmw_user_surface *user_srf;
720 	struct vmw_surface *srf;
721 	struct vmw_surface_metadata *metadata;
722 	struct vmw_resource *res;
723 	struct vmw_resource *tmp;
724 	union drm_vmw_surface_create_arg *arg =
725 	    (union drm_vmw_surface_create_arg *)data;
726 	struct drm_vmw_surface_create_req *req = &arg->req;
727 	struct drm_vmw_surface_arg *rep = &arg->rep;
728 	struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile;
729 	int ret;
730 	int i, j;
731 	uint32_t cur_bo_offset;
732 	struct drm_vmw_size *cur_size;
733 	struct vmw_surface_offset *cur_offset;
734 	uint32_t num_sizes;
735 	const SVGA3dSurfaceDesc *desc;
736 
737 	num_sizes = 0;
738 	for (i = 0; i < DRM_VMW_MAX_SURFACE_FACES; ++i) {
739 		if (req->mip_levels[i] > DRM_VMW_MAX_MIP_LEVELS)
740 			return -EINVAL;
741 		num_sizes += req->mip_levels[i];
742 	}
743 
744 	if (num_sizes > DRM_VMW_MAX_SURFACE_FACES * DRM_VMW_MAX_MIP_LEVELS ||
745 	    num_sizes == 0)
746 		return -EINVAL;
747 
748 	desc = vmw_surface_get_desc(req->format);
749 	if (unlikely(desc->blockDesc == SVGA3DBLOCKDESC_NONE)) {
750 		VMW_DEBUG_USER("Invalid format %d for surface creation.\n",
751 			       req->format);
752 		return -EINVAL;
753 	}
754 
755 	user_srf = kzalloc(sizeof(*user_srf), GFP_KERNEL);
756 	if (unlikely(!user_srf)) {
757 		ret = -ENOMEM;
758 		goto out_unlock;
759 	}
760 
761 	srf = &user_srf->srf;
762 	metadata = &srf->metadata;
763 	res = &srf->res;
764 
765 	/* Driver internally stores as 64-bit flags */
766 	metadata->flags = (SVGA3dSurfaceAllFlags)req->flags;
767 	metadata->format = req->format;
768 	metadata->scanout = req->scanout;
769 
770 	memcpy(metadata->mip_levels, req->mip_levels,
771 	       sizeof(metadata->mip_levels));
772 	metadata->num_sizes = num_sizes;
773 	metadata->sizes =
774 		memdup_user((struct drm_vmw_size __user *)(unsigned long)
775 			    req->size_addr,
776 			    sizeof(*metadata->sizes) * metadata->num_sizes);
777 	if (IS_ERR(metadata->sizes)) {
778 		ret = PTR_ERR(metadata->sizes);
779 		goto out_no_sizes;
780 	}
781 	srf->offsets = kmalloc_array(metadata->num_sizes, sizeof(*srf->offsets),
782 				     GFP_KERNEL);
783 	if (unlikely(!srf->offsets)) {
784 		ret = -ENOMEM;
785 		goto out_no_offsets;
786 	}
787 
788 	metadata->base_size = *srf->metadata.sizes;
789 	metadata->autogen_filter = SVGA3D_TEX_FILTER_NONE;
790 	metadata->multisample_count = 0;
791 	metadata->multisample_pattern = SVGA3D_MS_PATTERN_NONE;
792 	metadata->quality_level = SVGA3D_MS_QUALITY_NONE;
793 
794 	cur_bo_offset = 0;
795 	cur_offset = srf->offsets;
796 	cur_size = metadata->sizes;
797 
798 	for (i = 0; i < DRM_VMW_MAX_SURFACE_FACES; ++i) {
799 		for (j = 0; j < metadata->mip_levels[i]; ++j) {
800 			uint32_t stride = vmw_surface_calculate_pitch(
801 						  desc, cur_size);
802 
803 			cur_offset->face = i;
804 			cur_offset->mip = j;
805 			cur_offset->bo_offset = cur_bo_offset;
806 			cur_bo_offset += vmw_surface_get_image_buffer_size
807 				(desc, cur_size, stride);
808 			++cur_offset;
809 			++cur_size;
810 		}
811 	}
812 	res->backup_size = cur_bo_offset;
813 	if (metadata->scanout &&
814 	    metadata->num_sizes == 1 &&
815 	    metadata->sizes[0].width == 64 &&
816 	    metadata->sizes[0].height == 64 &&
817 	    metadata->format == SVGA3D_A8R8G8B8) {
818 
819 		srf->snooper.image = kzalloc(64 * 64 * 4, GFP_KERNEL);
820 		if (!srf->snooper.image) {
821 			DRM_ERROR("Failed to allocate cursor_image\n");
822 			ret = -ENOMEM;
823 			goto out_no_copy;
824 		}
825 	} else {
826 		srf->snooper.image = NULL;
827 	}
828 
829 	user_srf->prime.base.shareable = false;
830 	user_srf->prime.base.tfile = NULL;
831 	if (drm_is_primary_client(file_priv))
832 		user_srf->master = drm_file_get_master(file_priv);
833 
834 	/**
835 	 * From this point, the generic resource management functions
836 	 * destroy the object on failure.
837 	 */
838 
839 	ret = vmw_surface_init(dev_priv, srf, vmw_user_surface_free);
840 	if (unlikely(ret != 0))
841 		goto out_unlock;
842 
843 	/*
844 	 * A gb-aware client referencing a shared surface will
845 	 * expect a backup buffer to be present.
846 	 */
847 	if (dev_priv->has_mob && req->shareable) {
848 		uint32_t backup_handle;
849 
850 		ret = vmw_gem_object_create_with_handle(dev_priv,
851 							file_priv,
852 							res->backup_size,
853 							&backup_handle,
854 							&res->backup);
855 		if (unlikely(ret != 0)) {
856 			vmw_resource_unreference(&res);
857 			goto out_unlock;
858 		}
859 		vmw_bo_reference(res->backup);
860 	}
861 
862 	tmp = vmw_resource_reference(&srf->res);
863 	ret = ttm_prime_object_init(tfile, res->backup_size, &user_srf->prime,
864 				    req->shareable, VMW_RES_SURFACE,
865 				    &vmw_user_surface_base_release);
866 
867 	if (unlikely(ret != 0)) {
868 		vmw_resource_unreference(&tmp);
869 		vmw_resource_unreference(&res);
870 		goto out_unlock;
871 	}
872 
873 	rep->sid = user_srf->prime.base.handle;
874 	vmw_resource_unreference(&res);
875 
876 	return 0;
877 out_no_copy:
878 	kfree(srf->offsets);
879 out_no_offsets:
880 	kfree(metadata->sizes);
881 out_no_sizes:
882 	ttm_prime_object_kfree(user_srf, prime);
883 out_unlock:
884 	return ret;
885 }
886 
887 
888 static int
889 vmw_surface_handle_reference(struct vmw_private *dev_priv,
890 			     struct drm_file *file_priv,
891 			     uint32_t u_handle,
892 			     enum drm_vmw_handle_type handle_type,
893 			     struct ttm_base_object **base_p)
894 {
895 	struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile;
896 	struct vmw_user_surface *user_srf;
897 	uint32_t handle;
898 	struct ttm_base_object *base;
899 	int ret;
900 
901 	if (handle_type == DRM_VMW_HANDLE_PRIME) {
902 		ret = ttm_prime_fd_to_handle(tfile, u_handle, &handle);
903 		if (unlikely(ret != 0))
904 			return ret;
905 	} else {
906 		handle = u_handle;
907 	}
908 
909 	ret = -EINVAL;
910 	base = ttm_base_object_lookup_for_ref(dev_priv->tdev, handle);
911 	if (unlikely(!base)) {
912 		VMW_DEBUG_USER("Could not find surface to reference.\n");
913 		goto out_no_lookup;
914 	}
915 
916 	if (unlikely(ttm_base_object_type(base) != VMW_RES_SURFACE)) {
917 		VMW_DEBUG_USER("Referenced object is not a surface.\n");
918 		goto out_bad_resource;
919 	}
920 	if (handle_type != DRM_VMW_HANDLE_PRIME) {
921 		bool require_exist = false;
922 
923 		user_srf = container_of(base, struct vmw_user_surface,
924 					prime.base);
925 
926 		/* Error out if we are unauthenticated primary */
927 		if (drm_is_primary_client(file_priv) &&
928 		    !file_priv->authenticated) {
929 			ret = -EACCES;
930 			goto out_bad_resource;
931 		}
932 
933 		/*
934 		 * Make sure the surface creator has the same
935 		 * authenticating master, or is already registered with us.
936 		 */
937 		if (drm_is_primary_client(file_priv) &&
938 		    user_srf->master != file_priv->master)
939 			require_exist = true;
940 
941 		if (unlikely(drm_is_render_client(file_priv)))
942 			require_exist = true;
943 
944 		ret = ttm_ref_object_add(tfile, base, NULL, require_exist);
945 		if (unlikely(ret != 0)) {
946 			DRM_ERROR("Could not add a reference to a surface.\n");
947 			goto out_bad_resource;
948 		}
949 	}
950 
951 	*base_p = base;
952 	return 0;
953 
954 out_bad_resource:
955 	ttm_base_object_unref(&base);
956 out_no_lookup:
957 	if (handle_type == DRM_VMW_HANDLE_PRIME)
958 		(void) ttm_ref_object_base_unref(tfile, handle);
959 
960 	return ret;
961 }
962 
963 /**
964  * vmw_surface_reference_ioctl - Ioctl function implementing
965  *                                  the user surface reference functionality.
966  *
967  * @dev:            Pointer to a struct drm_device.
968  * @data:           Pointer to data copied from / to user-space.
969  * @file_priv:      Pointer to a drm file private structure.
970  */
971 int vmw_surface_reference_ioctl(struct drm_device *dev, void *data,
972 				struct drm_file *file_priv)
973 {
974 	struct vmw_private *dev_priv = vmw_priv(dev);
975 	union drm_vmw_surface_reference_arg *arg =
976 	    (union drm_vmw_surface_reference_arg *)data;
977 	struct drm_vmw_surface_arg *req = &arg->req;
978 	struct drm_vmw_surface_create_req *rep = &arg->rep;
979 	struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile;
980 	struct vmw_surface *srf;
981 	struct vmw_user_surface *user_srf;
982 	struct drm_vmw_size __user *user_sizes;
983 	struct ttm_base_object *base;
984 	int ret;
985 
986 	ret = vmw_surface_handle_reference(dev_priv, file_priv, req->sid,
987 					   req->handle_type, &base);
988 	if (unlikely(ret != 0))
989 		return ret;
990 
991 	user_srf = container_of(base, struct vmw_user_surface, prime.base);
992 	srf = &user_srf->srf;
993 
994 	/* Downcast of flags when sending back to user space */
995 	rep->flags = (uint32_t)srf->metadata.flags;
996 	rep->format = srf->metadata.format;
997 	memcpy(rep->mip_levels, srf->metadata.mip_levels,
998 	       sizeof(srf->metadata.mip_levels));
999 	user_sizes = (struct drm_vmw_size __user *)(unsigned long)
1000 	    rep->size_addr;
1001 
1002 	if (user_sizes)
1003 		ret = copy_to_user(user_sizes, &srf->metadata.base_size,
1004 				   sizeof(srf->metadata.base_size));
1005 	if (unlikely(ret != 0)) {
1006 		VMW_DEBUG_USER("copy_to_user failed %p %u\n", user_sizes,
1007 			       srf->metadata.num_sizes);
1008 		ttm_ref_object_base_unref(tfile, base->handle);
1009 		ret = -EFAULT;
1010 	}
1011 
1012 	ttm_base_object_unref(&base);
1013 
1014 	return ret;
1015 }
1016 
1017 /**
1018  * vmw_gb_surface_create - Encode a surface_define command.
1019  *
1020  * @res:        Pointer to a struct vmw_resource embedded in a struct
1021  *              vmw_surface.
1022  */
1023 static int vmw_gb_surface_create(struct vmw_resource *res)
1024 {
1025 	struct vmw_private *dev_priv = res->dev_priv;
1026 	struct vmw_surface *srf = vmw_res_to_srf(res);
1027 	struct vmw_surface_metadata *metadata = &srf->metadata;
1028 	uint32_t cmd_len, cmd_id, submit_len;
1029 	int ret;
1030 	struct {
1031 		SVGA3dCmdHeader header;
1032 		SVGA3dCmdDefineGBSurface body;
1033 	} *cmd;
1034 	struct {
1035 		SVGA3dCmdHeader header;
1036 		SVGA3dCmdDefineGBSurface_v2 body;
1037 	} *cmd2;
1038 	struct {
1039 		SVGA3dCmdHeader header;
1040 		SVGA3dCmdDefineGBSurface_v3 body;
1041 	} *cmd3;
1042 	struct {
1043 		SVGA3dCmdHeader header;
1044 		SVGA3dCmdDefineGBSurface_v4 body;
1045 	} *cmd4;
1046 
1047 	if (likely(res->id != -1))
1048 		return 0;
1049 
1050 	vmw_fifo_resource_inc(dev_priv);
1051 	ret = vmw_resource_alloc_id(res);
1052 	if (unlikely(ret != 0)) {
1053 		DRM_ERROR("Failed to allocate a surface id.\n");
1054 		goto out_no_id;
1055 	}
1056 
1057 	if (unlikely(res->id >= VMWGFX_NUM_GB_SURFACE)) {
1058 		ret = -EBUSY;
1059 		goto out_no_fifo;
1060 	}
1061 
1062 	if (has_sm5_context(dev_priv) && metadata->array_size > 0) {
1063 		cmd_id = SVGA_3D_CMD_DEFINE_GB_SURFACE_V4;
1064 		cmd_len = sizeof(cmd4->body);
1065 		submit_len = sizeof(*cmd4);
1066 	} else if (has_sm4_1_context(dev_priv) && metadata->array_size > 0) {
1067 		cmd_id = SVGA_3D_CMD_DEFINE_GB_SURFACE_V3;
1068 		cmd_len = sizeof(cmd3->body);
1069 		submit_len = sizeof(*cmd3);
1070 	} else if (metadata->array_size > 0) {
1071 		/* VMW_SM_4 support verified at creation time. */
1072 		cmd_id = SVGA_3D_CMD_DEFINE_GB_SURFACE_V2;
1073 		cmd_len = sizeof(cmd2->body);
1074 		submit_len = sizeof(*cmd2);
1075 	} else {
1076 		cmd_id = SVGA_3D_CMD_DEFINE_GB_SURFACE;
1077 		cmd_len = sizeof(cmd->body);
1078 		submit_len = sizeof(*cmd);
1079 	}
1080 
1081 	cmd = VMW_CMD_RESERVE(dev_priv, submit_len);
1082 	cmd2 = (typeof(cmd2))cmd;
1083 	cmd3 = (typeof(cmd3))cmd;
1084 	cmd4 = (typeof(cmd4))cmd;
1085 	if (unlikely(!cmd)) {
1086 		ret = -ENOMEM;
1087 		goto out_no_fifo;
1088 	}
1089 
1090 	if (has_sm5_context(dev_priv) && metadata->array_size > 0) {
1091 		cmd4->header.id = cmd_id;
1092 		cmd4->header.size = cmd_len;
1093 		cmd4->body.sid = srf->res.id;
1094 		cmd4->body.surfaceFlags = metadata->flags;
1095 		cmd4->body.format = metadata->format;
1096 		cmd4->body.numMipLevels = metadata->mip_levels[0];
1097 		cmd4->body.multisampleCount = metadata->multisample_count;
1098 		cmd4->body.multisamplePattern = metadata->multisample_pattern;
1099 		cmd4->body.qualityLevel = metadata->quality_level;
1100 		cmd4->body.autogenFilter = metadata->autogen_filter;
1101 		cmd4->body.size.width = metadata->base_size.width;
1102 		cmd4->body.size.height = metadata->base_size.height;
1103 		cmd4->body.size.depth = metadata->base_size.depth;
1104 		cmd4->body.arraySize = metadata->array_size;
1105 		cmd4->body.bufferByteStride = metadata->buffer_byte_stride;
1106 	} else if (has_sm4_1_context(dev_priv) && metadata->array_size > 0) {
1107 		cmd3->header.id = cmd_id;
1108 		cmd3->header.size = cmd_len;
1109 		cmd3->body.sid = srf->res.id;
1110 		cmd3->body.surfaceFlags = metadata->flags;
1111 		cmd3->body.format = metadata->format;
1112 		cmd3->body.numMipLevels = metadata->mip_levels[0];
1113 		cmd3->body.multisampleCount = metadata->multisample_count;
1114 		cmd3->body.multisamplePattern = metadata->multisample_pattern;
1115 		cmd3->body.qualityLevel = metadata->quality_level;
1116 		cmd3->body.autogenFilter = metadata->autogen_filter;
1117 		cmd3->body.size.width = metadata->base_size.width;
1118 		cmd3->body.size.height = metadata->base_size.height;
1119 		cmd3->body.size.depth = metadata->base_size.depth;
1120 		cmd3->body.arraySize = metadata->array_size;
1121 	} else if (metadata->array_size > 0) {
1122 		cmd2->header.id = cmd_id;
1123 		cmd2->header.size = cmd_len;
1124 		cmd2->body.sid = srf->res.id;
1125 		cmd2->body.surfaceFlags = metadata->flags;
1126 		cmd2->body.format = metadata->format;
1127 		cmd2->body.numMipLevels = metadata->mip_levels[0];
1128 		cmd2->body.multisampleCount = metadata->multisample_count;
1129 		cmd2->body.autogenFilter = metadata->autogen_filter;
1130 		cmd2->body.size.width = metadata->base_size.width;
1131 		cmd2->body.size.height = metadata->base_size.height;
1132 		cmd2->body.size.depth = metadata->base_size.depth;
1133 		cmd2->body.arraySize = metadata->array_size;
1134 	} else {
1135 		cmd->header.id = cmd_id;
1136 		cmd->header.size = cmd_len;
1137 		cmd->body.sid = srf->res.id;
1138 		cmd->body.surfaceFlags = metadata->flags;
1139 		cmd->body.format = metadata->format;
1140 		cmd->body.numMipLevels = metadata->mip_levels[0];
1141 		cmd->body.multisampleCount = metadata->multisample_count;
1142 		cmd->body.autogenFilter = metadata->autogen_filter;
1143 		cmd->body.size.width = metadata->base_size.width;
1144 		cmd->body.size.height = metadata->base_size.height;
1145 		cmd->body.size.depth = metadata->base_size.depth;
1146 	}
1147 
1148 	vmw_cmd_commit(dev_priv, submit_len);
1149 
1150 	return 0;
1151 
1152 out_no_fifo:
1153 	vmw_resource_release_id(res);
1154 out_no_id:
1155 	vmw_fifo_resource_dec(dev_priv);
1156 	return ret;
1157 }
1158 
1159 
1160 static int vmw_gb_surface_bind(struct vmw_resource *res,
1161 			       struct ttm_validate_buffer *val_buf)
1162 {
1163 	struct vmw_private *dev_priv = res->dev_priv;
1164 	struct {
1165 		SVGA3dCmdHeader header;
1166 		SVGA3dCmdBindGBSurface body;
1167 	} *cmd1;
1168 	struct {
1169 		SVGA3dCmdHeader header;
1170 		SVGA3dCmdUpdateGBSurface body;
1171 	} *cmd2;
1172 	uint32_t submit_size;
1173 	struct ttm_buffer_object *bo = val_buf->bo;
1174 
1175 	BUG_ON(bo->resource->mem_type != VMW_PL_MOB);
1176 
1177 	submit_size = sizeof(*cmd1) + (res->backup_dirty ? sizeof(*cmd2) : 0);
1178 
1179 	cmd1 = VMW_CMD_RESERVE(dev_priv, submit_size);
1180 	if (unlikely(!cmd1))
1181 		return -ENOMEM;
1182 
1183 	cmd1->header.id = SVGA_3D_CMD_BIND_GB_SURFACE;
1184 	cmd1->header.size = sizeof(cmd1->body);
1185 	cmd1->body.sid = res->id;
1186 	cmd1->body.mobid = bo->resource->start;
1187 	if (res->backup_dirty) {
1188 		cmd2 = (void *) &cmd1[1];
1189 		cmd2->header.id = SVGA_3D_CMD_UPDATE_GB_SURFACE;
1190 		cmd2->header.size = sizeof(cmd2->body);
1191 		cmd2->body.sid = res->id;
1192 	}
1193 	vmw_cmd_commit(dev_priv, submit_size);
1194 
1195 	if (res->backup->dirty && res->backup_dirty) {
1196 		/* We've just made a full upload. Cear dirty regions. */
1197 		vmw_bo_dirty_clear_res(res);
1198 	}
1199 
1200 	res->backup_dirty = false;
1201 
1202 	return 0;
1203 }
1204 
1205 static int vmw_gb_surface_unbind(struct vmw_resource *res,
1206 				 bool readback,
1207 				 struct ttm_validate_buffer *val_buf)
1208 {
1209 	struct vmw_private *dev_priv = res->dev_priv;
1210 	struct ttm_buffer_object *bo = val_buf->bo;
1211 	struct vmw_fence_obj *fence;
1212 
1213 	struct {
1214 		SVGA3dCmdHeader header;
1215 		SVGA3dCmdReadbackGBSurface body;
1216 	} *cmd1;
1217 	struct {
1218 		SVGA3dCmdHeader header;
1219 		SVGA3dCmdInvalidateGBSurface body;
1220 	} *cmd2;
1221 	struct {
1222 		SVGA3dCmdHeader header;
1223 		SVGA3dCmdBindGBSurface body;
1224 	} *cmd3;
1225 	uint32_t submit_size;
1226 	uint8_t *cmd;
1227 
1228 
1229 	BUG_ON(bo->resource->mem_type != VMW_PL_MOB);
1230 
1231 	submit_size = sizeof(*cmd3) + (readback ? sizeof(*cmd1) : sizeof(*cmd2));
1232 	cmd = VMW_CMD_RESERVE(dev_priv, submit_size);
1233 	if (unlikely(!cmd))
1234 		return -ENOMEM;
1235 
1236 	if (readback) {
1237 		cmd1 = (void *) cmd;
1238 		cmd1->header.id = SVGA_3D_CMD_READBACK_GB_SURFACE;
1239 		cmd1->header.size = sizeof(cmd1->body);
1240 		cmd1->body.sid = res->id;
1241 		cmd3 = (void *) &cmd1[1];
1242 	} else {
1243 		cmd2 = (void *) cmd;
1244 		cmd2->header.id = SVGA_3D_CMD_INVALIDATE_GB_SURFACE;
1245 		cmd2->header.size = sizeof(cmd2->body);
1246 		cmd2->body.sid = res->id;
1247 		cmd3 = (void *) &cmd2[1];
1248 	}
1249 
1250 	cmd3->header.id = SVGA_3D_CMD_BIND_GB_SURFACE;
1251 	cmd3->header.size = sizeof(cmd3->body);
1252 	cmd3->body.sid = res->id;
1253 	cmd3->body.mobid = SVGA3D_INVALID_ID;
1254 
1255 	vmw_cmd_commit(dev_priv, submit_size);
1256 
1257 	/*
1258 	 * Create a fence object and fence the backup buffer.
1259 	 */
1260 
1261 	(void) vmw_execbuf_fence_commands(NULL, dev_priv,
1262 					  &fence, NULL);
1263 
1264 	vmw_bo_fence_single(val_buf->bo, fence);
1265 
1266 	if (likely(fence != NULL))
1267 		vmw_fence_obj_unreference(&fence);
1268 
1269 	return 0;
1270 }
1271 
1272 static int vmw_gb_surface_destroy(struct vmw_resource *res)
1273 {
1274 	struct vmw_private *dev_priv = res->dev_priv;
1275 	struct vmw_surface *srf = vmw_res_to_srf(res);
1276 	struct {
1277 		SVGA3dCmdHeader header;
1278 		SVGA3dCmdDestroyGBSurface body;
1279 	} *cmd;
1280 
1281 	if (likely(res->id == -1))
1282 		return 0;
1283 
1284 	mutex_lock(&dev_priv->binding_mutex);
1285 	vmw_view_surface_list_destroy(dev_priv, &srf->view_list);
1286 	vmw_binding_res_list_scrub(&res->binding_head);
1287 
1288 	cmd = VMW_CMD_RESERVE(dev_priv, sizeof(*cmd));
1289 	if (unlikely(!cmd)) {
1290 		mutex_unlock(&dev_priv->binding_mutex);
1291 		return -ENOMEM;
1292 	}
1293 
1294 	cmd->header.id = SVGA_3D_CMD_DESTROY_GB_SURFACE;
1295 	cmd->header.size = sizeof(cmd->body);
1296 	cmd->body.sid = res->id;
1297 	vmw_cmd_commit(dev_priv, sizeof(*cmd));
1298 	mutex_unlock(&dev_priv->binding_mutex);
1299 	vmw_resource_release_id(res);
1300 	vmw_fifo_resource_dec(dev_priv);
1301 
1302 	return 0;
1303 }
1304 
1305 /**
1306  * vmw_gb_surface_define_ioctl - Ioctl function implementing
1307  * the user surface define functionality.
1308  *
1309  * @dev: Pointer to a struct drm_device.
1310  * @data: Pointer to data copied from / to user-space.
1311  * @file_priv: Pointer to a drm file private structure.
1312  */
1313 int vmw_gb_surface_define_ioctl(struct drm_device *dev, void *data,
1314 				struct drm_file *file_priv)
1315 {
1316 	union drm_vmw_gb_surface_create_arg *arg =
1317 	    (union drm_vmw_gb_surface_create_arg *)data;
1318 	struct drm_vmw_gb_surface_create_rep *rep = &arg->rep;
1319 	struct drm_vmw_gb_surface_create_ext_req req_ext;
1320 
1321 	req_ext.base = arg->req;
1322 	req_ext.version = drm_vmw_gb_surface_v1;
1323 	req_ext.svga3d_flags_upper_32_bits = 0;
1324 	req_ext.multisample_pattern = SVGA3D_MS_PATTERN_NONE;
1325 	req_ext.quality_level = SVGA3D_MS_QUALITY_NONE;
1326 	req_ext.buffer_byte_stride = 0;
1327 	req_ext.must_be_zero = 0;
1328 
1329 	return vmw_gb_surface_define_internal(dev, &req_ext, rep, file_priv);
1330 }
1331 
1332 /**
1333  * vmw_gb_surface_reference_ioctl - Ioctl function implementing
1334  * the user surface reference functionality.
1335  *
1336  * @dev: Pointer to a struct drm_device.
1337  * @data: Pointer to data copied from / to user-space.
1338  * @file_priv: Pointer to a drm file private structure.
1339  */
1340 int vmw_gb_surface_reference_ioctl(struct drm_device *dev, void *data,
1341 				   struct drm_file *file_priv)
1342 {
1343 	union drm_vmw_gb_surface_reference_arg *arg =
1344 	    (union drm_vmw_gb_surface_reference_arg *)data;
1345 	struct drm_vmw_surface_arg *req = &arg->req;
1346 	struct drm_vmw_gb_surface_ref_rep *rep = &arg->rep;
1347 	struct drm_vmw_gb_surface_ref_ext_rep rep_ext;
1348 	int ret;
1349 
1350 	ret = vmw_gb_surface_reference_internal(dev, req, &rep_ext, file_priv);
1351 
1352 	if (unlikely(ret != 0))
1353 		return ret;
1354 
1355 	rep->creq = rep_ext.creq.base;
1356 	rep->crep = rep_ext.crep;
1357 
1358 	return ret;
1359 }
1360 
1361 /**
1362  * vmw_gb_surface_define_ext_ioctl - Ioctl function implementing
1363  * the user surface define functionality.
1364  *
1365  * @dev: Pointer to a struct drm_device.
1366  * @data: Pointer to data copied from / to user-space.
1367  * @file_priv: Pointer to a drm file private structure.
1368  */
1369 int vmw_gb_surface_define_ext_ioctl(struct drm_device *dev, void *data,
1370 				struct drm_file *file_priv)
1371 {
1372 	union drm_vmw_gb_surface_create_ext_arg *arg =
1373 	    (union drm_vmw_gb_surface_create_ext_arg *)data;
1374 	struct drm_vmw_gb_surface_create_ext_req *req = &arg->req;
1375 	struct drm_vmw_gb_surface_create_rep *rep = &arg->rep;
1376 
1377 	return vmw_gb_surface_define_internal(dev, req, rep, file_priv);
1378 }
1379 
1380 /**
1381  * vmw_gb_surface_reference_ext_ioctl - Ioctl function implementing
1382  * the user surface reference functionality.
1383  *
1384  * @dev: Pointer to a struct drm_device.
1385  * @data: Pointer to data copied from / to user-space.
1386  * @file_priv: Pointer to a drm file private structure.
1387  */
1388 int vmw_gb_surface_reference_ext_ioctl(struct drm_device *dev, void *data,
1389 				   struct drm_file *file_priv)
1390 {
1391 	union drm_vmw_gb_surface_reference_ext_arg *arg =
1392 	    (union drm_vmw_gb_surface_reference_ext_arg *)data;
1393 	struct drm_vmw_surface_arg *req = &arg->req;
1394 	struct drm_vmw_gb_surface_ref_ext_rep *rep = &arg->rep;
1395 
1396 	return vmw_gb_surface_reference_internal(dev, req, rep, file_priv);
1397 }
1398 
1399 /**
1400  * vmw_gb_surface_define_internal - Ioctl function implementing
1401  * the user surface define functionality.
1402  *
1403  * @dev: Pointer to a struct drm_device.
1404  * @req: Request argument from user-space.
1405  * @rep: Response argument to user-space.
1406  * @file_priv: Pointer to a drm file private structure.
1407  */
1408 static int
1409 vmw_gb_surface_define_internal(struct drm_device *dev,
1410 			       struct drm_vmw_gb_surface_create_ext_req *req,
1411 			       struct drm_vmw_gb_surface_create_rep *rep,
1412 			       struct drm_file *file_priv)
1413 {
1414 	struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile;
1415 	struct vmw_private *dev_priv = vmw_priv(dev);
1416 	struct vmw_user_surface *user_srf;
1417 	struct vmw_surface_metadata metadata = {0};
1418 	struct vmw_surface *srf;
1419 	struct vmw_resource *res;
1420 	struct vmw_resource *tmp;
1421 	int ret = 0;
1422 	uint32_t backup_handle = 0;
1423 	SVGA3dSurfaceAllFlags svga3d_flags_64 =
1424 		SVGA3D_FLAGS_64(req->svga3d_flags_upper_32_bits,
1425 				req->base.svga3d_flags);
1426 
1427 	/* array_size must be null for non-GL3 host. */
1428 	if (req->base.array_size > 0 && !has_sm4_context(dev_priv)) {
1429 		VMW_DEBUG_USER("SM4 surface not supported.\n");
1430 		return -EINVAL;
1431 	}
1432 
1433 	if (!has_sm4_1_context(dev_priv)) {
1434 		if (req->svga3d_flags_upper_32_bits != 0)
1435 			ret = -EINVAL;
1436 
1437 		if (req->base.multisample_count != 0)
1438 			ret = -EINVAL;
1439 
1440 		if (req->multisample_pattern != SVGA3D_MS_PATTERN_NONE)
1441 			ret = -EINVAL;
1442 
1443 		if (req->quality_level != SVGA3D_MS_QUALITY_NONE)
1444 			ret = -EINVAL;
1445 
1446 		if (ret) {
1447 			VMW_DEBUG_USER("SM4.1 surface not supported.\n");
1448 			return ret;
1449 		}
1450 	}
1451 
1452 	if (req->buffer_byte_stride > 0 && !has_sm5_context(dev_priv)) {
1453 		VMW_DEBUG_USER("SM5 surface not supported.\n");
1454 		return -EINVAL;
1455 	}
1456 
1457 	if ((svga3d_flags_64 & SVGA3D_SURFACE_MULTISAMPLE) &&
1458 	    req->base.multisample_count == 0) {
1459 		VMW_DEBUG_USER("Invalid sample count.\n");
1460 		return -EINVAL;
1461 	}
1462 
1463 	if (req->base.mip_levels > DRM_VMW_MAX_MIP_LEVELS) {
1464 		VMW_DEBUG_USER("Invalid mip level.\n");
1465 		return -EINVAL;
1466 	}
1467 
1468 	metadata.flags = svga3d_flags_64;
1469 	metadata.format = req->base.format;
1470 	metadata.mip_levels[0] = req->base.mip_levels;
1471 	metadata.multisample_count = req->base.multisample_count;
1472 	metadata.multisample_pattern = req->multisample_pattern;
1473 	metadata.quality_level = req->quality_level;
1474 	metadata.array_size = req->base.array_size;
1475 	metadata.buffer_byte_stride = req->buffer_byte_stride;
1476 	metadata.num_sizes = 1;
1477 	metadata.base_size = req->base.base_size;
1478 	metadata.scanout = req->base.drm_surface_flags &
1479 		drm_vmw_surface_flag_scanout;
1480 
1481 	/* Define a surface based on the parameters. */
1482 	ret = vmw_gb_surface_define(dev_priv, &metadata, &srf);
1483 	if (ret != 0) {
1484 		VMW_DEBUG_USER("Failed to define surface.\n");
1485 		return ret;
1486 	}
1487 
1488 	user_srf = container_of(srf, struct vmw_user_surface, srf);
1489 	if (drm_is_primary_client(file_priv))
1490 		user_srf->master = drm_file_get_master(file_priv);
1491 
1492 	res = &user_srf->srf.res;
1493 
1494 	if (req->base.buffer_handle != SVGA3D_INVALID_ID) {
1495 		ret = vmw_user_bo_lookup(file_priv, req->base.buffer_handle,
1496 					 &res->backup);
1497 		if (ret == 0) {
1498 			if (res->backup->base.base.size < res->backup_size) {
1499 				VMW_DEBUG_USER("Surface backup buffer too small.\n");
1500 				vmw_bo_unreference(&res->backup);
1501 				ret = -EINVAL;
1502 				goto out_unlock;
1503 			} else {
1504 				backup_handle = req->base.buffer_handle;
1505 			}
1506 		}
1507 	} else if (req->base.drm_surface_flags &
1508 		   (drm_vmw_surface_flag_create_buffer |
1509 		    drm_vmw_surface_flag_coherent)) {
1510 		ret = vmw_gem_object_create_with_handle(dev_priv, file_priv,
1511 							res->backup_size,
1512 							&backup_handle,
1513 							&res->backup);
1514 		if (ret == 0)
1515 			vmw_bo_reference(res->backup);
1516 
1517 	}
1518 
1519 	if (unlikely(ret != 0)) {
1520 		vmw_resource_unreference(&res);
1521 		goto out_unlock;
1522 	}
1523 
1524 	if (req->base.drm_surface_flags & drm_vmw_surface_flag_coherent) {
1525 		struct vmw_buffer_object *backup = res->backup;
1526 
1527 		ttm_bo_reserve(&backup->base, false, false, NULL);
1528 		if (!res->func->dirty_alloc)
1529 			ret = -EINVAL;
1530 		if (!ret)
1531 			ret = vmw_bo_dirty_add(backup);
1532 		if (!ret) {
1533 			res->coherent = true;
1534 			ret = res->func->dirty_alloc(res);
1535 		}
1536 		ttm_bo_unreserve(&backup->base);
1537 		if (ret) {
1538 			vmw_resource_unreference(&res);
1539 			goto out_unlock;
1540 		}
1541 
1542 	}
1543 
1544 	tmp = vmw_resource_reference(res);
1545 	ret = ttm_prime_object_init(tfile, res->backup_size, &user_srf->prime,
1546 				    req->base.drm_surface_flags &
1547 				    drm_vmw_surface_flag_shareable,
1548 				    VMW_RES_SURFACE,
1549 				    &vmw_user_surface_base_release);
1550 
1551 	if (unlikely(ret != 0)) {
1552 		vmw_resource_unreference(&tmp);
1553 		vmw_resource_unreference(&res);
1554 		goto out_unlock;
1555 	}
1556 
1557 	rep->handle      = user_srf->prime.base.handle;
1558 	rep->backup_size = res->backup_size;
1559 	if (res->backup) {
1560 		rep->buffer_map_handle =
1561 			drm_vma_node_offset_addr(&res->backup->base.base.vma_node);
1562 		rep->buffer_size = res->backup->base.base.size;
1563 		rep->buffer_handle = backup_handle;
1564 	} else {
1565 		rep->buffer_map_handle = 0;
1566 		rep->buffer_size = 0;
1567 		rep->buffer_handle = SVGA3D_INVALID_ID;
1568 	}
1569 	vmw_resource_unreference(&res);
1570 
1571 out_unlock:
1572 	return ret;
1573 }
1574 
1575 /**
1576  * vmw_gb_surface_reference_internal - Ioctl function implementing
1577  * the user surface reference functionality.
1578  *
1579  * @dev: Pointer to a struct drm_device.
1580  * @req: Pointer to user-space request surface arg.
1581  * @rep: Pointer to response to user-space.
1582  * @file_priv: Pointer to a drm file private structure.
1583  */
1584 static int
1585 vmw_gb_surface_reference_internal(struct drm_device *dev,
1586 				  struct drm_vmw_surface_arg *req,
1587 				  struct drm_vmw_gb_surface_ref_ext_rep *rep,
1588 				  struct drm_file *file_priv)
1589 {
1590 	struct vmw_private *dev_priv = vmw_priv(dev);
1591 	struct vmw_surface *srf;
1592 	struct vmw_user_surface *user_srf;
1593 	struct vmw_surface_metadata *metadata;
1594 	struct ttm_base_object *base;
1595 	u32 backup_handle;
1596 	int ret;
1597 
1598 	ret = vmw_surface_handle_reference(dev_priv, file_priv, req->sid,
1599 					   req->handle_type, &base);
1600 	if (unlikely(ret != 0))
1601 		return ret;
1602 
1603 	user_srf = container_of(base, struct vmw_user_surface, prime.base);
1604 	srf = &user_srf->srf;
1605 	if (!srf->res.backup) {
1606 		DRM_ERROR("Shared GB surface is missing a backup buffer.\n");
1607 		goto out_bad_resource;
1608 	}
1609 	metadata = &srf->metadata;
1610 
1611 	mutex_lock(&dev_priv->cmdbuf_mutex); /* Protect res->backup */
1612 	ret = drm_gem_handle_create(file_priv, &srf->res.backup->base.base,
1613 				    &backup_handle);
1614 	mutex_unlock(&dev_priv->cmdbuf_mutex);
1615 	if (ret != 0) {
1616 		drm_err(dev, "Wasn't able to create a backing handle for surface sid = %u.\n",
1617 			req->sid);
1618 		goto out_bad_resource;
1619 	}
1620 
1621 	rep->creq.base.svga3d_flags = SVGA3D_FLAGS_LOWER_32(metadata->flags);
1622 	rep->creq.base.format = metadata->format;
1623 	rep->creq.base.mip_levels = metadata->mip_levels[0];
1624 	rep->creq.base.drm_surface_flags = 0;
1625 	rep->creq.base.multisample_count = metadata->multisample_count;
1626 	rep->creq.base.autogen_filter = metadata->autogen_filter;
1627 	rep->creq.base.array_size = metadata->array_size;
1628 	rep->creq.base.buffer_handle = backup_handle;
1629 	rep->creq.base.base_size = metadata->base_size;
1630 	rep->crep.handle = user_srf->prime.base.handle;
1631 	rep->crep.backup_size = srf->res.backup_size;
1632 	rep->crep.buffer_handle = backup_handle;
1633 	rep->crep.buffer_map_handle =
1634 		drm_vma_node_offset_addr(&srf->res.backup->base.base.vma_node);
1635 	rep->crep.buffer_size = srf->res.backup->base.base.size;
1636 
1637 	rep->creq.version = drm_vmw_gb_surface_v1;
1638 	rep->creq.svga3d_flags_upper_32_bits =
1639 		SVGA3D_FLAGS_UPPER_32(metadata->flags);
1640 	rep->creq.multisample_pattern = metadata->multisample_pattern;
1641 	rep->creq.quality_level = metadata->quality_level;
1642 	rep->creq.must_be_zero = 0;
1643 
1644 out_bad_resource:
1645 	ttm_base_object_unref(&base);
1646 
1647 	return ret;
1648 }
1649 
1650 /**
1651  * vmw_subres_dirty_add - Add a dirty region to a subresource
1652  * @dirty: The surfaces's dirty tracker.
1653  * @loc_start: The location corresponding to the start of the region.
1654  * @loc_end: The location corresponding to the end of the region.
1655  *
1656  * As we are assuming that @loc_start and @loc_end represent a sequential
1657  * range of backing store memory, if the region spans multiple lines then
1658  * regardless of the x coordinate, the full lines are dirtied.
1659  * Correspondingly if the region spans multiple z slices, then full rather
1660  * than partial z slices are dirtied.
1661  */
1662 static void vmw_subres_dirty_add(struct vmw_surface_dirty *dirty,
1663 				 const struct vmw_surface_loc *loc_start,
1664 				 const struct vmw_surface_loc *loc_end)
1665 {
1666 	const struct vmw_surface_cache *cache = &dirty->cache;
1667 	SVGA3dBox *box = &dirty->boxes[loc_start->sub_resource];
1668 	u32 mip = loc_start->sub_resource % cache->num_mip_levels;
1669 	const struct drm_vmw_size *size = &cache->mip[mip].size;
1670 	u32 box_c2 = box->z + box->d;
1671 
1672 	if (WARN_ON(loc_start->sub_resource >= dirty->num_subres))
1673 		return;
1674 
1675 	if (box->d == 0 || box->z > loc_start->z)
1676 		box->z = loc_start->z;
1677 	if (box_c2 < loc_end->z)
1678 		box->d = loc_end->z - box->z;
1679 
1680 	if (loc_start->z + 1 == loc_end->z) {
1681 		box_c2 = box->y + box->h;
1682 		if (box->h == 0 || box->y > loc_start->y)
1683 			box->y = loc_start->y;
1684 		if (box_c2 < loc_end->y)
1685 			box->h = loc_end->y - box->y;
1686 
1687 		if (loc_start->y + 1 == loc_end->y) {
1688 			box_c2 = box->x + box->w;
1689 			if (box->w == 0 || box->x > loc_start->x)
1690 				box->x = loc_start->x;
1691 			if (box_c2 < loc_end->x)
1692 				box->w = loc_end->x - box->x;
1693 		} else {
1694 			box->x = 0;
1695 			box->w = size->width;
1696 		}
1697 	} else {
1698 		box->y = 0;
1699 		box->h = size->height;
1700 		box->x = 0;
1701 		box->w = size->width;
1702 	}
1703 }
1704 
1705 /**
1706  * vmw_subres_dirty_full - Mark a full subresource as dirty
1707  * @dirty: The surface's dirty tracker.
1708  * @subres: The subresource
1709  */
1710 static void vmw_subres_dirty_full(struct vmw_surface_dirty *dirty, u32 subres)
1711 {
1712 	const struct vmw_surface_cache *cache = &dirty->cache;
1713 	u32 mip = subres % cache->num_mip_levels;
1714 	const struct drm_vmw_size *size = &cache->mip[mip].size;
1715 	SVGA3dBox *box = &dirty->boxes[subres];
1716 
1717 	box->x = 0;
1718 	box->y = 0;
1719 	box->z = 0;
1720 	box->w = size->width;
1721 	box->h = size->height;
1722 	box->d = size->depth;
1723 }
1724 
1725 /*
1726  * vmw_surface_tex_dirty_add_range - The dirty_add_range callback for texture
1727  * surfaces.
1728  */
1729 static void vmw_surface_tex_dirty_range_add(struct vmw_resource *res,
1730 					    size_t start, size_t end)
1731 {
1732 	struct vmw_surface_dirty *dirty =
1733 		(struct vmw_surface_dirty *) res->dirty;
1734 	size_t backup_end = res->backup_offset + res->backup_size;
1735 	struct vmw_surface_loc loc1, loc2;
1736 	const struct vmw_surface_cache *cache;
1737 
1738 	start = max_t(size_t, start, res->backup_offset) - res->backup_offset;
1739 	end = min(end, backup_end) - res->backup_offset;
1740 	cache = &dirty->cache;
1741 	vmw_surface_get_loc(cache, &loc1, start);
1742 	vmw_surface_get_loc(cache, &loc2, end - 1);
1743 	vmw_surface_inc_loc(cache, &loc2);
1744 
1745 	if (loc1.sheet != loc2.sheet) {
1746 		u32 sub_res;
1747 
1748 		/*
1749 		 * Multiple multisample sheets. To do this in an optimized
1750 		 * fashion, compute the dirty region for each sheet and the
1751 		 * resulting union. Since this is not a common case, just dirty
1752 		 * the whole surface.
1753 		 */
1754 		for (sub_res = 0; sub_res < dirty->num_subres; ++sub_res)
1755 			vmw_subres_dirty_full(dirty, sub_res);
1756 		return;
1757 	}
1758 	if (loc1.sub_resource + 1 == loc2.sub_resource) {
1759 		/* Dirty range covers a single sub-resource */
1760 		vmw_subres_dirty_add(dirty, &loc1, &loc2);
1761 	} else {
1762 		/* Dirty range covers multiple sub-resources */
1763 		struct vmw_surface_loc loc_min, loc_max;
1764 		u32 sub_res;
1765 
1766 		vmw_surface_max_loc(cache, loc1.sub_resource, &loc_max);
1767 		vmw_subres_dirty_add(dirty, &loc1, &loc_max);
1768 		vmw_surface_min_loc(cache, loc2.sub_resource - 1, &loc_min);
1769 		vmw_subres_dirty_add(dirty, &loc_min, &loc2);
1770 		for (sub_res = loc1.sub_resource + 1;
1771 		     sub_res < loc2.sub_resource - 1; ++sub_res)
1772 			vmw_subres_dirty_full(dirty, sub_res);
1773 	}
1774 }
1775 
1776 /*
1777  * vmw_surface_tex_dirty_add_range - The dirty_add_range callback for buffer
1778  * surfaces.
1779  */
1780 static void vmw_surface_buf_dirty_range_add(struct vmw_resource *res,
1781 					    size_t start, size_t end)
1782 {
1783 	struct vmw_surface_dirty *dirty =
1784 		(struct vmw_surface_dirty *) res->dirty;
1785 	const struct vmw_surface_cache *cache = &dirty->cache;
1786 	size_t backup_end = res->backup_offset + cache->mip_chain_bytes;
1787 	SVGA3dBox *box = &dirty->boxes[0];
1788 	u32 box_c2;
1789 
1790 	box->h = box->d = 1;
1791 	start = max_t(size_t, start, res->backup_offset) - res->backup_offset;
1792 	end = min(end, backup_end) - res->backup_offset;
1793 	box_c2 = box->x + box->w;
1794 	if (box->w == 0 || box->x > start)
1795 		box->x = start;
1796 	if (box_c2 < end)
1797 		box->w = end - box->x;
1798 }
1799 
1800 /*
1801  * vmw_surface_tex_dirty_add_range - The dirty_add_range callback for surfaces
1802  */
1803 static void vmw_surface_dirty_range_add(struct vmw_resource *res, size_t start,
1804 					size_t end)
1805 {
1806 	struct vmw_surface *srf = vmw_res_to_srf(res);
1807 
1808 	if (WARN_ON(end <= res->backup_offset ||
1809 		    start >= res->backup_offset + res->backup_size))
1810 		return;
1811 
1812 	if (srf->metadata.format == SVGA3D_BUFFER)
1813 		vmw_surface_buf_dirty_range_add(res, start, end);
1814 	else
1815 		vmw_surface_tex_dirty_range_add(res, start, end);
1816 }
1817 
1818 /*
1819  * vmw_surface_dirty_sync - The surface's dirty_sync callback.
1820  */
1821 static int vmw_surface_dirty_sync(struct vmw_resource *res)
1822 {
1823 	struct vmw_private *dev_priv = res->dev_priv;
1824 	u32 i, num_dirty;
1825 	struct vmw_surface_dirty *dirty =
1826 		(struct vmw_surface_dirty *) res->dirty;
1827 	size_t alloc_size;
1828 	const struct vmw_surface_cache *cache = &dirty->cache;
1829 	struct {
1830 		SVGA3dCmdHeader header;
1831 		SVGA3dCmdDXUpdateSubResource body;
1832 	} *cmd1;
1833 	struct {
1834 		SVGA3dCmdHeader header;
1835 		SVGA3dCmdUpdateGBImage body;
1836 	} *cmd2;
1837 	void *cmd;
1838 
1839 	num_dirty = 0;
1840 	for (i = 0; i < dirty->num_subres; ++i) {
1841 		const SVGA3dBox *box = &dirty->boxes[i];
1842 
1843 		if (box->d)
1844 			num_dirty++;
1845 	}
1846 
1847 	if (!num_dirty)
1848 		goto out;
1849 
1850 	alloc_size = num_dirty * ((has_sm4_context(dev_priv)) ? sizeof(*cmd1) : sizeof(*cmd2));
1851 	cmd = VMW_CMD_RESERVE(dev_priv, alloc_size);
1852 	if (!cmd)
1853 		return -ENOMEM;
1854 
1855 	cmd1 = cmd;
1856 	cmd2 = cmd;
1857 
1858 	for (i = 0; i < dirty->num_subres; ++i) {
1859 		const SVGA3dBox *box = &dirty->boxes[i];
1860 
1861 		if (!box->d)
1862 			continue;
1863 
1864 		/*
1865 		 * DX_UPDATE_SUBRESOURCE is aware of array surfaces.
1866 		 * UPDATE_GB_IMAGE is not.
1867 		 */
1868 		if (has_sm4_context(dev_priv)) {
1869 			cmd1->header.id = SVGA_3D_CMD_DX_UPDATE_SUBRESOURCE;
1870 			cmd1->header.size = sizeof(cmd1->body);
1871 			cmd1->body.sid = res->id;
1872 			cmd1->body.subResource = i;
1873 			cmd1->body.box = *box;
1874 			cmd1++;
1875 		} else {
1876 			cmd2->header.id = SVGA_3D_CMD_UPDATE_GB_IMAGE;
1877 			cmd2->header.size = sizeof(cmd2->body);
1878 			cmd2->body.image.sid = res->id;
1879 			cmd2->body.image.face = i / cache->num_mip_levels;
1880 			cmd2->body.image.mipmap = i -
1881 				(cache->num_mip_levels * cmd2->body.image.face);
1882 			cmd2->body.box = *box;
1883 			cmd2++;
1884 		}
1885 
1886 	}
1887 	vmw_cmd_commit(dev_priv, alloc_size);
1888  out:
1889 	memset(&dirty->boxes[0], 0, sizeof(dirty->boxes[0]) *
1890 	       dirty->num_subres);
1891 
1892 	return 0;
1893 }
1894 
1895 /*
1896  * vmw_surface_dirty_alloc - The surface's dirty_alloc callback.
1897  */
1898 static int vmw_surface_dirty_alloc(struct vmw_resource *res)
1899 {
1900 	struct vmw_surface *srf = vmw_res_to_srf(res);
1901 	const struct vmw_surface_metadata *metadata = &srf->metadata;
1902 	struct vmw_surface_dirty *dirty;
1903 	u32 num_layers = 1;
1904 	u32 num_mip;
1905 	u32 num_subres;
1906 	u32 num_samples;
1907 	size_t dirty_size;
1908 	int ret;
1909 
1910 	if (metadata->array_size)
1911 		num_layers = metadata->array_size;
1912 	else if (metadata->flags & SVGA3D_SURFACE_CUBEMAP)
1913 		num_layers *= SVGA3D_MAX_SURFACE_FACES;
1914 
1915 	num_mip = metadata->mip_levels[0];
1916 	if (!num_mip)
1917 		num_mip = 1;
1918 
1919 	num_subres = num_layers * num_mip;
1920 	dirty_size = struct_size(dirty, boxes, num_subres);
1921 
1922 	dirty = kvzalloc(dirty_size, GFP_KERNEL);
1923 	if (!dirty) {
1924 		ret = -ENOMEM;
1925 		goto out_no_dirty;
1926 	}
1927 
1928 	num_samples = max_t(u32, 1, metadata->multisample_count);
1929 	ret = vmw_surface_setup_cache(&metadata->base_size, metadata->format,
1930 				      num_mip, num_layers, num_samples,
1931 				      &dirty->cache);
1932 	if (ret)
1933 		goto out_no_cache;
1934 
1935 	dirty->num_subres = num_subres;
1936 	res->dirty = (struct vmw_resource_dirty *) dirty;
1937 
1938 	return 0;
1939 
1940 out_no_cache:
1941 	kvfree(dirty);
1942 out_no_dirty:
1943 	return ret;
1944 }
1945 
1946 /*
1947  * vmw_surface_dirty_free - The surface's dirty_free callback
1948  */
1949 static void vmw_surface_dirty_free(struct vmw_resource *res)
1950 {
1951 	struct vmw_surface_dirty *dirty =
1952 		(struct vmw_surface_dirty *) res->dirty;
1953 
1954 	kvfree(dirty);
1955 	res->dirty = NULL;
1956 }
1957 
1958 /*
1959  * vmw_surface_clean - The surface's clean callback
1960  */
1961 static int vmw_surface_clean(struct vmw_resource *res)
1962 {
1963 	struct vmw_private *dev_priv = res->dev_priv;
1964 	size_t alloc_size;
1965 	struct {
1966 		SVGA3dCmdHeader header;
1967 		SVGA3dCmdReadbackGBSurface body;
1968 	} *cmd;
1969 
1970 	alloc_size = sizeof(*cmd);
1971 	cmd = VMW_CMD_RESERVE(dev_priv, alloc_size);
1972 	if (!cmd)
1973 		return -ENOMEM;
1974 
1975 	cmd->header.id = SVGA_3D_CMD_READBACK_GB_SURFACE;
1976 	cmd->header.size = sizeof(cmd->body);
1977 	cmd->body.sid = res->id;
1978 	vmw_cmd_commit(dev_priv, alloc_size);
1979 
1980 	return 0;
1981 }
1982 
1983 /*
1984  * vmw_gb_surface_define - Define a private GB surface
1985  *
1986  * @dev_priv: Pointer to a device private.
1987  * @metadata: Metadata representing the surface to create.
1988  * @user_srf_out: allocated user_srf. Set to NULL on failure.
1989  *
1990  * GB surfaces allocated by this function will not have a user mode handle, and
1991  * thus will only be visible to vmwgfx.  For optimization reasons the
1992  * surface may later be given a user mode handle by another function to make
1993  * it available to user mode drivers.
1994  */
1995 int vmw_gb_surface_define(struct vmw_private *dev_priv,
1996 			  const struct vmw_surface_metadata *req,
1997 			  struct vmw_surface **srf_out)
1998 {
1999 	struct vmw_surface_metadata *metadata;
2000 	struct vmw_user_surface *user_srf;
2001 	struct vmw_surface *srf;
2002 	u32 sample_count = 1;
2003 	u32 num_layers = 1;
2004 	int ret;
2005 
2006 	*srf_out = NULL;
2007 
2008 	if (req->scanout) {
2009 		if (!vmw_surface_is_screen_target_format(req->format)) {
2010 			VMW_DEBUG_USER("Invalid Screen Target surface format.");
2011 			return -EINVAL;
2012 		}
2013 
2014 		if (req->base_size.width > dev_priv->texture_max_width ||
2015 		    req->base_size.height > dev_priv->texture_max_height) {
2016 			VMW_DEBUG_USER("%ux%u\n, exceed max surface size %ux%u",
2017 				       req->base_size.width,
2018 				       req->base_size.height,
2019 				       dev_priv->texture_max_width,
2020 				       dev_priv->texture_max_height);
2021 			return -EINVAL;
2022 		}
2023 	} else {
2024 		const SVGA3dSurfaceDesc *desc =
2025 			vmw_surface_get_desc(req->format);
2026 
2027 		if (desc->blockDesc == SVGA3DBLOCKDESC_NONE) {
2028 			VMW_DEBUG_USER("Invalid surface format.\n");
2029 			return -EINVAL;
2030 		}
2031 	}
2032 
2033 	if (req->autogen_filter != SVGA3D_TEX_FILTER_NONE)
2034 		return -EINVAL;
2035 
2036 	if (req->num_sizes != 1)
2037 		return -EINVAL;
2038 
2039 	if (req->sizes != NULL)
2040 		return -EINVAL;
2041 
2042 	user_srf = kzalloc(sizeof(*user_srf), GFP_KERNEL);
2043 	if (unlikely(!user_srf)) {
2044 		ret = -ENOMEM;
2045 		goto out_unlock;
2046 	}
2047 
2048 	*srf_out  = &user_srf->srf;
2049 	user_srf->prime.base.shareable = false;
2050 	user_srf->prime.base.tfile = NULL;
2051 
2052 	srf = &user_srf->srf;
2053 	srf->metadata = *req;
2054 	srf->offsets = NULL;
2055 
2056 	metadata = &srf->metadata;
2057 
2058 	if (metadata->array_size)
2059 		num_layers = req->array_size;
2060 	else if (metadata->flags & SVGA3D_SURFACE_CUBEMAP)
2061 		num_layers = SVGA3D_MAX_SURFACE_FACES;
2062 
2063 	if (metadata->flags & SVGA3D_SURFACE_MULTISAMPLE)
2064 		sample_count = metadata->multisample_count;
2065 
2066 	srf->res.backup_size =
2067 		vmw_surface_get_serialized_size_extended(
2068 				metadata->format,
2069 				metadata->base_size,
2070 				metadata->mip_levels[0],
2071 				num_layers,
2072 				sample_count);
2073 
2074 	if (metadata->flags & SVGA3D_SURFACE_BIND_STREAM_OUTPUT)
2075 		srf->res.backup_size += sizeof(SVGA3dDXSOState);
2076 
2077 	/*
2078 	 * Don't set SVGA3D_SURFACE_SCREENTARGET flag for a scanout surface with
2079 	 * size greater than STDU max width/height. This is really a workaround
2080 	 * to support creation of big framebuffer requested by some user-space
2081 	 * for whole topology. That big framebuffer won't really be used for
2082 	 * binding with screen target as during prepare_fb a separate surface is
2083 	 * created so it's safe to ignore SVGA3D_SURFACE_SCREENTARGET flag.
2084 	 */
2085 	if (dev_priv->active_display_unit == vmw_du_screen_target &&
2086 	    metadata->scanout &&
2087 	    metadata->base_size.width <= dev_priv->stdu_max_width &&
2088 	    metadata->base_size.height <= dev_priv->stdu_max_height)
2089 		metadata->flags |= SVGA3D_SURFACE_SCREENTARGET;
2090 
2091 	/*
2092 	 * From this point, the generic resource management functions
2093 	 * destroy the object on failure.
2094 	 */
2095 	ret = vmw_surface_init(dev_priv, srf, vmw_user_surface_free);
2096 
2097 	return ret;
2098 
2099 out_unlock:
2100 	return ret;
2101 }
2102