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/drm_atomic.h>
29 #include <drm/drm_atomic_helper.h>
30 #include <drm/drm_damage_helper.h>
31 #include <drm/drm_fourcc.h>
32 #include <drm/drm_plane_helper.h>
33 #include <drm/drm_rect.h>
34 #include <drm/drm_sysfs.h>
35 #include <drm/drm_vblank.h>
36 
37 #include "vmwgfx_kms.h"
38 
39 void vmw_du_cleanup(struct vmw_display_unit *du)
40 {
41 	struct vmw_private *dev_priv = vmw_priv(du->primary.dev);
42 	drm_plane_cleanup(&du->primary);
43 	if (vmw_cmd_supported(dev_priv))
44 		drm_plane_cleanup(&du->cursor);
45 
46 	drm_connector_unregister(&du->connector);
47 	drm_crtc_cleanup(&du->crtc);
48 	drm_encoder_cleanup(&du->encoder);
49 	drm_connector_cleanup(&du->connector);
50 }
51 
52 /*
53  * Display Unit Cursor functions
54  */
55 
56 static int vmw_cursor_update_image(struct vmw_private *dev_priv,
57 				   u32 *image, u32 width, u32 height,
58 				   u32 hotspotX, u32 hotspotY)
59 {
60 	struct {
61 		u32 cmd;
62 		SVGAFifoCmdDefineAlphaCursor cursor;
63 	} *cmd;
64 	u32 image_size = width * height * 4;
65 	u32 cmd_size = sizeof(*cmd) + image_size;
66 
67 	if (!image)
68 		return -EINVAL;
69 
70 	cmd = VMW_CMD_RESERVE(dev_priv, cmd_size);
71 	if (unlikely(cmd == NULL))
72 		return -ENOMEM;
73 
74 	memset(cmd, 0, sizeof(*cmd));
75 
76 	memcpy(&cmd[1], image, image_size);
77 
78 	cmd->cmd = SVGA_CMD_DEFINE_ALPHA_CURSOR;
79 	cmd->cursor.id = 0;
80 	cmd->cursor.width = width;
81 	cmd->cursor.height = height;
82 	cmd->cursor.hotspotX = hotspotX;
83 	cmd->cursor.hotspotY = hotspotY;
84 
85 	vmw_cmd_commit_flush(dev_priv, cmd_size);
86 
87 	return 0;
88 }
89 
90 static int vmw_cursor_update_bo(struct vmw_private *dev_priv,
91 				struct vmw_buffer_object *bo,
92 				u32 width, u32 height,
93 				u32 hotspotX, u32 hotspotY)
94 {
95 	struct ttm_bo_kmap_obj map;
96 	unsigned long kmap_offset;
97 	unsigned long kmap_num;
98 	void *virtual;
99 	bool dummy;
100 	int ret;
101 
102 	kmap_offset = 0;
103 	kmap_num = PFN_UP(width*height*4);
104 
105 	ret = ttm_bo_reserve(&bo->base, true, false, NULL);
106 	if (unlikely(ret != 0)) {
107 		DRM_ERROR("reserve failed\n");
108 		return -EINVAL;
109 	}
110 
111 	ret = ttm_bo_kmap(&bo->base, kmap_offset, kmap_num, &map);
112 	if (unlikely(ret != 0))
113 		goto err_unreserve;
114 
115 	virtual = ttm_kmap_obj_virtual(&map, &dummy);
116 	ret = vmw_cursor_update_image(dev_priv, virtual, width, height,
117 				      hotspotX, hotspotY);
118 
119 	ttm_bo_kunmap(&map);
120 err_unreserve:
121 	ttm_bo_unreserve(&bo->base);
122 
123 	return ret;
124 }
125 
126 
127 static void vmw_cursor_update_position(struct vmw_private *dev_priv,
128 				       bool show, int x, int y)
129 {
130 	uint32_t count;
131 
132 	spin_lock(&dev_priv->cursor_lock);
133 	if (vmw_is_cursor_bypass3_enabled(dev_priv)) {
134 		vmw_fifo_mem_write(dev_priv, SVGA_FIFO_CURSOR_ON, show ? 1 : 0);
135 		vmw_fifo_mem_write(dev_priv, SVGA_FIFO_CURSOR_X, x);
136 		vmw_fifo_mem_write(dev_priv, SVGA_FIFO_CURSOR_Y, y);
137 		count = vmw_fifo_mem_read(dev_priv, SVGA_FIFO_CURSOR_COUNT);
138 		vmw_fifo_mem_write(dev_priv, SVGA_FIFO_CURSOR_COUNT, ++count);
139 	} else {
140 		vmw_write(dev_priv, SVGA_REG_CURSOR_X, x);
141 		vmw_write(dev_priv, SVGA_REG_CURSOR_Y, y);
142 		vmw_write(dev_priv, SVGA_REG_CURSOR_ON, show ? 1 : 0);
143 	}
144 	spin_unlock(&dev_priv->cursor_lock);
145 }
146 
147 
148 void vmw_kms_cursor_snoop(struct vmw_surface *srf,
149 			  struct ttm_object_file *tfile,
150 			  struct ttm_buffer_object *bo,
151 			  SVGA3dCmdHeader *header)
152 {
153 	struct ttm_bo_kmap_obj map;
154 	unsigned long kmap_offset;
155 	unsigned long kmap_num;
156 	SVGA3dCopyBox *box;
157 	unsigned box_count;
158 	void *virtual;
159 	bool dummy;
160 	struct vmw_dma_cmd {
161 		SVGA3dCmdHeader header;
162 		SVGA3dCmdSurfaceDMA dma;
163 	} *cmd;
164 	int i, ret;
165 
166 	cmd = container_of(header, struct vmw_dma_cmd, header);
167 
168 	/* No snooper installed */
169 	if (!srf->snooper.image)
170 		return;
171 
172 	if (cmd->dma.host.face != 0 || cmd->dma.host.mipmap != 0) {
173 		DRM_ERROR("face and mipmap for cursors should never != 0\n");
174 		return;
175 	}
176 
177 	if (cmd->header.size < 64) {
178 		DRM_ERROR("at least one full copy box must be given\n");
179 		return;
180 	}
181 
182 	box = (SVGA3dCopyBox *)&cmd[1];
183 	box_count = (cmd->header.size - sizeof(SVGA3dCmdSurfaceDMA)) /
184 			sizeof(SVGA3dCopyBox);
185 
186 	if (cmd->dma.guest.ptr.offset % PAGE_SIZE ||
187 	    box->x != 0    || box->y != 0    || box->z != 0    ||
188 	    box->srcx != 0 || box->srcy != 0 || box->srcz != 0 ||
189 	    box->d != 1    || box_count != 1) {
190 		/* TODO handle none page aligned offsets */
191 		/* TODO handle more dst & src != 0 */
192 		/* TODO handle more then one copy */
193 		DRM_ERROR("Can't snoop dma request for cursor!\n");
194 		DRM_ERROR("(%u, %u, %u) (%u, %u, %u) (%ux%ux%u) %u %u\n",
195 			  box->srcx, box->srcy, box->srcz,
196 			  box->x, box->y, box->z,
197 			  box->w, box->h, box->d, box_count,
198 			  cmd->dma.guest.ptr.offset);
199 		return;
200 	}
201 
202 	kmap_offset = cmd->dma.guest.ptr.offset >> PAGE_SHIFT;
203 	kmap_num = (64*64*4) >> PAGE_SHIFT;
204 
205 	ret = ttm_bo_reserve(bo, true, false, NULL);
206 	if (unlikely(ret != 0)) {
207 		DRM_ERROR("reserve failed\n");
208 		return;
209 	}
210 
211 	ret = ttm_bo_kmap(bo, kmap_offset, kmap_num, &map);
212 	if (unlikely(ret != 0))
213 		goto err_unreserve;
214 
215 	virtual = ttm_kmap_obj_virtual(&map, &dummy);
216 
217 	if (box->w == 64 && cmd->dma.guest.pitch == 64*4) {
218 		memcpy(srf->snooper.image, virtual, 64*64*4);
219 	} else {
220 		/* Image is unsigned pointer. */
221 		for (i = 0; i < box->h; i++)
222 			memcpy(srf->snooper.image + i * 64,
223 			       virtual + i * cmd->dma.guest.pitch,
224 			       box->w * 4);
225 	}
226 
227 	srf->snooper.age++;
228 
229 	ttm_bo_kunmap(&map);
230 err_unreserve:
231 	ttm_bo_unreserve(bo);
232 }
233 
234 /**
235  * vmw_kms_legacy_hotspot_clear - Clear legacy hotspots
236  *
237  * @dev_priv: Pointer to the device private struct.
238  *
239  * Clears all legacy hotspots.
240  */
241 void vmw_kms_legacy_hotspot_clear(struct vmw_private *dev_priv)
242 {
243 	struct drm_device *dev = &dev_priv->drm;
244 	struct vmw_display_unit *du;
245 	struct drm_crtc *crtc;
246 
247 	drm_modeset_lock_all(dev);
248 	drm_for_each_crtc(crtc, dev) {
249 		du = vmw_crtc_to_du(crtc);
250 
251 		du->hotspot_x = 0;
252 		du->hotspot_y = 0;
253 	}
254 	drm_modeset_unlock_all(dev);
255 }
256 
257 void vmw_kms_cursor_post_execbuf(struct vmw_private *dev_priv)
258 {
259 	struct drm_device *dev = &dev_priv->drm;
260 	struct vmw_display_unit *du;
261 	struct drm_crtc *crtc;
262 
263 	mutex_lock(&dev->mode_config.mutex);
264 
265 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
266 		du = vmw_crtc_to_du(crtc);
267 		if (!du->cursor_surface ||
268 		    du->cursor_age == du->cursor_surface->snooper.age)
269 			continue;
270 
271 		du->cursor_age = du->cursor_surface->snooper.age;
272 		vmw_cursor_update_image(dev_priv,
273 					du->cursor_surface->snooper.image,
274 					64, 64,
275 					du->hotspot_x + du->core_hotspot_x,
276 					du->hotspot_y + du->core_hotspot_y);
277 	}
278 
279 	mutex_unlock(&dev->mode_config.mutex);
280 }
281 
282 
283 void vmw_du_cursor_plane_destroy(struct drm_plane *plane)
284 {
285 	vmw_cursor_update_position(plane->dev->dev_private, false, 0, 0);
286 
287 	drm_plane_cleanup(plane);
288 }
289 
290 
291 void vmw_du_primary_plane_destroy(struct drm_plane *plane)
292 {
293 	drm_plane_cleanup(plane);
294 
295 	/* Planes are static in our case so we don't free it */
296 }
297 
298 
299 /**
300  * vmw_du_plane_unpin_surf - unpins resource associated with a framebuffer surface
301  *
302  * @vps: plane state associated with the display surface
303  * @unreference: true if we also want to unreference the display.
304  */
305 void vmw_du_plane_unpin_surf(struct vmw_plane_state *vps,
306 			     bool unreference)
307 {
308 	if (vps->surf) {
309 		if (vps->pinned) {
310 			vmw_resource_unpin(&vps->surf->res);
311 			vps->pinned--;
312 		}
313 
314 		if (unreference) {
315 			if (vps->pinned)
316 				DRM_ERROR("Surface still pinned\n");
317 			vmw_surface_unreference(&vps->surf);
318 		}
319 	}
320 }
321 
322 
323 /**
324  * vmw_du_plane_cleanup_fb - Unpins the cursor
325  *
326  * @plane:  display plane
327  * @old_state: Contains the FB to clean up
328  *
329  * Unpins the framebuffer surface
330  *
331  * Returns 0 on success
332  */
333 void
334 vmw_du_plane_cleanup_fb(struct drm_plane *plane,
335 			struct drm_plane_state *old_state)
336 {
337 	struct vmw_plane_state *vps = vmw_plane_state_to_vps(old_state);
338 
339 	vmw_du_plane_unpin_surf(vps, false);
340 }
341 
342 
343 /**
344  * vmw_du_cursor_plane_prepare_fb - Readies the cursor by referencing it
345  *
346  * @plane:  display plane
347  * @new_state: info on the new plane state, including the FB
348  *
349  * Returns 0 on success
350  */
351 int
352 vmw_du_cursor_plane_prepare_fb(struct drm_plane *plane,
353 			       struct drm_plane_state *new_state)
354 {
355 	struct drm_framebuffer *fb = new_state->fb;
356 	struct vmw_plane_state *vps = vmw_plane_state_to_vps(new_state);
357 
358 
359 	if (vps->surf)
360 		vmw_surface_unreference(&vps->surf);
361 
362 	if (vps->bo)
363 		vmw_bo_unreference(&vps->bo);
364 
365 	if (fb) {
366 		if (vmw_framebuffer_to_vfb(fb)->bo) {
367 			vps->bo = vmw_framebuffer_to_vfbd(fb)->buffer;
368 			vmw_bo_reference(vps->bo);
369 		} else {
370 			vps->surf = vmw_framebuffer_to_vfbs(fb)->surface;
371 			vmw_surface_reference(vps->surf);
372 		}
373 	}
374 
375 	return 0;
376 }
377 
378 
379 void
380 vmw_du_cursor_plane_atomic_update(struct drm_plane *plane,
381 				  struct drm_atomic_state *state)
382 {
383 	struct drm_plane_state *new_state = drm_atomic_get_new_plane_state(state,
384 									   plane);
385 	struct drm_plane_state *old_state = drm_atomic_get_old_plane_state(state,
386 									   plane);
387 	struct drm_crtc *crtc = new_state->crtc ?: old_state->crtc;
388 	struct vmw_private *dev_priv = vmw_priv(crtc->dev);
389 	struct vmw_display_unit *du = vmw_crtc_to_du(crtc);
390 	struct vmw_plane_state *vps = vmw_plane_state_to_vps(new_state);
391 	s32 hotspot_x, hotspot_y;
392 	int ret = 0;
393 
394 
395 	hotspot_x = du->hotspot_x;
396 	hotspot_y = du->hotspot_y;
397 
398 	if (new_state->fb) {
399 		hotspot_x += new_state->fb->hot_x;
400 		hotspot_y += new_state->fb->hot_y;
401 	}
402 
403 	du->cursor_surface = vps->surf;
404 	du->cursor_bo = vps->bo;
405 
406 	if (vps->surf) {
407 		du->cursor_age = du->cursor_surface->snooper.age;
408 
409 		ret = vmw_cursor_update_image(dev_priv,
410 					      vps->surf->snooper.image,
411 					      64, 64, hotspot_x,
412 					      hotspot_y);
413 	} else if (vps->bo) {
414 		ret = vmw_cursor_update_bo(dev_priv, vps->bo,
415 					   new_state->crtc_w,
416 					   new_state->crtc_h,
417 					   hotspot_x, hotspot_y);
418 	} else {
419 		vmw_cursor_update_position(dev_priv, false, 0, 0);
420 		return;
421 	}
422 
423 	if (!ret) {
424 		du->cursor_x = new_state->crtc_x + du->set_gui_x;
425 		du->cursor_y = new_state->crtc_y + du->set_gui_y;
426 
427 		vmw_cursor_update_position(dev_priv, true,
428 					   du->cursor_x + hotspot_x,
429 					   du->cursor_y + hotspot_y);
430 
431 		du->core_hotspot_x = hotspot_x - du->hotspot_x;
432 		du->core_hotspot_y = hotspot_y - du->hotspot_y;
433 	} else {
434 		DRM_ERROR("Failed to update cursor image\n");
435 	}
436 }
437 
438 
439 /**
440  * vmw_du_primary_plane_atomic_check - check if the new state is okay
441  *
442  * @plane: display plane
443  * @state: info on the new plane state, including the FB
444  *
445  * Check if the new state is settable given the current state.  Other
446  * than what the atomic helper checks, we care about crtc fitting
447  * the FB and maintaining one active framebuffer.
448  *
449  * Returns 0 on success
450  */
451 int vmw_du_primary_plane_atomic_check(struct drm_plane *plane,
452 				      struct drm_atomic_state *state)
453 {
454 	struct drm_plane_state *new_state = drm_atomic_get_new_plane_state(state,
455 									   plane);
456 	struct drm_crtc_state *crtc_state = NULL;
457 	struct drm_framebuffer *new_fb = new_state->fb;
458 	int ret;
459 
460 	if (new_state->crtc)
461 		crtc_state = drm_atomic_get_new_crtc_state(state,
462 							   new_state->crtc);
463 
464 	ret = drm_atomic_helper_check_plane_state(new_state, crtc_state,
465 						  DRM_PLANE_HELPER_NO_SCALING,
466 						  DRM_PLANE_HELPER_NO_SCALING,
467 						  false, true);
468 
469 	if (!ret && new_fb) {
470 		struct drm_crtc *crtc = new_state->crtc;
471 		struct vmw_display_unit *du = vmw_crtc_to_du(crtc);
472 
473 		vmw_connector_state_to_vcs(du->connector.state);
474 	}
475 
476 
477 	return ret;
478 }
479 
480 
481 /**
482  * vmw_du_cursor_plane_atomic_check - check if the new state is okay
483  *
484  * @plane: cursor plane
485  * @state: info on the new plane state
486  *
487  * This is a chance to fail if the new cursor state does not fit
488  * our requirements.
489  *
490  * Returns 0 on success
491  */
492 int vmw_du_cursor_plane_atomic_check(struct drm_plane *plane,
493 				     struct drm_atomic_state *state)
494 {
495 	struct drm_plane_state *new_state = drm_atomic_get_new_plane_state(state,
496 									   plane);
497 	int ret = 0;
498 	struct drm_crtc_state *crtc_state = NULL;
499 	struct vmw_surface *surface = NULL;
500 	struct drm_framebuffer *fb = new_state->fb;
501 
502 	if (new_state->crtc)
503 		crtc_state = drm_atomic_get_new_crtc_state(new_state->state,
504 							   new_state->crtc);
505 
506 	ret = drm_atomic_helper_check_plane_state(new_state, crtc_state,
507 						  DRM_PLANE_HELPER_NO_SCALING,
508 						  DRM_PLANE_HELPER_NO_SCALING,
509 						  true, true);
510 	if (ret)
511 		return ret;
512 
513 	/* Turning off */
514 	if (!fb)
515 		return 0;
516 
517 	/* A lot of the code assumes this */
518 	if (new_state->crtc_w != 64 || new_state->crtc_h != 64) {
519 		DRM_ERROR("Invalid cursor dimensions (%d, %d)\n",
520 			  new_state->crtc_w, new_state->crtc_h);
521 		ret = -EINVAL;
522 	}
523 
524 	if (!vmw_framebuffer_to_vfb(fb)->bo)
525 		surface = vmw_framebuffer_to_vfbs(fb)->surface;
526 
527 	if (surface && !surface->snooper.image) {
528 		DRM_ERROR("surface not suitable for cursor\n");
529 		ret = -EINVAL;
530 	}
531 
532 	return ret;
533 }
534 
535 
536 int vmw_du_crtc_atomic_check(struct drm_crtc *crtc,
537 			     struct drm_atomic_state *state)
538 {
539 	struct drm_crtc_state *new_state = drm_atomic_get_new_crtc_state(state,
540 									 crtc);
541 	struct vmw_display_unit *du = vmw_crtc_to_du(new_state->crtc);
542 	int connector_mask = drm_connector_mask(&du->connector);
543 	bool has_primary = new_state->plane_mask &
544 			   drm_plane_mask(crtc->primary);
545 
546 	/* We always want to have an active plane with an active CRTC */
547 	if (has_primary != new_state->enable)
548 		return -EINVAL;
549 
550 
551 	if (new_state->connector_mask != connector_mask &&
552 	    new_state->connector_mask != 0) {
553 		DRM_ERROR("Invalid connectors configuration\n");
554 		return -EINVAL;
555 	}
556 
557 	/*
558 	 * Our virtual device does not have a dot clock, so use the logical
559 	 * clock value as the dot clock.
560 	 */
561 	if (new_state->mode.crtc_clock == 0)
562 		new_state->adjusted_mode.crtc_clock = new_state->mode.clock;
563 
564 	return 0;
565 }
566 
567 
568 void vmw_du_crtc_atomic_begin(struct drm_crtc *crtc,
569 			      struct drm_atomic_state *state)
570 {
571 }
572 
573 
574 void vmw_du_crtc_atomic_flush(struct drm_crtc *crtc,
575 			      struct drm_atomic_state *state)
576 {
577 	struct drm_pending_vblank_event *event = crtc->state->event;
578 
579 	if (event) {
580 		crtc->state->event = NULL;
581 
582 		spin_lock_irq(&crtc->dev->event_lock);
583 		drm_crtc_send_vblank_event(crtc, event);
584 		spin_unlock_irq(&crtc->dev->event_lock);
585 	}
586 }
587 
588 
589 /**
590  * vmw_du_crtc_duplicate_state - duplicate crtc state
591  * @crtc: DRM crtc
592  *
593  * Allocates and returns a copy of the crtc state (both common and
594  * vmw-specific) for the specified crtc.
595  *
596  * Returns: The newly allocated crtc state, or NULL on failure.
597  */
598 struct drm_crtc_state *
599 vmw_du_crtc_duplicate_state(struct drm_crtc *crtc)
600 {
601 	struct drm_crtc_state *state;
602 	struct vmw_crtc_state *vcs;
603 
604 	if (WARN_ON(!crtc->state))
605 		return NULL;
606 
607 	vcs = kmemdup(crtc->state, sizeof(*vcs), GFP_KERNEL);
608 
609 	if (!vcs)
610 		return NULL;
611 
612 	state = &vcs->base;
613 
614 	__drm_atomic_helper_crtc_duplicate_state(crtc, state);
615 
616 	return state;
617 }
618 
619 
620 /**
621  * vmw_du_crtc_reset - creates a blank vmw crtc state
622  * @crtc: DRM crtc
623  *
624  * Resets the atomic state for @crtc by freeing the state pointer (which
625  * might be NULL, e.g. at driver load time) and allocating a new empty state
626  * object.
627  */
628 void vmw_du_crtc_reset(struct drm_crtc *crtc)
629 {
630 	struct vmw_crtc_state *vcs;
631 
632 
633 	if (crtc->state) {
634 		__drm_atomic_helper_crtc_destroy_state(crtc->state);
635 
636 		kfree(vmw_crtc_state_to_vcs(crtc->state));
637 	}
638 
639 	vcs = kzalloc(sizeof(*vcs), GFP_KERNEL);
640 
641 	if (!vcs) {
642 		DRM_ERROR("Cannot allocate vmw_crtc_state\n");
643 		return;
644 	}
645 
646 	__drm_atomic_helper_crtc_reset(crtc, &vcs->base);
647 }
648 
649 
650 /**
651  * vmw_du_crtc_destroy_state - destroy crtc state
652  * @crtc: DRM crtc
653  * @state: state object to destroy
654  *
655  * Destroys the crtc state (both common and vmw-specific) for the
656  * specified plane.
657  */
658 void
659 vmw_du_crtc_destroy_state(struct drm_crtc *crtc,
660 			  struct drm_crtc_state *state)
661 {
662 	drm_atomic_helper_crtc_destroy_state(crtc, state);
663 }
664 
665 
666 /**
667  * vmw_du_plane_duplicate_state - duplicate plane state
668  * @plane: drm plane
669  *
670  * Allocates and returns a copy of the plane state (both common and
671  * vmw-specific) for the specified plane.
672  *
673  * Returns: The newly allocated plane state, or NULL on failure.
674  */
675 struct drm_plane_state *
676 vmw_du_plane_duplicate_state(struct drm_plane *plane)
677 {
678 	struct drm_plane_state *state;
679 	struct vmw_plane_state *vps;
680 
681 	vps = kmemdup(plane->state, sizeof(*vps), GFP_KERNEL);
682 
683 	if (!vps)
684 		return NULL;
685 
686 	vps->pinned = 0;
687 	vps->cpp = 0;
688 
689 	/* Each ref counted resource needs to be acquired again */
690 	if (vps->surf)
691 		(void) vmw_surface_reference(vps->surf);
692 
693 	if (vps->bo)
694 		(void) vmw_bo_reference(vps->bo);
695 
696 	state = &vps->base;
697 
698 	__drm_atomic_helper_plane_duplicate_state(plane, state);
699 
700 	return state;
701 }
702 
703 
704 /**
705  * vmw_du_plane_reset - creates a blank vmw plane state
706  * @plane: drm plane
707  *
708  * Resets the atomic state for @plane by freeing the state pointer (which might
709  * be NULL, e.g. at driver load time) and allocating a new empty state object.
710  */
711 void vmw_du_plane_reset(struct drm_plane *plane)
712 {
713 	struct vmw_plane_state *vps;
714 
715 
716 	if (plane->state)
717 		vmw_du_plane_destroy_state(plane, plane->state);
718 
719 	vps = kzalloc(sizeof(*vps), GFP_KERNEL);
720 
721 	if (!vps) {
722 		DRM_ERROR("Cannot allocate vmw_plane_state\n");
723 		return;
724 	}
725 
726 	__drm_atomic_helper_plane_reset(plane, &vps->base);
727 }
728 
729 
730 /**
731  * vmw_du_plane_destroy_state - destroy plane state
732  * @plane: DRM plane
733  * @state: state object to destroy
734  *
735  * Destroys the plane state (both common and vmw-specific) for the
736  * specified plane.
737  */
738 void
739 vmw_du_plane_destroy_state(struct drm_plane *plane,
740 			   struct drm_plane_state *state)
741 {
742 	struct vmw_plane_state *vps = vmw_plane_state_to_vps(state);
743 
744 
745 	/* Should have been freed by cleanup_fb */
746 	if (vps->surf)
747 		vmw_surface_unreference(&vps->surf);
748 
749 	if (vps->bo)
750 		vmw_bo_unreference(&vps->bo);
751 
752 	drm_atomic_helper_plane_destroy_state(plane, state);
753 }
754 
755 
756 /**
757  * vmw_du_connector_duplicate_state - duplicate connector state
758  * @connector: DRM connector
759  *
760  * Allocates and returns a copy of the connector state (both common and
761  * vmw-specific) for the specified connector.
762  *
763  * Returns: The newly allocated connector state, or NULL on failure.
764  */
765 struct drm_connector_state *
766 vmw_du_connector_duplicate_state(struct drm_connector *connector)
767 {
768 	struct drm_connector_state *state;
769 	struct vmw_connector_state *vcs;
770 
771 	if (WARN_ON(!connector->state))
772 		return NULL;
773 
774 	vcs = kmemdup(connector->state, sizeof(*vcs), GFP_KERNEL);
775 
776 	if (!vcs)
777 		return NULL;
778 
779 	state = &vcs->base;
780 
781 	__drm_atomic_helper_connector_duplicate_state(connector, state);
782 
783 	return state;
784 }
785 
786 
787 /**
788  * vmw_du_connector_reset - creates a blank vmw connector state
789  * @connector: DRM connector
790  *
791  * Resets the atomic state for @connector by freeing the state pointer (which
792  * might be NULL, e.g. at driver load time) and allocating a new empty state
793  * object.
794  */
795 void vmw_du_connector_reset(struct drm_connector *connector)
796 {
797 	struct vmw_connector_state *vcs;
798 
799 
800 	if (connector->state) {
801 		__drm_atomic_helper_connector_destroy_state(connector->state);
802 
803 		kfree(vmw_connector_state_to_vcs(connector->state));
804 	}
805 
806 	vcs = kzalloc(sizeof(*vcs), GFP_KERNEL);
807 
808 	if (!vcs) {
809 		DRM_ERROR("Cannot allocate vmw_connector_state\n");
810 		return;
811 	}
812 
813 	__drm_atomic_helper_connector_reset(connector, &vcs->base);
814 }
815 
816 
817 /**
818  * vmw_du_connector_destroy_state - destroy connector state
819  * @connector: DRM connector
820  * @state: state object to destroy
821  *
822  * Destroys the connector state (both common and vmw-specific) for the
823  * specified plane.
824  */
825 void
826 vmw_du_connector_destroy_state(struct drm_connector *connector,
827 			  struct drm_connector_state *state)
828 {
829 	drm_atomic_helper_connector_destroy_state(connector, state);
830 }
831 /*
832  * Generic framebuffer code
833  */
834 
835 /*
836  * Surface framebuffer code
837  */
838 
839 static void vmw_framebuffer_surface_destroy(struct drm_framebuffer *framebuffer)
840 {
841 	struct vmw_framebuffer_surface *vfbs =
842 		vmw_framebuffer_to_vfbs(framebuffer);
843 
844 	drm_framebuffer_cleanup(framebuffer);
845 	vmw_surface_unreference(&vfbs->surface);
846 	if (vfbs->base.user_obj)
847 		ttm_base_object_unref(&vfbs->base.user_obj);
848 
849 	kfree(vfbs);
850 }
851 
852 /**
853  * vmw_kms_readback - Perform a readback from the screen system to
854  * a buffer-object backed framebuffer.
855  *
856  * @dev_priv: Pointer to the device private structure.
857  * @file_priv: Pointer to a struct drm_file identifying the caller.
858  * Must be set to NULL if @user_fence_rep is NULL.
859  * @vfb: Pointer to the buffer-object backed framebuffer.
860  * @user_fence_rep: User-space provided structure for fence information.
861  * Must be set to non-NULL if @file_priv is non-NULL.
862  * @vclips: Array of clip rects.
863  * @num_clips: Number of clip rects in @vclips.
864  *
865  * Returns 0 on success, negative error code on failure. -ERESTARTSYS if
866  * interrupted.
867  */
868 int vmw_kms_readback(struct vmw_private *dev_priv,
869 		     struct drm_file *file_priv,
870 		     struct vmw_framebuffer *vfb,
871 		     struct drm_vmw_fence_rep __user *user_fence_rep,
872 		     struct drm_vmw_rect *vclips,
873 		     uint32_t num_clips)
874 {
875 	switch (dev_priv->active_display_unit) {
876 	case vmw_du_screen_object:
877 		return vmw_kms_sou_readback(dev_priv, file_priv, vfb,
878 					    user_fence_rep, vclips, num_clips,
879 					    NULL);
880 	case vmw_du_screen_target:
881 		return vmw_kms_stdu_dma(dev_priv, file_priv, vfb,
882 					user_fence_rep, NULL, vclips, num_clips,
883 					1, false, true, NULL);
884 	default:
885 		WARN_ONCE(true,
886 			  "Readback called with invalid display system.\n");
887 }
888 
889 	return -ENOSYS;
890 }
891 
892 
893 static const struct drm_framebuffer_funcs vmw_framebuffer_surface_funcs = {
894 	.destroy = vmw_framebuffer_surface_destroy,
895 	.dirty = drm_atomic_helper_dirtyfb,
896 };
897 
898 static int vmw_kms_new_framebuffer_surface(struct vmw_private *dev_priv,
899 					   struct vmw_surface *surface,
900 					   struct vmw_framebuffer **out,
901 					   const struct drm_mode_fb_cmd2
902 					   *mode_cmd,
903 					   bool is_bo_proxy)
904 
905 {
906 	struct drm_device *dev = &dev_priv->drm;
907 	struct vmw_framebuffer_surface *vfbs;
908 	enum SVGA3dSurfaceFormat format;
909 	int ret;
910 
911 	/* 3D is only supported on HWv8 and newer hosts */
912 	if (dev_priv->active_display_unit == vmw_du_legacy)
913 		return -ENOSYS;
914 
915 	/*
916 	 * Sanity checks.
917 	 */
918 
919 	/* Surface must be marked as a scanout. */
920 	if (unlikely(!surface->metadata.scanout))
921 		return -EINVAL;
922 
923 	if (unlikely(surface->metadata.mip_levels[0] != 1 ||
924 		     surface->metadata.num_sizes != 1 ||
925 		     surface->metadata.base_size.width < mode_cmd->width ||
926 		     surface->metadata.base_size.height < mode_cmd->height ||
927 		     surface->metadata.base_size.depth != 1)) {
928 		DRM_ERROR("Incompatible surface dimensions "
929 			  "for requested mode.\n");
930 		return -EINVAL;
931 	}
932 
933 	switch (mode_cmd->pixel_format) {
934 	case DRM_FORMAT_ARGB8888:
935 		format = SVGA3D_A8R8G8B8;
936 		break;
937 	case DRM_FORMAT_XRGB8888:
938 		format = SVGA3D_X8R8G8B8;
939 		break;
940 	case DRM_FORMAT_RGB565:
941 		format = SVGA3D_R5G6B5;
942 		break;
943 	case DRM_FORMAT_XRGB1555:
944 		format = SVGA3D_A1R5G5B5;
945 		break;
946 	default:
947 		DRM_ERROR("Invalid pixel format: %p4cc\n",
948 			  &mode_cmd->pixel_format);
949 		return -EINVAL;
950 	}
951 
952 	/*
953 	 * For DX, surface format validation is done when surface->scanout
954 	 * is set.
955 	 */
956 	if (!has_sm4_context(dev_priv) && format != surface->metadata.format) {
957 		DRM_ERROR("Invalid surface format for requested mode.\n");
958 		return -EINVAL;
959 	}
960 
961 	vfbs = kzalloc(sizeof(*vfbs), GFP_KERNEL);
962 	if (!vfbs) {
963 		ret = -ENOMEM;
964 		goto out_err1;
965 	}
966 
967 	drm_helper_mode_fill_fb_struct(dev, &vfbs->base.base, mode_cmd);
968 	vfbs->surface = vmw_surface_reference(surface);
969 	vfbs->base.user_handle = mode_cmd->handles[0];
970 	vfbs->is_bo_proxy = is_bo_proxy;
971 
972 	*out = &vfbs->base;
973 
974 	ret = drm_framebuffer_init(dev, &vfbs->base.base,
975 				   &vmw_framebuffer_surface_funcs);
976 	if (ret)
977 		goto out_err2;
978 
979 	return 0;
980 
981 out_err2:
982 	vmw_surface_unreference(&surface);
983 	kfree(vfbs);
984 out_err1:
985 	return ret;
986 }
987 
988 /*
989  * Buffer-object framebuffer code
990  */
991 
992 static void vmw_framebuffer_bo_destroy(struct drm_framebuffer *framebuffer)
993 {
994 	struct vmw_framebuffer_bo *vfbd =
995 		vmw_framebuffer_to_vfbd(framebuffer);
996 
997 	drm_framebuffer_cleanup(framebuffer);
998 	vmw_bo_unreference(&vfbd->buffer);
999 	if (vfbd->base.user_obj)
1000 		ttm_base_object_unref(&vfbd->base.user_obj);
1001 
1002 	kfree(vfbd);
1003 }
1004 
1005 static int vmw_framebuffer_bo_dirty(struct drm_framebuffer *framebuffer,
1006 				    struct drm_file *file_priv,
1007 				    unsigned int flags, unsigned int color,
1008 				    struct drm_clip_rect *clips,
1009 				    unsigned int num_clips)
1010 {
1011 	struct vmw_private *dev_priv = vmw_priv(framebuffer->dev);
1012 	struct vmw_framebuffer_bo *vfbd =
1013 		vmw_framebuffer_to_vfbd(framebuffer);
1014 	struct drm_clip_rect norect;
1015 	int ret, increment = 1;
1016 
1017 	drm_modeset_lock_all(&dev_priv->drm);
1018 
1019 	if (!num_clips) {
1020 		num_clips = 1;
1021 		clips = &norect;
1022 		norect.x1 = norect.y1 = 0;
1023 		norect.x2 = framebuffer->width;
1024 		norect.y2 = framebuffer->height;
1025 	} else if (flags & DRM_MODE_FB_DIRTY_ANNOTATE_COPY) {
1026 		num_clips /= 2;
1027 		increment = 2;
1028 	}
1029 
1030 	switch (dev_priv->active_display_unit) {
1031 	case vmw_du_legacy:
1032 		ret = vmw_kms_ldu_do_bo_dirty(dev_priv, &vfbd->base, 0, 0,
1033 					      clips, num_clips, increment);
1034 		break;
1035 	default:
1036 		ret = -EINVAL;
1037 		WARN_ONCE(true, "Dirty called with invalid display system.\n");
1038 		break;
1039 	}
1040 
1041 	vmw_cmd_flush(dev_priv, false);
1042 
1043 	drm_modeset_unlock_all(&dev_priv->drm);
1044 
1045 	return ret;
1046 }
1047 
1048 static int vmw_framebuffer_bo_dirty_ext(struct drm_framebuffer *framebuffer,
1049 					struct drm_file *file_priv,
1050 					unsigned int flags, unsigned int color,
1051 					struct drm_clip_rect *clips,
1052 					unsigned int num_clips)
1053 {
1054 	struct vmw_private *dev_priv = vmw_priv(framebuffer->dev);
1055 
1056 	if (dev_priv->active_display_unit == vmw_du_legacy &&
1057 	    vmw_cmd_supported(dev_priv))
1058 		return vmw_framebuffer_bo_dirty(framebuffer, file_priv, flags,
1059 						color, clips, num_clips);
1060 
1061 	return drm_atomic_helper_dirtyfb(framebuffer, file_priv, flags, color,
1062 					 clips, num_clips);
1063 }
1064 
1065 static const struct drm_framebuffer_funcs vmw_framebuffer_bo_funcs = {
1066 	.destroy = vmw_framebuffer_bo_destroy,
1067 	.dirty = vmw_framebuffer_bo_dirty_ext,
1068 };
1069 
1070 /*
1071  * Pin the bofer in a location suitable for access by the
1072  * display system.
1073  */
1074 static int vmw_framebuffer_pin(struct vmw_framebuffer *vfb)
1075 {
1076 	struct vmw_private *dev_priv = vmw_priv(vfb->base.dev);
1077 	struct vmw_buffer_object *buf;
1078 	struct ttm_placement *placement;
1079 	int ret;
1080 
1081 	buf = vfb->bo ?  vmw_framebuffer_to_vfbd(&vfb->base)->buffer :
1082 		vmw_framebuffer_to_vfbs(&vfb->base)->surface->res.backup;
1083 
1084 	if (!buf)
1085 		return 0;
1086 
1087 	switch (dev_priv->active_display_unit) {
1088 	case vmw_du_legacy:
1089 		vmw_overlay_pause_all(dev_priv);
1090 		ret = vmw_bo_pin_in_start_of_vram(dev_priv, buf, false);
1091 		vmw_overlay_resume_all(dev_priv);
1092 		break;
1093 	case vmw_du_screen_object:
1094 	case vmw_du_screen_target:
1095 		if (vfb->bo) {
1096 			if (dev_priv->capabilities & SVGA_CAP_3D) {
1097 				/*
1098 				 * Use surface DMA to get content to
1099 				 * sreen target surface.
1100 				 */
1101 				placement = &vmw_vram_gmr_placement;
1102 			} else {
1103 				/* Use CPU blit. */
1104 				placement = &vmw_sys_placement;
1105 			}
1106 		} else {
1107 			/* Use surface / image update */
1108 			placement = &vmw_mob_placement;
1109 		}
1110 
1111 		return vmw_bo_pin_in_placement(dev_priv, buf, placement, false);
1112 	default:
1113 		return -EINVAL;
1114 	}
1115 
1116 	return ret;
1117 }
1118 
1119 static int vmw_framebuffer_unpin(struct vmw_framebuffer *vfb)
1120 {
1121 	struct vmw_private *dev_priv = vmw_priv(vfb->base.dev);
1122 	struct vmw_buffer_object *buf;
1123 
1124 	buf = vfb->bo ?  vmw_framebuffer_to_vfbd(&vfb->base)->buffer :
1125 		vmw_framebuffer_to_vfbs(&vfb->base)->surface->res.backup;
1126 
1127 	if (WARN_ON(!buf))
1128 		return 0;
1129 
1130 	return vmw_bo_unpin(dev_priv, buf, false);
1131 }
1132 
1133 /**
1134  * vmw_create_bo_proxy - create a proxy surface for the buffer object
1135  *
1136  * @dev: DRM device
1137  * @mode_cmd: parameters for the new surface
1138  * @bo_mob: MOB backing the buffer object
1139  * @srf_out: newly created surface
1140  *
1141  * When the content FB is a buffer object, we create a surface as a proxy to the
1142  * same buffer.  This way we can do a surface copy rather than a surface DMA.
1143  * This is a more efficient approach
1144  *
1145  * RETURNS:
1146  * 0 on success, error code otherwise
1147  */
1148 static int vmw_create_bo_proxy(struct drm_device *dev,
1149 			       const struct drm_mode_fb_cmd2 *mode_cmd,
1150 			       struct vmw_buffer_object *bo_mob,
1151 			       struct vmw_surface **srf_out)
1152 {
1153 	struct vmw_surface_metadata metadata = {0};
1154 	uint32_t format;
1155 	struct vmw_resource *res;
1156 	unsigned int bytes_pp;
1157 	int ret;
1158 
1159 	switch (mode_cmd->pixel_format) {
1160 	case DRM_FORMAT_ARGB8888:
1161 	case DRM_FORMAT_XRGB8888:
1162 		format = SVGA3D_X8R8G8B8;
1163 		bytes_pp = 4;
1164 		break;
1165 
1166 	case DRM_FORMAT_RGB565:
1167 	case DRM_FORMAT_XRGB1555:
1168 		format = SVGA3D_R5G6B5;
1169 		bytes_pp = 2;
1170 		break;
1171 
1172 	case 8:
1173 		format = SVGA3D_P8;
1174 		bytes_pp = 1;
1175 		break;
1176 
1177 	default:
1178 		DRM_ERROR("Invalid framebuffer format %p4cc\n",
1179 			  &mode_cmd->pixel_format);
1180 		return -EINVAL;
1181 	}
1182 
1183 	metadata.format = format;
1184 	metadata.mip_levels[0] = 1;
1185 	metadata.num_sizes = 1;
1186 	metadata.base_size.width = mode_cmd->pitches[0] / bytes_pp;
1187 	metadata.base_size.height =  mode_cmd->height;
1188 	metadata.base_size.depth = 1;
1189 	metadata.scanout = true;
1190 
1191 	ret = vmw_gb_surface_define(vmw_priv(dev), 0, &metadata, srf_out);
1192 	if (ret) {
1193 		DRM_ERROR("Failed to allocate proxy content buffer\n");
1194 		return ret;
1195 	}
1196 
1197 	res = &(*srf_out)->res;
1198 
1199 	/* Reserve and switch the backing mob. */
1200 	mutex_lock(&res->dev_priv->cmdbuf_mutex);
1201 	(void) vmw_resource_reserve(res, false, true);
1202 	vmw_bo_unreference(&res->backup);
1203 	res->backup = vmw_bo_reference(bo_mob);
1204 	res->backup_offset = 0;
1205 	vmw_resource_unreserve(res, false, false, false, NULL, 0);
1206 	mutex_unlock(&res->dev_priv->cmdbuf_mutex);
1207 
1208 	return 0;
1209 }
1210 
1211 
1212 
1213 static int vmw_kms_new_framebuffer_bo(struct vmw_private *dev_priv,
1214 				      struct vmw_buffer_object *bo,
1215 				      struct vmw_framebuffer **out,
1216 				      const struct drm_mode_fb_cmd2
1217 				      *mode_cmd)
1218 
1219 {
1220 	struct drm_device *dev = &dev_priv->drm;
1221 	struct vmw_framebuffer_bo *vfbd;
1222 	unsigned int requested_size;
1223 	int ret;
1224 
1225 	requested_size = mode_cmd->height * mode_cmd->pitches[0];
1226 	if (unlikely(requested_size > bo->base.base.size)) {
1227 		DRM_ERROR("Screen buffer object size is too small "
1228 			  "for requested mode.\n");
1229 		return -EINVAL;
1230 	}
1231 
1232 	/* Limited framebuffer color depth support for screen objects */
1233 	if (dev_priv->active_display_unit == vmw_du_screen_object) {
1234 		switch (mode_cmd->pixel_format) {
1235 		case DRM_FORMAT_XRGB8888:
1236 		case DRM_FORMAT_ARGB8888:
1237 			break;
1238 		case DRM_FORMAT_XRGB1555:
1239 		case DRM_FORMAT_RGB565:
1240 			break;
1241 		default:
1242 			DRM_ERROR("Invalid pixel format: %p4cc\n",
1243 				  &mode_cmd->pixel_format);
1244 			return -EINVAL;
1245 		}
1246 	}
1247 
1248 	vfbd = kzalloc(sizeof(*vfbd), GFP_KERNEL);
1249 	if (!vfbd) {
1250 		ret = -ENOMEM;
1251 		goto out_err1;
1252 	}
1253 
1254 	drm_helper_mode_fill_fb_struct(dev, &vfbd->base.base, mode_cmd);
1255 	vfbd->base.bo = true;
1256 	vfbd->buffer = vmw_bo_reference(bo);
1257 	vfbd->base.user_handle = mode_cmd->handles[0];
1258 	*out = &vfbd->base;
1259 
1260 	ret = drm_framebuffer_init(dev, &vfbd->base.base,
1261 				   &vmw_framebuffer_bo_funcs);
1262 	if (ret)
1263 		goto out_err2;
1264 
1265 	return 0;
1266 
1267 out_err2:
1268 	vmw_bo_unreference(&bo);
1269 	kfree(vfbd);
1270 out_err1:
1271 	return ret;
1272 }
1273 
1274 
1275 /**
1276  * vmw_kms_srf_ok - check if a surface can be created
1277  *
1278  * @dev_priv: Pointer to device private struct.
1279  * @width: requested width
1280  * @height: requested height
1281  *
1282  * Surfaces need to be less than texture size
1283  */
1284 static bool
1285 vmw_kms_srf_ok(struct vmw_private *dev_priv, uint32_t width, uint32_t height)
1286 {
1287 	if (width  > dev_priv->texture_max_width ||
1288 	    height > dev_priv->texture_max_height)
1289 		return false;
1290 
1291 	return true;
1292 }
1293 
1294 /**
1295  * vmw_kms_new_framebuffer - Create a new framebuffer.
1296  *
1297  * @dev_priv: Pointer to device private struct.
1298  * @bo: Pointer to buffer object to wrap the kms framebuffer around.
1299  * Either @bo or @surface must be NULL.
1300  * @surface: Pointer to a surface to wrap the kms framebuffer around.
1301  * Either @bo or @surface must be NULL.
1302  * @only_2d: No presents will occur to this buffer object based framebuffer.
1303  * This helps the code to do some important optimizations.
1304  * @mode_cmd: Frame-buffer metadata.
1305  */
1306 struct vmw_framebuffer *
1307 vmw_kms_new_framebuffer(struct vmw_private *dev_priv,
1308 			struct vmw_buffer_object *bo,
1309 			struct vmw_surface *surface,
1310 			bool only_2d,
1311 			const struct drm_mode_fb_cmd2 *mode_cmd)
1312 {
1313 	struct vmw_framebuffer *vfb = NULL;
1314 	bool is_bo_proxy = false;
1315 	int ret;
1316 
1317 	/*
1318 	 * We cannot use the SurfaceDMA command in an non-accelerated VM,
1319 	 * therefore, wrap the buffer object in a surface so we can use the
1320 	 * SurfaceCopy command.
1321 	 */
1322 	if (vmw_kms_srf_ok(dev_priv, mode_cmd->width, mode_cmd->height)  &&
1323 	    bo && only_2d &&
1324 	    mode_cmd->width > 64 &&  /* Don't create a proxy for cursor */
1325 	    dev_priv->active_display_unit == vmw_du_screen_target) {
1326 		ret = vmw_create_bo_proxy(&dev_priv->drm, mode_cmd,
1327 					  bo, &surface);
1328 		if (ret)
1329 			return ERR_PTR(ret);
1330 
1331 		is_bo_proxy = true;
1332 	}
1333 
1334 	/* Create the new framebuffer depending one what we have */
1335 	if (surface) {
1336 		ret = vmw_kms_new_framebuffer_surface(dev_priv, surface, &vfb,
1337 						      mode_cmd,
1338 						      is_bo_proxy);
1339 
1340 		/*
1341 		 * vmw_create_bo_proxy() adds a reference that is no longer
1342 		 * needed
1343 		 */
1344 		if (is_bo_proxy)
1345 			vmw_surface_unreference(&surface);
1346 	} else if (bo) {
1347 		ret = vmw_kms_new_framebuffer_bo(dev_priv, bo, &vfb,
1348 						 mode_cmd);
1349 	} else {
1350 		BUG();
1351 	}
1352 
1353 	if (ret)
1354 		return ERR_PTR(ret);
1355 
1356 	vfb->pin = vmw_framebuffer_pin;
1357 	vfb->unpin = vmw_framebuffer_unpin;
1358 
1359 	return vfb;
1360 }
1361 
1362 /*
1363  * Generic Kernel modesetting functions
1364  */
1365 
1366 static struct drm_framebuffer *vmw_kms_fb_create(struct drm_device *dev,
1367 						 struct drm_file *file_priv,
1368 						 const struct drm_mode_fb_cmd2 *mode_cmd)
1369 {
1370 	struct vmw_private *dev_priv = vmw_priv(dev);
1371 	struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile;
1372 	struct vmw_framebuffer *vfb = NULL;
1373 	struct vmw_surface *surface = NULL;
1374 	struct vmw_buffer_object *bo = NULL;
1375 	struct ttm_base_object *user_obj;
1376 	int ret;
1377 
1378 	/*
1379 	 * Take a reference on the user object of the resource
1380 	 * backing the kms fb. This ensures that user-space handle
1381 	 * lookups on that resource will always work as long as
1382 	 * it's registered with a kms framebuffer. This is important,
1383 	 * since vmw_execbuf_process identifies resources in the
1384 	 * command stream using user-space handles.
1385 	 */
1386 
1387 	user_obj = ttm_base_object_lookup(tfile, mode_cmd->handles[0]);
1388 	if (unlikely(user_obj == NULL)) {
1389 		DRM_ERROR("Could not locate requested kms frame buffer.\n");
1390 		return ERR_PTR(-ENOENT);
1391 	}
1392 
1393 	/**
1394 	 * End conditioned code.
1395 	 */
1396 
1397 	/* returns either a bo or surface */
1398 	ret = vmw_user_lookup_handle(dev_priv, tfile,
1399 				     mode_cmd->handles[0],
1400 				     &surface, &bo);
1401 	if (ret)
1402 		goto err_out;
1403 
1404 
1405 	if (!bo &&
1406 	    !vmw_kms_srf_ok(dev_priv, mode_cmd->width, mode_cmd->height)) {
1407 		DRM_ERROR("Surface size cannot exceed %dx%d",
1408 			dev_priv->texture_max_width,
1409 			dev_priv->texture_max_height);
1410 		goto err_out;
1411 	}
1412 
1413 
1414 	vfb = vmw_kms_new_framebuffer(dev_priv, bo, surface,
1415 				      !(dev_priv->capabilities & SVGA_CAP_3D),
1416 				      mode_cmd);
1417 	if (IS_ERR(vfb)) {
1418 		ret = PTR_ERR(vfb);
1419 		goto err_out;
1420  	}
1421 
1422 err_out:
1423 	/* vmw_user_lookup_handle takes one ref so does new_fb */
1424 	if (bo)
1425 		vmw_bo_unreference(&bo);
1426 	if (surface)
1427 		vmw_surface_unreference(&surface);
1428 
1429 	if (ret) {
1430 		DRM_ERROR("failed to create vmw_framebuffer: %i\n", ret);
1431 		ttm_base_object_unref(&user_obj);
1432 		return ERR_PTR(ret);
1433 	} else
1434 		vfb->user_obj = user_obj;
1435 
1436 	return &vfb->base;
1437 }
1438 
1439 /**
1440  * vmw_kms_check_display_memory - Validates display memory required for a
1441  * topology
1442  * @dev: DRM device
1443  * @num_rects: number of drm_rect in rects
1444  * @rects: array of drm_rect representing the topology to validate indexed by
1445  * crtc index.
1446  *
1447  * Returns:
1448  * 0 on success otherwise negative error code
1449  */
1450 static int vmw_kms_check_display_memory(struct drm_device *dev,
1451 					uint32_t num_rects,
1452 					struct drm_rect *rects)
1453 {
1454 	struct vmw_private *dev_priv = vmw_priv(dev);
1455 	struct drm_rect bounding_box = {0};
1456 	u64 total_pixels = 0, pixel_mem, bb_mem;
1457 	int i;
1458 
1459 	for (i = 0; i < num_rects; i++) {
1460 		/*
1461 		 * For STDU only individual screen (screen target) is limited by
1462 		 * SCREENTARGET_MAX_WIDTH/HEIGHT registers.
1463 		 */
1464 		if (dev_priv->active_display_unit == vmw_du_screen_target &&
1465 		    (drm_rect_width(&rects[i]) > dev_priv->stdu_max_width ||
1466 		     drm_rect_height(&rects[i]) > dev_priv->stdu_max_height)) {
1467 			VMW_DEBUG_KMS("Screen size not supported.\n");
1468 			return -EINVAL;
1469 		}
1470 
1471 		/* Bounding box upper left is at (0,0). */
1472 		if (rects[i].x2 > bounding_box.x2)
1473 			bounding_box.x2 = rects[i].x2;
1474 
1475 		if (rects[i].y2 > bounding_box.y2)
1476 			bounding_box.y2 = rects[i].y2;
1477 
1478 		total_pixels += (u64) drm_rect_width(&rects[i]) *
1479 			(u64) drm_rect_height(&rects[i]);
1480 	}
1481 
1482 	/* Virtual svga device primary limits are always in 32-bpp. */
1483 	pixel_mem = total_pixels * 4;
1484 
1485 	/*
1486 	 * For HV10 and below prim_bb_mem is vram size. When
1487 	 * SVGA_REG_MAX_PRIMARY_BOUNDING_BOX_MEM is not present vram size is
1488 	 * limit on primary bounding box
1489 	 */
1490 	if (pixel_mem > dev_priv->max_primary_mem) {
1491 		VMW_DEBUG_KMS("Combined output size too large.\n");
1492 		return -EINVAL;
1493 	}
1494 
1495 	/* SVGA_CAP_NO_BB_RESTRICTION is available for STDU only. */
1496 	if (dev_priv->active_display_unit != vmw_du_screen_target ||
1497 	    !(dev_priv->capabilities & SVGA_CAP_NO_BB_RESTRICTION)) {
1498 		bb_mem = (u64) bounding_box.x2 * bounding_box.y2 * 4;
1499 
1500 		if (bb_mem > dev_priv->max_primary_mem) {
1501 			VMW_DEBUG_KMS("Topology is beyond supported limits.\n");
1502 			return -EINVAL;
1503 		}
1504 	}
1505 
1506 	return 0;
1507 }
1508 
1509 /**
1510  * vmw_crtc_state_and_lock - Return new or current crtc state with locked
1511  * crtc mutex
1512  * @state: The atomic state pointer containing the new atomic state
1513  * @crtc: The crtc
1514  *
1515  * This function returns the new crtc state if it's part of the state update.
1516  * Otherwise returns the current crtc state. It also makes sure that the
1517  * crtc mutex is locked.
1518  *
1519  * Returns: A valid crtc state pointer or NULL. It may also return a
1520  * pointer error, in particular -EDEADLK if locking needs to be rerun.
1521  */
1522 static struct drm_crtc_state *
1523 vmw_crtc_state_and_lock(struct drm_atomic_state *state, struct drm_crtc *crtc)
1524 {
1525 	struct drm_crtc_state *crtc_state;
1526 
1527 	crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
1528 	if (crtc_state) {
1529 		lockdep_assert_held(&crtc->mutex.mutex.base);
1530 	} else {
1531 		int ret = drm_modeset_lock(&crtc->mutex, state->acquire_ctx);
1532 
1533 		if (ret != 0 && ret != -EALREADY)
1534 			return ERR_PTR(ret);
1535 
1536 		crtc_state = crtc->state;
1537 	}
1538 
1539 	return crtc_state;
1540 }
1541 
1542 /**
1543  * vmw_kms_check_implicit - Verify that all implicit display units scan out
1544  * from the same fb after the new state is committed.
1545  * @dev: The drm_device.
1546  * @state: The new state to be checked.
1547  *
1548  * Returns:
1549  *   Zero on success,
1550  *   -EINVAL on invalid state,
1551  *   -EDEADLK if modeset locking needs to be rerun.
1552  */
1553 static int vmw_kms_check_implicit(struct drm_device *dev,
1554 				  struct drm_atomic_state *state)
1555 {
1556 	struct drm_framebuffer *implicit_fb = NULL;
1557 	struct drm_crtc *crtc;
1558 	struct drm_crtc_state *crtc_state;
1559 	struct drm_plane_state *plane_state;
1560 
1561 	drm_for_each_crtc(crtc, dev) {
1562 		struct vmw_display_unit *du = vmw_crtc_to_du(crtc);
1563 
1564 		if (!du->is_implicit)
1565 			continue;
1566 
1567 		crtc_state = vmw_crtc_state_and_lock(state, crtc);
1568 		if (IS_ERR(crtc_state))
1569 			return PTR_ERR(crtc_state);
1570 
1571 		if (!crtc_state || !crtc_state->enable)
1572 			continue;
1573 
1574 		/*
1575 		 * Can't move primary planes across crtcs, so this is OK.
1576 		 * It also means we don't need to take the plane mutex.
1577 		 */
1578 		plane_state = du->primary.state;
1579 		if (plane_state->crtc != crtc)
1580 			continue;
1581 
1582 		if (!implicit_fb)
1583 			implicit_fb = plane_state->fb;
1584 		else if (implicit_fb != plane_state->fb)
1585 			return -EINVAL;
1586 	}
1587 
1588 	return 0;
1589 }
1590 
1591 /**
1592  * vmw_kms_check_topology - Validates topology in drm_atomic_state
1593  * @dev: DRM device
1594  * @state: the driver state object
1595  *
1596  * Returns:
1597  * 0 on success otherwise negative error code
1598  */
1599 static int vmw_kms_check_topology(struct drm_device *dev,
1600 				  struct drm_atomic_state *state)
1601 {
1602 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
1603 	struct drm_rect *rects;
1604 	struct drm_crtc *crtc;
1605 	uint32_t i;
1606 	int ret = 0;
1607 
1608 	rects = kcalloc(dev->mode_config.num_crtc, sizeof(struct drm_rect),
1609 			GFP_KERNEL);
1610 	if (!rects)
1611 		return -ENOMEM;
1612 
1613 	drm_for_each_crtc(crtc, dev) {
1614 		struct vmw_display_unit *du = vmw_crtc_to_du(crtc);
1615 		struct drm_crtc_state *crtc_state;
1616 
1617 		i = drm_crtc_index(crtc);
1618 
1619 		crtc_state = vmw_crtc_state_and_lock(state, crtc);
1620 		if (IS_ERR(crtc_state)) {
1621 			ret = PTR_ERR(crtc_state);
1622 			goto clean;
1623 		}
1624 
1625 		if (!crtc_state)
1626 			continue;
1627 
1628 		if (crtc_state->enable) {
1629 			rects[i].x1 = du->gui_x;
1630 			rects[i].y1 = du->gui_y;
1631 			rects[i].x2 = du->gui_x + crtc_state->mode.hdisplay;
1632 			rects[i].y2 = du->gui_y + crtc_state->mode.vdisplay;
1633 		} else {
1634 			rects[i].x1 = 0;
1635 			rects[i].y1 = 0;
1636 			rects[i].x2 = 0;
1637 			rects[i].y2 = 0;
1638 		}
1639 	}
1640 
1641 	/* Determine change to topology due to new atomic state */
1642 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
1643 				      new_crtc_state, i) {
1644 		struct vmw_display_unit *du = vmw_crtc_to_du(crtc);
1645 		struct drm_connector *connector;
1646 		struct drm_connector_state *conn_state;
1647 		struct vmw_connector_state *vmw_conn_state;
1648 
1649 		if (!du->pref_active && new_crtc_state->enable) {
1650 			VMW_DEBUG_KMS("Enabling a disabled display unit\n");
1651 			ret = -EINVAL;
1652 			goto clean;
1653 		}
1654 
1655 		/*
1656 		 * For vmwgfx each crtc has only one connector attached and it
1657 		 * is not changed so don't really need to check the
1658 		 * crtc->connector_mask and iterate over it.
1659 		 */
1660 		connector = &du->connector;
1661 		conn_state = drm_atomic_get_connector_state(state, connector);
1662 		if (IS_ERR(conn_state)) {
1663 			ret = PTR_ERR(conn_state);
1664 			goto clean;
1665 		}
1666 
1667 		vmw_conn_state = vmw_connector_state_to_vcs(conn_state);
1668 		vmw_conn_state->gui_x = du->gui_x;
1669 		vmw_conn_state->gui_y = du->gui_y;
1670 	}
1671 
1672 	ret = vmw_kms_check_display_memory(dev, dev->mode_config.num_crtc,
1673 					   rects);
1674 
1675 clean:
1676 	kfree(rects);
1677 	return ret;
1678 }
1679 
1680 /**
1681  * vmw_kms_atomic_check_modeset- validate state object for modeset changes
1682  *
1683  * @dev: DRM device
1684  * @state: the driver state object
1685  *
1686  * This is a simple wrapper around drm_atomic_helper_check_modeset() for
1687  * us to assign a value to mode->crtc_clock so that
1688  * drm_calc_timestamping_constants() won't throw an error message
1689  *
1690  * Returns:
1691  * Zero for success or -errno
1692  */
1693 static int
1694 vmw_kms_atomic_check_modeset(struct drm_device *dev,
1695 			     struct drm_atomic_state *state)
1696 {
1697 	struct drm_crtc *crtc;
1698 	struct drm_crtc_state *crtc_state;
1699 	bool need_modeset = false;
1700 	int i, ret;
1701 
1702 	ret = drm_atomic_helper_check(dev, state);
1703 	if (ret)
1704 		return ret;
1705 
1706 	ret = vmw_kms_check_implicit(dev, state);
1707 	if (ret) {
1708 		VMW_DEBUG_KMS("Invalid implicit state\n");
1709 		return ret;
1710 	}
1711 
1712 	for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
1713 		if (drm_atomic_crtc_needs_modeset(crtc_state))
1714 			need_modeset = true;
1715 	}
1716 
1717 	if (need_modeset)
1718 		return vmw_kms_check_topology(dev, state);
1719 
1720 	return ret;
1721 }
1722 
1723 static const struct drm_mode_config_funcs vmw_kms_funcs = {
1724 	.fb_create = vmw_kms_fb_create,
1725 	.atomic_check = vmw_kms_atomic_check_modeset,
1726 	.atomic_commit = drm_atomic_helper_commit,
1727 };
1728 
1729 static int vmw_kms_generic_present(struct vmw_private *dev_priv,
1730 				   struct drm_file *file_priv,
1731 				   struct vmw_framebuffer *vfb,
1732 				   struct vmw_surface *surface,
1733 				   uint32_t sid,
1734 				   int32_t destX, int32_t destY,
1735 				   struct drm_vmw_rect *clips,
1736 				   uint32_t num_clips)
1737 {
1738 	return vmw_kms_sou_do_surface_dirty(dev_priv, vfb, NULL, clips,
1739 					    &surface->res, destX, destY,
1740 					    num_clips, 1, NULL, NULL);
1741 }
1742 
1743 
1744 int vmw_kms_present(struct vmw_private *dev_priv,
1745 		    struct drm_file *file_priv,
1746 		    struct vmw_framebuffer *vfb,
1747 		    struct vmw_surface *surface,
1748 		    uint32_t sid,
1749 		    int32_t destX, int32_t destY,
1750 		    struct drm_vmw_rect *clips,
1751 		    uint32_t num_clips)
1752 {
1753 	int ret;
1754 
1755 	switch (dev_priv->active_display_unit) {
1756 	case vmw_du_screen_target:
1757 		ret = vmw_kms_stdu_surface_dirty(dev_priv, vfb, NULL, clips,
1758 						 &surface->res, destX, destY,
1759 						 num_clips, 1, NULL, NULL);
1760 		break;
1761 	case vmw_du_screen_object:
1762 		ret = vmw_kms_generic_present(dev_priv, file_priv, vfb, surface,
1763 					      sid, destX, destY, clips,
1764 					      num_clips);
1765 		break;
1766 	default:
1767 		WARN_ONCE(true,
1768 			  "Present called with invalid display system.\n");
1769 		ret = -ENOSYS;
1770 		break;
1771 	}
1772 	if (ret)
1773 		return ret;
1774 
1775 	vmw_cmd_flush(dev_priv, false);
1776 
1777 	return 0;
1778 }
1779 
1780 static void
1781 vmw_kms_create_hotplug_mode_update_property(struct vmw_private *dev_priv)
1782 {
1783 	if (dev_priv->hotplug_mode_update_property)
1784 		return;
1785 
1786 	dev_priv->hotplug_mode_update_property =
1787 		drm_property_create_range(&dev_priv->drm,
1788 					  DRM_MODE_PROP_IMMUTABLE,
1789 					  "hotplug_mode_update", 0, 1);
1790 }
1791 
1792 int vmw_kms_init(struct vmw_private *dev_priv)
1793 {
1794 	struct drm_device *dev = &dev_priv->drm;
1795 	int ret;
1796 	static const char *display_unit_names[] = {
1797 		"Invalid",
1798 		"Legacy",
1799 		"Screen Object",
1800 		"Screen Target",
1801 		"Invalid (max)"
1802 	};
1803 
1804 	drm_mode_config_init(dev);
1805 	dev->mode_config.funcs = &vmw_kms_funcs;
1806 	dev->mode_config.min_width = 1;
1807 	dev->mode_config.min_height = 1;
1808 	dev->mode_config.max_width = dev_priv->texture_max_width;
1809 	dev->mode_config.max_height = dev_priv->texture_max_height;
1810 
1811 	drm_mode_create_suggested_offset_properties(dev);
1812 	vmw_kms_create_hotplug_mode_update_property(dev_priv);
1813 
1814 	ret = vmw_kms_stdu_init_display(dev_priv);
1815 	if (ret) {
1816 		ret = vmw_kms_sou_init_display(dev_priv);
1817 		if (ret) /* Fallback */
1818 			ret = vmw_kms_ldu_init_display(dev_priv);
1819 	}
1820 	BUILD_BUG_ON(ARRAY_SIZE(display_unit_names) != (vmw_du_max + 1));
1821 	drm_info(&dev_priv->drm, "%s display unit initialized\n",
1822 		 display_unit_names[dev_priv->active_display_unit]);
1823 
1824 	return ret;
1825 }
1826 
1827 int vmw_kms_close(struct vmw_private *dev_priv)
1828 {
1829 	int ret = 0;
1830 
1831 	/*
1832 	 * Docs says we should take the lock before calling this function
1833 	 * but since it destroys encoders and our destructor calls
1834 	 * drm_encoder_cleanup which takes the lock we deadlock.
1835 	 */
1836 	drm_mode_config_cleanup(&dev_priv->drm);
1837 	if (dev_priv->active_display_unit == vmw_du_legacy)
1838 		ret = vmw_kms_ldu_close_display(dev_priv);
1839 
1840 	return ret;
1841 }
1842 
1843 int vmw_kms_cursor_bypass_ioctl(struct drm_device *dev, void *data,
1844 				struct drm_file *file_priv)
1845 {
1846 	struct drm_vmw_cursor_bypass_arg *arg = data;
1847 	struct vmw_display_unit *du;
1848 	struct drm_crtc *crtc;
1849 	int ret = 0;
1850 
1851 
1852 	mutex_lock(&dev->mode_config.mutex);
1853 	if (arg->flags & DRM_VMW_CURSOR_BYPASS_ALL) {
1854 
1855 		list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
1856 			du = vmw_crtc_to_du(crtc);
1857 			du->hotspot_x = arg->xhot;
1858 			du->hotspot_y = arg->yhot;
1859 		}
1860 
1861 		mutex_unlock(&dev->mode_config.mutex);
1862 		return 0;
1863 	}
1864 
1865 	crtc = drm_crtc_find(dev, file_priv, arg->crtc_id);
1866 	if (!crtc) {
1867 		ret = -ENOENT;
1868 		goto out;
1869 	}
1870 
1871 	du = vmw_crtc_to_du(crtc);
1872 
1873 	du->hotspot_x = arg->xhot;
1874 	du->hotspot_y = arg->yhot;
1875 
1876 out:
1877 	mutex_unlock(&dev->mode_config.mutex);
1878 
1879 	return ret;
1880 }
1881 
1882 int vmw_kms_write_svga(struct vmw_private *vmw_priv,
1883 			unsigned width, unsigned height, unsigned pitch,
1884 			unsigned bpp, unsigned depth)
1885 {
1886 	if (vmw_priv->capabilities & SVGA_CAP_PITCHLOCK)
1887 		vmw_write(vmw_priv, SVGA_REG_PITCHLOCK, pitch);
1888 	else if (vmw_fifo_have_pitchlock(vmw_priv))
1889 		vmw_fifo_mem_write(vmw_priv, SVGA_FIFO_PITCHLOCK, pitch);
1890 	vmw_write(vmw_priv, SVGA_REG_WIDTH, width);
1891 	vmw_write(vmw_priv, SVGA_REG_HEIGHT, height);
1892 	if ((vmw_priv->capabilities & SVGA_CAP_8BIT_EMULATION) != 0)
1893 		vmw_write(vmw_priv, SVGA_REG_BITS_PER_PIXEL, bpp);
1894 
1895 	if (vmw_read(vmw_priv, SVGA_REG_DEPTH) != depth) {
1896 		DRM_ERROR("Invalid depth %u for %u bpp, host expects %u\n",
1897 			  depth, bpp, vmw_read(vmw_priv, SVGA_REG_DEPTH));
1898 		return -EINVAL;
1899 	}
1900 
1901 	return 0;
1902 }
1903 
1904 bool vmw_kms_validate_mode_vram(struct vmw_private *dev_priv,
1905 				uint32_t pitch,
1906 				uint32_t height)
1907 {
1908 	return ((u64) pitch * (u64) height) < (u64)
1909 		((dev_priv->active_display_unit == vmw_du_screen_target) ?
1910 		 dev_priv->max_primary_mem : dev_priv->vram_size);
1911 }
1912 
1913 
1914 /*
1915  * Function called by DRM code called with vbl_lock held.
1916  */
1917 u32 vmw_get_vblank_counter(struct drm_crtc *crtc)
1918 {
1919 	return 0;
1920 }
1921 
1922 /*
1923  * Function called by DRM code called with vbl_lock held.
1924  */
1925 int vmw_enable_vblank(struct drm_crtc *crtc)
1926 {
1927 	return -EINVAL;
1928 }
1929 
1930 /*
1931  * Function called by DRM code called with vbl_lock held.
1932  */
1933 void vmw_disable_vblank(struct drm_crtc *crtc)
1934 {
1935 }
1936 
1937 /**
1938  * vmw_du_update_layout - Update the display unit with topology from resolution
1939  * plugin and generate DRM uevent
1940  * @dev_priv: device private
1941  * @num_rects: number of drm_rect in rects
1942  * @rects: toplogy to update
1943  */
1944 static int vmw_du_update_layout(struct vmw_private *dev_priv,
1945 				unsigned int num_rects, struct drm_rect *rects)
1946 {
1947 	struct drm_device *dev = &dev_priv->drm;
1948 	struct vmw_display_unit *du;
1949 	struct drm_connector *con;
1950 	struct drm_connector_list_iter conn_iter;
1951 	struct drm_modeset_acquire_ctx ctx;
1952 	struct drm_crtc *crtc;
1953 	int ret;
1954 
1955 	/* Currently gui_x/y is protected with the crtc mutex */
1956 	mutex_lock(&dev->mode_config.mutex);
1957 	drm_modeset_acquire_init(&ctx, 0);
1958 retry:
1959 	drm_for_each_crtc(crtc, dev) {
1960 		ret = drm_modeset_lock(&crtc->mutex, &ctx);
1961 		if (ret < 0) {
1962 			if (ret == -EDEADLK) {
1963 				drm_modeset_backoff(&ctx);
1964 				goto retry;
1965       		}
1966 			goto out_fini;
1967 		}
1968 	}
1969 
1970 	drm_connector_list_iter_begin(dev, &conn_iter);
1971 	drm_for_each_connector_iter(con, &conn_iter) {
1972 		du = vmw_connector_to_du(con);
1973 		if (num_rects > du->unit) {
1974 			du->pref_width = drm_rect_width(&rects[du->unit]);
1975 			du->pref_height = drm_rect_height(&rects[du->unit]);
1976 			du->pref_active = true;
1977 			du->gui_x = rects[du->unit].x1;
1978 			du->gui_y = rects[du->unit].y1;
1979 		} else {
1980 			du->pref_width = 800;
1981 			du->pref_height = 600;
1982 			du->pref_active = false;
1983 			du->gui_x = 0;
1984 			du->gui_y = 0;
1985 		}
1986 	}
1987 	drm_connector_list_iter_end(&conn_iter);
1988 
1989 	list_for_each_entry(con, &dev->mode_config.connector_list, head) {
1990 		du = vmw_connector_to_du(con);
1991 		if (num_rects > du->unit) {
1992 			drm_object_property_set_value
1993 			  (&con->base, dev->mode_config.suggested_x_property,
1994 			   du->gui_x);
1995 			drm_object_property_set_value
1996 			  (&con->base, dev->mode_config.suggested_y_property,
1997 			   du->gui_y);
1998 		} else {
1999 			drm_object_property_set_value
2000 			  (&con->base, dev->mode_config.suggested_x_property,
2001 			   0);
2002 			drm_object_property_set_value
2003 			  (&con->base, dev->mode_config.suggested_y_property,
2004 			   0);
2005 		}
2006 		con->status = vmw_du_connector_detect(con, true);
2007 	}
2008 
2009 	drm_sysfs_hotplug_event(dev);
2010 out_fini:
2011 	drm_modeset_drop_locks(&ctx);
2012 	drm_modeset_acquire_fini(&ctx);
2013 	mutex_unlock(&dev->mode_config.mutex);
2014 
2015 	return 0;
2016 }
2017 
2018 int vmw_du_crtc_gamma_set(struct drm_crtc *crtc,
2019 			  u16 *r, u16 *g, u16 *b,
2020 			  uint32_t size,
2021 			  struct drm_modeset_acquire_ctx *ctx)
2022 {
2023 	struct vmw_private *dev_priv = vmw_priv(crtc->dev);
2024 	int i;
2025 
2026 	for (i = 0; i < size; i++) {
2027 		DRM_DEBUG("%d r/g/b = 0x%04x / 0x%04x / 0x%04x\n", i,
2028 			  r[i], g[i], b[i]);
2029 		vmw_write(dev_priv, SVGA_PALETTE_BASE + i * 3 + 0, r[i] >> 8);
2030 		vmw_write(dev_priv, SVGA_PALETTE_BASE + i * 3 + 1, g[i] >> 8);
2031 		vmw_write(dev_priv, SVGA_PALETTE_BASE + i * 3 + 2, b[i] >> 8);
2032 	}
2033 
2034 	return 0;
2035 }
2036 
2037 int vmw_du_connector_dpms(struct drm_connector *connector, int mode)
2038 {
2039 	return 0;
2040 }
2041 
2042 enum drm_connector_status
2043 vmw_du_connector_detect(struct drm_connector *connector, bool force)
2044 {
2045 	uint32_t num_displays;
2046 	struct drm_device *dev = connector->dev;
2047 	struct vmw_private *dev_priv = vmw_priv(dev);
2048 	struct vmw_display_unit *du = vmw_connector_to_du(connector);
2049 
2050 	num_displays = vmw_read(dev_priv, SVGA_REG_NUM_DISPLAYS);
2051 
2052 	return ((vmw_connector_to_du(connector)->unit < num_displays &&
2053 		 du->pref_active) ?
2054 		connector_status_connected : connector_status_disconnected);
2055 }
2056 
2057 static struct drm_display_mode vmw_kms_connector_builtin[] = {
2058 	/* 640x480@60Hz */
2059 	{ DRM_MODE("640x480", DRM_MODE_TYPE_DRIVER, 25175, 640, 656,
2060 		   752, 800, 0, 480, 489, 492, 525, 0,
2061 		   DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC) },
2062 	/* 800x600@60Hz */
2063 	{ DRM_MODE("800x600", DRM_MODE_TYPE_DRIVER, 40000, 800, 840,
2064 		   968, 1056, 0, 600, 601, 605, 628, 0,
2065 		   DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) },
2066 	/* 1024x768@60Hz */
2067 	{ DRM_MODE("1024x768", DRM_MODE_TYPE_DRIVER, 65000, 1024, 1048,
2068 		   1184, 1344, 0, 768, 771, 777, 806, 0,
2069 		   DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC) },
2070 	/* 1152x864@75Hz */
2071 	{ DRM_MODE("1152x864", DRM_MODE_TYPE_DRIVER, 108000, 1152, 1216,
2072 		   1344, 1600, 0, 864, 865, 868, 900, 0,
2073 		   DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) },
2074 	/* 1280x720@60Hz */
2075 	{ DRM_MODE("1280x720", DRM_MODE_TYPE_DRIVER, 74500, 1280, 1344,
2076 		   1472, 1664, 0, 720, 723, 728, 748, 0,
2077 		   DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
2078 	/* 1280x768@60Hz */
2079 	{ DRM_MODE("1280x768", DRM_MODE_TYPE_DRIVER, 79500, 1280, 1344,
2080 		   1472, 1664, 0, 768, 771, 778, 798, 0,
2081 		   DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
2082 	/* 1280x800@60Hz */
2083 	{ DRM_MODE("1280x800", DRM_MODE_TYPE_DRIVER, 83500, 1280, 1352,
2084 		   1480, 1680, 0, 800, 803, 809, 831, 0,
2085 		   DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NVSYNC) },
2086 	/* 1280x960@60Hz */
2087 	{ DRM_MODE("1280x960", DRM_MODE_TYPE_DRIVER, 108000, 1280, 1376,
2088 		   1488, 1800, 0, 960, 961, 964, 1000, 0,
2089 		   DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) },
2090 	/* 1280x1024@60Hz */
2091 	{ DRM_MODE("1280x1024", DRM_MODE_TYPE_DRIVER, 108000, 1280, 1328,
2092 		   1440, 1688, 0, 1024, 1025, 1028, 1066, 0,
2093 		   DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) },
2094 	/* 1360x768@60Hz */
2095 	{ DRM_MODE("1360x768", DRM_MODE_TYPE_DRIVER, 85500, 1360, 1424,
2096 		   1536, 1792, 0, 768, 771, 777, 795, 0,
2097 		   DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) },
2098 	/* 1440x1050@60Hz */
2099 	{ DRM_MODE("1400x1050", DRM_MODE_TYPE_DRIVER, 121750, 1400, 1488,
2100 		   1632, 1864, 0, 1050, 1053, 1057, 1089, 0,
2101 		   DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
2102 	/* 1440x900@60Hz */
2103 	{ DRM_MODE("1440x900", DRM_MODE_TYPE_DRIVER, 106500, 1440, 1520,
2104 		   1672, 1904, 0, 900, 903, 909, 934, 0,
2105 		   DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
2106 	/* 1600x1200@60Hz */
2107 	{ DRM_MODE("1600x1200", DRM_MODE_TYPE_DRIVER, 162000, 1600, 1664,
2108 		   1856, 2160, 0, 1200, 1201, 1204, 1250, 0,
2109 		   DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) },
2110 	/* 1680x1050@60Hz */
2111 	{ DRM_MODE("1680x1050", DRM_MODE_TYPE_DRIVER, 146250, 1680, 1784,
2112 		   1960, 2240, 0, 1050, 1053, 1059, 1089, 0,
2113 		   DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
2114 	/* 1792x1344@60Hz */
2115 	{ DRM_MODE("1792x1344", DRM_MODE_TYPE_DRIVER, 204750, 1792, 1920,
2116 		   2120, 2448, 0, 1344, 1345, 1348, 1394, 0,
2117 		   DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
2118 	/* 1853x1392@60Hz */
2119 	{ DRM_MODE("1856x1392", DRM_MODE_TYPE_DRIVER, 218250, 1856, 1952,
2120 		   2176, 2528, 0, 1392, 1393, 1396, 1439, 0,
2121 		   DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
2122 	/* 1920x1080@60Hz */
2123 	{ DRM_MODE("1920x1080", DRM_MODE_TYPE_DRIVER, 173000, 1920, 2048,
2124 		   2248, 2576, 0, 1080, 1083, 1088, 1120, 0,
2125 		   DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
2126 	/* 1920x1200@60Hz */
2127 	{ DRM_MODE("1920x1200", DRM_MODE_TYPE_DRIVER, 193250, 1920, 2056,
2128 		   2256, 2592, 0, 1200, 1203, 1209, 1245, 0,
2129 		   DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
2130 	/* 1920x1440@60Hz */
2131 	{ DRM_MODE("1920x1440", DRM_MODE_TYPE_DRIVER, 234000, 1920, 2048,
2132 		   2256, 2600, 0, 1440, 1441, 1444, 1500, 0,
2133 		   DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
2134 	/* 2560x1440@60Hz */
2135 	{ DRM_MODE("2560x1440", DRM_MODE_TYPE_DRIVER, 241500, 2560, 2608,
2136 		   2640, 2720, 0, 1440, 1443, 1448, 1481, 0,
2137 		   DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NVSYNC) },
2138 	/* 2560x1600@60Hz */
2139 	{ DRM_MODE("2560x1600", DRM_MODE_TYPE_DRIVER, 348500, 2560, 2752,
2140 		   3032, 3504, 0, 1600, 1603, 1609, 1658, 0,
2141 		   DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC) },
2142 	/* 2880x1800@60Hz */
2143 	{ DRM_MODE("2880x1800", DRM_MODE_TYPE_DRIVER, 337500, 2880, 2928,
2144 		   2960, 3040, 0, 1800, 1803, 1809, 1852, 0,
2145 		   DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NVSYNC) },
2146 	/* 3840x2160@60Hz */
2147 	{ DRM_MODE("3840x2160", DRM_MODE_TYPE_DRIVER, 533000, 3840, 3888,
2148 		   3920, 4000, 0, 2160, 2163, 2168, 2222, 0,
2149 		   DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NVSYNC) },
2150 	/* 3840x2400@60Hz */
2151 	{ DRM_MODE("3840x2400", DRM_MODE_TYPE_DRIVER, 592250, 3840, 3888,
2152 		   3920, 4000, 0, 2400, 2403, 2409, 2469, 0,
2153 		   DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NVSYNC) },
2154 	/* Terminate */
2155 	{ DRM_MODE("", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) },
2156 };
2157 
2158 /**
2159  * vmw_guess_mode_timing - Provide fake timings for a
2160  * 60Hz vrefresh mode.
2161  *
2162  * @mode: Pointer to a struct drm_display_mode with hdisplay and vdisplay
2163  * members filled in.
2164  */
2165 void vmw_guess_mode_timing(struct drm_display_mode *mode)
2166 {
2167 	mode->hsync_start = mode->hdisplay + 50;
2168 	mode->hsync_end = mode->hsync_start + 50;
2169 	mode->htotal = mode->hsync_end + 50;
2170 
2171 	mode->vsync_start = mode->vdisplay + 50;
2172 	mode->vsync_end = mode->vsync_start + 50;
2173 	mode->vtotal = mode->vsync_end + 50;
2174 
2175 	mode->clock = (u32)mode->htotal * (u32)mode->vtotal / 100 * 6;
2176 }
2177 
2178 
2179 int vmw_du_connector_fill_modes(struct drm_connector *connector,
2180 				uint32_t max_width, uint32_t max_height)
2181 {
2182 	struct vmw_display_unit *du = vmw_connector_to_du(connector);
2183 	struct drm_device *dev = connector->dev;
2184 	struct vmw_private *dev_priv = vmw_priv(dev);
2185 	struct drm_display_mode *mode = NULL;
2186 	struct drm_display_mode *bmode;
2187 	struct drm_display_mode prefmode = { DRM_MODE("preferred",
2188 		DRM_MODE_TYPE_DRIVER | DRM_MODE_TYPE_PREFERRED,
2189 		0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2190 		DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC)
2191 	};
2192 	int i;
2193 	u32 assumed_bpp = 4;
2194 
2195 	if (dev_priv->assume_16bpp)
2196 		assumed_bpp = 2;
2197 
2198 	max_width  = min(max_width,  dev_priv->texture_max_width);
2199 	max_height = min(max_height, dev_priv->texture_max_height);
2200 
2201 	/*
2202 	 * For STDU extra limit for a mode on SVGA_REG_SCREENTARGET_MAX_WIDTH/
2203 	 * HEIGHT registers.
2204 	 */
2205 	if (dev_priv->active_display_unit == vmw_du_screen_target) {
2206 		max_width  = min(max_width,  dev_priv->stdu_max_width);
2207 		max_height = min(max_height, dev_priv->stdu_max_height);
2208 	}
2209 
2210 	/* Add preferred mode */
2211 	mode = drm_mode_duplicate(dev, &prefmode);
2212 	if (!mode)
2213 		return 0;
2214 	mode->hdisplay = du->pref_width;
2215 	mode->vdisplay = du->pref_height;
2216 	vmw_guess_mode_timing(mode);
2217 	drm_mode_set_name(mode);
2218 
2219 	if (vmw_kms_validate_mode_vram(dev_priv,
2220 					mode->hdisplay * assumed_bpp,
2221 					mode->vdisplay)) {
2222 		drm_mode_probed_add(connector, mode);
2223 	} else {
2224 		drm_mode_destroy(dev, mode);
2225 		mode = NULL;
2226 	}
2227 
2228 	if (du->pref_mode) {
2229 		list_del_init(&du->pref_mode->head);
2230 		drm_mode_destroy(dev, du->pref_mode);
2231 	}
2232 
2233 	/* mode might be null here, this is intended */
2234 	du->pref_mode = mode;
2235 
2236 	for (i = 0; vmw_kms_connector_builtin[i].type != 0; i++) {
2237 		bmode = &vmw_kms_connector_builtin[i];
2238 		if (bmode->hdisplay > max_width ||
2239 		    bmode->vdisplay > max_height)
2240 			continue;
2241 
2242 		if (!vmw_kms_validate_mode_vram(dev_priv,
2243 						bmode->hdisplay * assumed_bpp,
2244 						bmode->vdisplay))
2245 			continue;
2246 
2247 		mode = drm_mode_duplicate(dev, bmode);
2248 		if (!mode)
2249 			return 0;
2250 
2251 		drm_mode_probed_add(connector, mode);
2252 	}
2253 
2254 	drm_connector_list_update(connector);
2255 	/* Move the prefered mode first, help apps pick the right mode. */
2256 	drm_mode_sort(&connector->modes);
2257 
2258 	return 1;
2259 }
2260 
2261 /**
2262  * vmw_kms_update_layout_ioctl - Handler for DRM_VMW_UPDATE_LAYOUT ioctl
2263  * @dev: drm device for the ioctl
2264  * @data: data pointer for the ioctl
2265  * @file_priv: drm file for the ioctl call
2266  *
2267  * Update preferred topology of display unit as per ioctl request. The topology
2268  * is expressed as array of drm_vmw_rect.
2269  * e.g.
2270  * [0 0 640 480] [640 0 800 600] [0 480 640 480]
2271  *
2272  * NOTE:
2273  * The x and y offset (upper left) in drm_vmw_rect cannot be less than 0. Beside
2274  * device limit on topology, x + w and y + h (lower right) cannot be greater
2275  * than INT_MAX. So topology beyond these limits will return with error.
2276  *
2277  * Returns:
2278  * Zero on success, negative errno on failure.
2279  */
2280 int vmw_kms_update_layout_ioctl(struct drm_device *dev, void *data,
2281 				struct drm_file *file_priv)
2282 {
2283 	struct vmw_private *dev_priv = vmw_priv(dev);
2284 	struct drm_mode_config *mode_config = &dev->mode_config;
2285 	struct drm_vmw_update_layout_arg *arg =
2286 		(struct drm_vmw_update_layout_arg *)data;
2287 	void __user *user_rects;
2288 	struct drm_vmw_rect *rects;
2289 	struct drm_rect *drm_rects;
2290 	unsigned rects_size;
2291 	int ret, i;
2292 
2293 	if (!arg->num_outputs) {
2294 		struct drm_rect def_rect = {0, 0, 800, 600};
2295 		VMW_DEBUG_KMS("Default layout x1 = %d y1 = %d x2 = %d y2 = %d\n",
2296 			      def_rect.x1, def_rect.y1,
2297 			      def_rect.x2, def_rect.y2);
2298 		vmw_du_update_layout(dev_priv, 1, &def_rect);
2299 		return 0;
2300 	}
2301 
2302 	rects_size = arg->num_outputs * sizeof(struct drm_vmw_rect);
2303 	rects = kcalloc(arg->num_outputs, sizeof(struct drm_vmw_rect),
2304 			GFP_KERNEL);
2305 	if (unlikely(!rects))
2306 		return -ENOMEM;
2307 
2308 	user_rects = (void __user *)(unsigned long)arg->rects;
2309 	ret = copy_from_user(rects, user_rects, rects_size);
2310 	if (unlikely(ret != 0)) {
2311 		DRM_ERROR("Failed to get rects.\n");
2312 		ret = -EFAULT;
2313 		goto out_free;
2314 	}
2315 
2316 	drm_rects = (struct drm_rect *)rects;
2317 
2318 	VMW_DEBUG_KMS("Layout count = %u\n", arg->num_outputs);
2319 	for (i = 0; i < arg->num_outputs; i++) {
2320 		struct drm_vmw_rect curr_rect;
2321 
2322 		/* Verify user-space for overflow as kernel use drm_rect */
2323 		if ((rects[i].x + rects[i].w > INT_MAX) ||
2324 		    (rects[i].y + rects[i].h > INT_MAX)) {
2325 			ret = -ERANGE;
2326 			goto out_free;
2327 		}
2328 
2329 		curr_rect = rects[i];
2330 		drm_rects[i].x1 = curr_rect.x;
2331 		drm_rects[i].y1 = curr_rect.y;
2332 		drm_rects[i].x2 = curr_rect.x + curr_rect.w;
2333 		drm_rects[i].y2 = curr_rect.y + curr_rect.h;
2334 
2335 		VMW_DEBUG_KMS("  x1 = %d y1 = %d x2 = %d y2 = %d\n",
2336 			      drm_rects[i].x1, drm_rects[i].y1,
2337 			      drm_rects[i].x2, drm_rects[i].y2);
2338 
2339 		/*
2340 		 * Currently this check is limiting the topology within
2341 		 * mode_config->max (which actually is max texture size
2342 		 * supported by virtual device). This limit is here to address
2343 		 * window managers that create a big framebuffer for whole
2344 		 * topology.
2345 		 */
2346 		if (drm_rects[i].x1 < 0 ||  drm_rects[i].y1 < 0 ||
2347 		    drm_rects[i].x2 > mode_config->max_width ||
2348 		    drm_rects[i].y2 > mode_config->max_height) {
2349 			VMW_DEBUG_KMS("Invalid layout %d %d %d %d\n",
2350 				      drm_rects[i].x1, drm_rects[i].y1,
2351 				      drm_rects[i].x2, drm_rects[i].y2);
2352 			ret = -EINVAL;
2353 			goto out_free;
2354 		}
2355 	}
2356 
2357 	ret = vmw_kms_check_display_memory(dev, arg->num_outputs, drm_rects);
2358 
2359 	if (ret == 0)
2360 		vmw_du_update_layout(dev_priv, arg->num_outputs, drm_rects);
2361 
2362 out_free:
2363 	kfree(rects);
2364 	return ret;
2365 }
2366 
2367 /**
2368  * vmw_kms_helper_dirty - Helper to build commands and perform actions based
2369  * on a set of cliprects and a set of display units.
2370  *
2371  * @dev_priv: Pointer to a device private structure.
2372  * @framebuffer: Pointer to the framebuffer on which to perform the actions.
2373  * @clips: A set of struct drm_clip_rect. Either this os @vclips must be NULL.
2374  * Cliprects are given in framebuffer coordinates.
2375  * @vclips: A set of struct drm_vmw_rect cliprects. Either this or @clips must
2376  * be NULL. Cliprects are given in source coordinates.
2377  * @dest_x: X coordinate offset for the crtc / destination clip rects.
2378  * @dest_y: Y coordinate offset for the crtc / destination clip rects.
2379  * @num_clips: Number of cliprects in the @clips or @vclips array.
2380  * @increment: Integer with which to increment the clip counter when looping.
2381  * Used to skip a predetermined number of clip rects.
2382  * @dirty: Closure structure. See the description of struct vmw_kms_dirty.
2383  */
2384 int vmw_kms_helper_dirty(struct vmw_private *dev_priv,
2385 			 struct vmw_framebuffer *framebuffer,
2386 			 const struct drm_clip_rect *clips,
2387 			 const struct drm_vmw_rect *vclips,
2388 			 s32 dest_x, s32 dest_y,
2389 			 int num_clips,
2390 			 int increment,
2391 			 struct vmw_kms_dirty *dirty)
2392 {
2393 	struct vmw_display_unit *units[VMWGFX_NUM_DISPLAY_UNITS];
2394 	struct drm_crtc *crtc;
2395 	u32 num_units = 0;
2396 	u32 i, k;
2397 
2398 	dirty->dev_priv = dev_priv;
2399 
2400 	/* If crtc is passed, no need to iterate over other display units */
2401 	if (dirty->crtc) {
2402 		units[num_units++] = vmw_crtc_to_du(dirty->crtc);
2403 	} else {
2404 		list_for_each_entry(crtc, &dev_priv->drm.mode_config.crtc_list,
2405 				    head) {
2406 			struct drm_plane *plane = crtc->primary;
2407 
2408 			if (plane->state->fb == &framebuffer->base)
2409 				units[num_units++] = vmw_crtc_to_du(crtc);
2410 		}
2411 	}
2412 
2413 	for (k = 0; k < num_units; k++) {
2414 		struct vmw_display_unit *unit = units[k];
2415 		s32 crtc_x = unit->crtc.x;
2416 		s32 crtc_y = unit->crtc.y;
2417 		s32 crtc_width = unit->crtc.mode.hdisplay;
2418 		s32 crtc_height = unit->crtc.mode.vdisplay;
2419 		const struct drm_clip_rect *clips_ptr = clips;
2420 		const struct drm_vmw_rect *vclips_ptr = vclips;
2421 
2422 		dirty->unit = unit;
2423 		if (dirty->fifo_reserve_size > 0) {
2424 			dirty->cmd = VMW_CMD_RESERVE(dev_priv,
2425 						      dirty->fifo_reserve_size);
2426 			if (!dirty->cmd)
2427 				return -ENOMEM;
2428 
2429 			memset(dirty->cmd, 0, dirty->fifo_reserve_size);
2430 		}
2431 		dirty->num_hits = 0;
2432 		for (i = 0; i < num_clips; i++, clips_ptr += increment,
2433 		       vclips_ptr += increment) {
2434 			s32 clip_left;
2435 			s32 clip_top;
2436 
2437 			/*
2438 			 * Select clip array type. Note that integer type
2439 			 * in @clips is unsigned short, whereas in @vclips
2440 			 * it's 32-bit.
2441 			 */
2442 			if (clips) {
2443 				dirty->fb_x = (s32) clips_ptr->x1;
2444 				dirty->fb_y = (s32) clips_ptr->y1;
2445 				dirty->unit_x2 = (s32) clips_ptr->x2 + dest_x -
2446 					crtc_x;
2447 				dirty->unit_y2 = (s32) clips_ptr->y2 + dest_y -
2448 					crtc_y;
2449 			} else {
2450 				dirty->fb_x = vclips_ptr->x;
2451 				dirty->fb_y = vclips_ptr->y;
2452 				dirty->unit_x2 = dirty->fb_x + vclips_ptr->w +
2453 					dest_x - crtc_x;
2454 				dirty->unit_y2 = dirty->fb_y + vclips_ptr->h +
2455 					dest_y - crtc_y;
2456 			}
2457 
2458 			dirty->unit_x1 = dirty->fb_x + dest_x - crtc_x;
2459 			dirty->unit_y1 = dirty->fb_y + dest_y - crtc_y;
2460 
2461 			/* Skip this clip if it's outside the crtc region */
2462 			if (dirty->unit_x1 >= crtc_width ||
2463 			    dirty->unit_y1 >= crtc_height ||
2464 			    dirty->unit_x2 <= 0 || dirty->unit_y2 <= 0)
2465 				continue;
2466 
2467 			/* Clip right and bottom to crtc limits */
2468 			dirty->unit_x2 = min_t(s32, dirty->unit_x2,
2469 					       crtc_width);
2470 			dirty->unit_y2 = min_t(s32, dirty->unit_y2,
2471 					       crtc_height);
2472 
2473 			/* Clip left and top to crtc limits */
2474 			clip_left = min_t(s32, dirty->unit_x1, 0);
2475 			clip_top = min_t(s32, dirty->unit_y1, 0);
2476 			dirty->unit_x1 -= clip_left;
2477 			dirty->unit_y1 -= clip_top;
2478 			dirty->fb_x -= clip_left;
2479 			dirty->fb_y -= clip_top;
2480 
2481 			dirty->clip(dirty);
2482 		}
2483 
2484 		dirty->fifo_commit(dirty);
2485 	}
2486 
2487 	return 0;
2488 }
2489 
2490 /**
2491  * vmw_kms_helper_validation_finish - Helper for post KMS command submission
2492  * cleanup and fencing
2493  * @dev_priv: Pointer to the device-private struct
2494  * @file_priv: Pointer identifying the client when user-space fencing is used
2495  * @ctx: Pointer to the validation context
2496  * @out_fence: If non-NULL, returned refcounted fence-pointer
2497  * @user_fence_rep: If non-NULL, pointer to user-space address area
2498  * in which to copy user-space fence info
2499  */
2500 void vmw_kms_helper_validation_finish(struct vmw_private *dev_priv,
2501 				      struct drm_file *file_priv,
2502 				      struct vmw_validation_context *ctx,
2503 				      struct vmw_fence_obj **out_fence,
2504 				      struct drm_vmw_fence_rep __user *
2505 				      user_fence_rep)
2506 {
2507 	struct vmw_fence_obj *fence = NULL;
2508 	uint32_t handle = 0;
2509 	int ret = 0;
2510 
2511 	if (file_priv || user_fence_rep || vmw_validation_has_bos(ctx) ||
2512 	    out_fence)
2513 		ret = vmw_execbuf_fence_commands(file_priv, dev_priv, &fence,
2514 						 file_priv ? &handle : NULL);
2515 	vmw_validation_done(ctx, fence);
2516 	if (file_priv)
2517 		vmw_execbuf_copy_fence_user(dev_priv, vmw_fpriv(file_priv),
2518 					    ret, user_fence_rep, fence,
2519 					    handle, -1, NULL);
2520 	if (out_fence)
2521 		*out_fence = fence;
2522 	else
2523 		vmw_fence_obj_unreference(&fence);
2524 }
2525 
2526 /**
2527  * vmw_kms_update_proxy - Helper function to update a proxy surface from
2528  * its backing MOB.
2529  *
2530  * @res: Pointer to the surface resource
2531  * @clips: Clip rects in framebuffer (surface) space.
2532  * @num_clips: Number of clips in @clips.
2533  * @increment: Integer with which to increment the clip counter when looping.
2534  * Used to skip a predetermined number of clip rects.
2535  *
2536  * This function makes sure the proxy surface is updated from its backing MOB
2537  * using the region given by @clips. The surface resource @res and its backing
2538  * MOB needs to be reserved and validated on call.
2539  */
2540 int vmw_kms_update_proxy(struct vmw_resource *res,
2541 			 const struct drm_clip_rect *clips,
2542 			 unsigned num_clips,
2543 			 int increment)
2544 {
2545 	struct vmw_private *dev_priv = res->dev_priv;
2546 	struct drm_vmw_size *size = &vmw_res_to_srf(res)->metadata.base_size;
2547 	struct {
2548 		SVGA3dCmdHeader header;
2549 		SVGA3dCmdUpdateGBImage body;
2550 	} *cmd;
2551 	SVGA3dBox *box;
2552 	size_t copy_size = 0;
2553 	int i;
2554 
2555 	if (!clips)
2556 		return 0;
2557 
2558 	cmd = VMW_CMD_RESERVE(dev_priv, sizeof(*cmd) * num_clips);
2559 	if (!cmd)
2560 		return -ENOMEM;
2561 
2562 	for (i = 0; i < num_clips; ++i, clips += increment, ++cmd) {
2563 		box = &cmd->body.box;
2564 
2565 		cmd->header.id = SVGA_3D_CMD_UPDATE_GB_IMAGE;
2566 		cmd->header.size = sizeof(cmd->body);
2567 		cmd->body.image.sid = res->id;
2568 		cmd->body.image.face = 0;
2569 		cmd->body.image.mipmap = 0;
2570 
2571 		if (clips->x1 > size->width || clips->x2 > size->width ||
2572 		    clips->y1 > size->height || clips->y2 > size->height) {
2573 			DRM_ERROR("Invalid clips outsize of framebuffer.\n");
2574 			return -EINVAL;
2575 		}
2576 
2577 		box->x = clips->x1;
2578 		box->y = clips->y1;
2579 		box->z = 0;
2580 		box->w = clips->x2 - clips->x1;
2581 		box->h = clips->y2 - clips->y1;
2582 		box->d = 1;
2583 
2584 		copy_size += sizeof(*cmd);
2585 	}
2586 
2587 	vmw_cmd_commit(dev_priv, copy_size);
2588 
2589 	return 0;
2590 }
2591 
2592 int vmw_kms_fbdev_init_data(struct vmw_private *dev_priv,
2593 			    unsigned unit,
2594 			    u32 max_width,
2595 			    u32 max_height,
2596 			    struct drm_connector **p_con,
2597 			    struct drm_crtc **p_crtc,
2598 			    struct drm_display_mode **p_mode)
2599 {
2600 	struct drm_connector *con;
2601 	struct vmw_display_unit *du;
2602 	struct drm_display_mode *mode;
2603 	int i = 0;
2604 	int ret = 0;
2605 
2606 	mutex_lock(&dev_priv->drm.mode_config.mutex);
2607 	list_for_each_entry(con, &dev_priv->drm.mode_config.connector_list,
2608 			    head) {
2609 		if (i == unit)
2610 			break;
2611 
2612 		++i;
2613 	}
2614 
2615 	if (&con->head == &dev_priv->drm.mode_config.connector_list) {
2616 		DRM_ERROR("Could not find initial display unit.\n");
2617 		ret = -EINVAL;
2618 		goto out_unlock;
2619 	}
2620 
2621 	if (list_empty(&con->modes))
2622 		(void) vmw_du_connector_fill_modes(con, max_width, max_height);
2623 
2624 	if (list_empty(&con->modes)) {
2625 		DRM_ERROR("Could not find initial display mode.\n");
2626 		ret = -EINVAL;
2627 		goto out_unlock;
2628 	}
2629 
2630 	du = vmw_connector_to_du(con);
2631 	*p_con = con;
2632 	*p_crtc = &du->crtc;
2633 
2634 	list_for_each_entry(mode, &con->modes, head) {
2635 		if (mode->type & DRM_MODE_TYPE_PREFERRED)
2636 			break;
2637 	}
2638 
2639 	if (&mode->head == &con->modes) {
2640 		WARN_ONCE(true, "Could not find initial preferred mode.\n");
2641 		*p_mode = list_first_entry(&con->modes,
2642 					   struct drm_display_mode,
2643 					   head);
2644 	} else {
2645 		*p_mode = mode;
2646 	}
2647 
2648  out_unlock:
2649 	mutex_unlock(&dev_priv->drm.mode_config.mutex);
2650 
2651 	return ret;
2652 }
2653 
2654 /**
2655  * vmw_kms_create_implicit_placement_property - Set up the implicit placement
2656  * property.
2657  *
2658  * @dev_priv: Pointer to a device private struct.
2659  *
2660  * Sets up the implicit placement property unless it's already set up.
2661  */
2662 void
2663 vmw_kms_create_implicit_placement_property(struct vmw_private *dev_priv)
2664 {
2665 	if (dev_priv->implicit_placement_property)
2666 		return;
2667 
2668 	dev_priv->implicit_placement_property =
2669 		drm_property_create_range(&dev_priv->drm,
2670 					  DRM_MODE_PROP_IMMUTABLE,
2671 					  "implicit_placement", 0, 1);
2672 }
2673 
2674 /**
2675  * vmw_kms_suspend - Save modesetting state and turn modesetting off.
2676  *
2677  * @dev: Pointer to the drm device
2678  * Return: 0 on success. Negative error code on failure.
2679  */
2680 int vmw_kms_suspend(struct drm_device *dev)
2681 {
2682 	struct vmw_private *dev_priv = vmw_priv(dev);
2683 
2684 	dev_priv->suspend_state = drm_atomic_helper_suspend(dev);
2685 	if (IS_ERR(dev_priv->suspend_state)) {
2686 		int ret = PTR_ERR(dev_priv->suspend_state);
2687 
2688 		DRM_ERROR("Failed kms suspend: %d\n", ret);
2689 		dev_priv->suspend_state = NULL;
2690 
2691 		return ret;
2692 	}
2693 
2694 	return 0;
2695 }
2696 
2697 
2698 /**
2699  * vmw_kms_resume - Re-enable modesetting and restore state
2700  *
2701  * @dev: Pointer to the drm device
2702  * Return: 0 on success. Negative error code on failure.
2703  *
2704  * State is resumed from a previous vmw_kms_suspend(). It's illegal
2705  * to call this function without a previous vmw_kms_suspend().
2706  */
2707 int vmw_kms_resume(struct drm_device *dev)
2708 {
2709 	struct vmw_private *dev_priv = vmw_priv(dev);
2710 	int ret;
2711 
2712 	if (WARN_ON(!dev_priv->suspend_state))
2713 		return 0;
2714 
2715 	ret = drm_atomic_helper_resume(dev, dev_priv->suspend_state);
2716 	dev_priv->suspend_state = NULL;
2717 
2718 	return ret;
2719 }
2720 
2721 /**
2722  * vmw_kms_lost_device - Notify kms that modesetting capabilities will be lost
2723  *
2724  * @dev: Pointer to the drm device
2725  */
2726 void vmw_kms_lost_device(struct drm_device *dev)
2727 {
2728 	drm_atomic_helper_shutdown(dev);
2729 }
2730 
2731 /**
2732  * vmw_du_helper_plane_update - Helper to do plane update on a display unit.
2733  * @update: The closure structure.
2734  *
2735  * Call this helper after setting callbacks in &vmw_du_update_plane to do plane
2736  * update on display unit.
2737  *
2738  * Return: 0 on success or a negative error code on failure.
2739  */
2740 int vmw_du_helper_plane_update(struct vmw_du_update_plane *update)
2741 {
2742 	struct drm_plane_state *state = update->plane->state;
2743 	struct drm_plane_state *old_state = update->old_state;
2744 	struct drm_atomic_helper_damage_iter iter;
2745 	struct drm_rect clip;
2746 	struct drm_rect bb;
2747 	DECLARE_VAL_CONTEXT(val_ctx, NULL, 0);
2748 	uint32_t reserved_size = 0;
2749 	uint32_t submit_size = 0;
2750 	uint32_t curr_size = 0;
2751 	uint32_t num_hits = 0;
2752 	void *cmd_start;
2753 	char *cmd_next;
2754 	int ret;
2755 
2756 	/*
2757 	 * Iterate in advance to check if really need plane update and find the
2758 	 * number of clips that actually are in plane src for fifo allocation.
2759 	 */
2760 	drm_atomic_helper_damage_iter_init(&iter, old_state, state);
2761 	drm_atomic_for_each_plane_damage(&iter, &clip)
2762 		num_hits++;
2763 
2764 	if (num_hits == 0)
2765 		return 0;
2766 
2767 	if (update->vfb->bo) {
2768 		struct vmw_framebuffer_bo *vfbbo =
2769 			container_of(update->vfb, typeof(*vfbbo), base);
2770 
2771 		ret = vmw_validation_add_bo(&val_ctx, vfbbo->buffer, false,
2772 					    update->cpu_blit);
2773 	} else {
2774 		struct vmw_framebuffer_surface *vfbs =
2775 			container_of(update->vfb, typeof(*vfbs), base);
2776 
2777 		ret = vmw_validation_add_resource(&val_ctx, &vfbs->surface->res,
2778 						  0, VMW_RES_DIRTY_NONE, NULL,
2779 						  NULL);
2780 	}
2781 
2782 	if (ret)
2783 		return ret;
2784 
2785 	ret = vmw_validation_prepare(&val_ctx, update->mutex, update->intr);
2786 	if (ret)
2787 		goto out_unref;
2788 
2789 	reserved_size = update->calc_fifo_size(update, num_hits);
2790 	cmd_start = VMW_CMD_RESERVE(update->dev_priv, reserved_size);
2791 	if (!cmd_start) {
2792 		ret = -ENOMEM;
2793 		goto out_revert;
2794 	}
2795 
2796 	cmd_next = cmd_start;
2797 
2798 	if (update->post_prepare) {
2799 		curr_size = update->post_prepare(update, cmd_next);
2800 		cmd_next += curr_size;
2801 		submit_size += curr_size;
2802 	}
2803 
2804 	if (update->pre_clip) {
2805 		curr_size = update->pre_clip(update, cmd_next, num_hits);
2806 		cmd_next += curr_size;
2807 		submit_size += curr_size;
2808 	}
2809 
2810 	bb.x1 = INT_MAX;
2811 	bb.y1 = INT_MAX;
2812 	bb.x2 = INT_MIN;
2813 	bb.y2 = INT_MIN;
2814 
2815 	drm_atomic_helper_damage_iter_init(&iter, old_state, state);
2816 	drm_atomic_for_each_plane_damage(&iter, &clip) {
2817 		uint32_t fb_x = clip.x1;
2818 		uint32_t fb_y = clip.y1;
2819 
2820 		vmw_du_translate_to_crtc(state, &clip);
2821 		if (update->clip) {
2822 			curr_size = update->clip(update, cmd_next, &clip, fb_x,
2823 						 fb_y);
2824 			cmd_next += curr_size;
2825 			submit_size += curr_size;
2826 		}
2827 		bb.x1 = min_t(int, bb.x1, clip.x1);
2828 		bb.y1 = min_t(int, bb.y1, clip.y1);
2829 		bb.x2 = max_t(int, bb.x2, clip.x2);
2830 		bb.y2 = max_t(int, bb.y2, clip.y2);
2831 	}
2832 
2833 	curr_size = update->post_clip(update, cmd_next, &bb);
2834 	submit_size += curr_size;
2835 
2836 	if (reserved_size < submit_size)
2837 		submit_size = 0;
2838 
2839 	vmw_cmd_commit(update->dev_priv, submit_size);
2840 
2841 	vmw_kms_helper_validation_finish(update->dev_priv, NULL, &val_ctx,
2842 					 update->out_fence, NULL);
2843 	return ret;
2844 
2845 out_revert:
2846 	vmw_validation_revert(&val_ctx);
2847 
2848 out_unref:
2849 	vmw_validation_unref_lists(&val_ctx);
2850 	return ret;
2851 }
2852