xref: /openbmc/linux/drivers/gpu/drm/i915/gvt/scheduler.c (revision 0b26ca68)
1 /*
2  * Copyright(c) 2011-2016 Intel Corporation. All rights reserved.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21  * SOFTWARE.
22  *
23  * Authors:
24  *    Zhi Wang <zhi.a.wang@intel.com>
25  *
26  * Contributors:
27  *    Ping Gao <ping.a.gao@intel.com>
28  *    Tina Zhang <tina.zhang@intel.com>
29  *    Chanbin Du <changbin.du@intel.com>
30  *    Min He <min.he@intel.com>
31  *    Bing Niu <bing.niu@intel.com>
32  *    Zhenyu Wang <zhenyuw@linux.intel.com>
33  *
34  */
35 
36 #include <linux/kthread.h>
37 
38 #include "gem/i915_gem_pm.h"
39 #include "gt/intel_context.h"
40 #include "gt/intel_execlists_submission.h"
41 #include "gt/intel_lrc.h"
42 #include "gt/intel_ring.h"
43 
44 #include "i915_drv.h"
45 #include "i915_gem_gtt.h"
46 #include "gvt.h"
47 
48 #define RING_CTX_OFF(x) \
49 	offsetof(struct execlist_ring_context, x)
50 
51 static void set_context_pdp_root_pointer(
52 		struct execlist_ring_context *ring_context,
53 		u32 pdp[8])
54 {
55 	int i;
56 
57 	for (i = 0; i < 8; i++)
58 		ring_context->pdps[i].val = pdp[7 - i];
59 }
60 
61 static void update_shadow_pdps(struct intel_vgpu_workload *workload)
62 {
63 	struct execlist_ring_context *shadow_ring_context;
64 	struct intel_context *ctx = workload->req->context;
65 
66 	if (WARN_ON(!workload->shadow_mm))
67 		return;
68 
69 	if (WARN_ON(!atomic_read(&workload->shadow_mm->pincount)))
70 		return;
71 
72 	shadow_ring_context = (struct execlist_ring_context *)ctx->lrc_reg_state;
73 	set_context_pdp_root_pointer(shadow_ring_context,
74 			(void *)workload->shadow_mm->ppgtt_mm.shadow_pdps);
75 }
76 
77 /*
78  * when populating shadow ctx from guest, we should not overrride oa related
79  * registers, so that they will not be overlapped by guest oa configs. Thus
80  * made it possible to capture oa data from host for both host and guests.
81  */
82 static void sr_oa_regs(struct intel_vgpu_workload *workload,
83 		u32 *reg_state, bool save)
84 {
85 	struct drm_i915_private *dev_priv = workload->vgpu->gvt->gt->i915;
86 	u32 ctx_oactxctrl = dev_priv->perf.ctx_oactxctrl_offset;
87 	u32 ctx_flexeu0 = dev_priv->perf.ctx_flexeu0_offset;
88 	int i = 0;
89 	u32 flex_mmio[] = {
90 		i915_mmio_reg_offset(EU_PERF_CNTL0),
91 		i915_mmio_reg_offset(EU_PERF_CNTL1),
92 		i915_mmio_reg_offset(EU_PERF_CNTL2),
93 		i915_mmio_reg_offset(EU_PERF_CNTL3),
94 		i915_mmio_reg_offset(EU_PERF_CNTL4),
95 		i915_mmio_reg_offset(EU_PERF_CNTL5),
96 		i915_mmio_reg_offset(EU_PERF_CNTL6),
97 	};
98 
99 	if (workload->engine->id != RCS0)
100 		return;
101 
102 	if (save) {
103 		workload->oactxctrl = reg_state[ctx_oactxctrl + 1];
104 
105 		for (i = 0; i < ARRAY_SIZE(workload->flex_mmio); i++) {
106 			u32 state_offset = ctx_flexeu0 + i * 2;
107 
108 			workload->flex_mmio[i] = reg_state[state_offset + 1];
109 		}
110 	} else {
111 		reg_state[ctx_oactxctrl] =
112 			i915_mmio_reg_offset(GEN8_OACTXCONTROL);
113 		reg_state[ctx_oactxctrl + 1] = workload->oactxctrl;
114 
115 		for (i = 0; i < ARRAY_SIZE(workload->flex_mmio); i++) {
116 			u32 state_offset = ctx_flexeu0 + i * 2;
117 			u32 mmio = flex_mmio[i];
118 
119 			reg_state[state_offset] = mmio;
120 			reg_state[state_offset + 1] = workload->flex_mmio[i];
121 		}
122 	}
123 }
124 
125 static int populate_shadow_context(struct intel_vgpu_workload *workload)
126 {
127 	struct intel_vgpu *vgpu = workload->vgpu;
128 	struct intel_gvt *gvt = vgpu->gvt;
129 	struct intel_context *ctx = workload->req->context;
130 	struct execlist_ring_context *shadow_ring_context;
131 	void *dst;
132 	void *context_base;
133 	unsigned long context_gpa, context_page_num;
134 	unsigned long gpa_base; /* first gpa of consecutive GPAs */
135 	unsigned long gpa_size; /* size of consecutive GPAs */
136 	struct intel_vgpu_submission *s = &vgpu->submission;
137 	int i;
138 	bool skip = false;
139 	int ring_id = workload->engine->id;
140 	int ret;
141 
142 	GEM_BUG_ON(!intel_context_is_pinned(ctx));
143 
144 	context_base = (void *) ctx->lrc_reg_state -
145 				(LRC_STATE_PN << I915_GTT_PAGE_SHIFT);
146 
147 	shadow_ring_context = (void *) ctx->lrc_reg_state;
148 
149 	sr_oa_regs(workload, (u32 *)shadow_ring_context, true);
150 #define COPY_REG(name) \
151 	intel_gvt_hypervisor_read_gpa(vgpu, workload->ring_context_gpa \
152 		+ RING_CTX_OFF(name.val), &shadow_ring_context->name.val, 4)
153 #define COPY_REG_MASKED(name) {\
154 		intel_gvt_hypervisor_read_gpa(vgpu, workload->ring_context_gpa \
155 					      + RING_CTX_OFF(name.val),\
156 					      &shadow_ring_context->name.val, 4);\
157 		shadow_ring_context->name.val |= 0xffff << 16;\
158 	}
159 
160 	COPY_REG_MASKED(ctx_ctrl);
161 	COPY_REG(ctx_timestamp);
162 
163 	if (workload->engine->id == RCS0) {
164 		COPY_REG(bb_per_ctx_ptr);
165 		COPY_REG(rcs_indirect_ctx);
166 		COPY_REG(rcs_indirect_ctx_offset);
167 	} else if (workload->engine->id == BCS0)
168 		intel_gvt_hypervisor_read_gpa(vgpu,
169 				workload->ring_context_gpa +
170 				BCS_TILE_REGISTER_VAL_OFFSET,
171 				(void *)shadow_ring_context +
172 				BCS_TILE_REGISTER_VAL_OFFSET, 4);
173 #undef COPY_REG
174 #undef COPY_REG_MASKED
175 
176 	/* don't copy Ring Context (the first 0x50 dwords),
177 	 * only copy the Engine Context part from guest
178 	 */
179 	intel_gvt_hypervisor_read_gpa(vgpu,
180 			workload->ring_context_gpa +
181 			RING_CTX_SIZE,
182 			(void *)shadow_ring_context +
183 			RING_CTX_SIZE,
184 			I915_GTT_PAGE_SIZE - RING_CTX_SIZE);
185 
186 	sr_oa_regs(workload, (u32 *)shadow_ring_context, false);
187 
188 	gvt_dbg_sched("ring %s workload lrca %x, ctx_id %x, ctx gpa %llx",
189 			workload->engine->name, workload->ctx_desc.lrca,
190 			workload->ctx_desc.context_id,
191 			workload->ring_context_gpa);
192 
193 	/* only need to ensure this context is not pinned/unpinned during the
194 	 * period from last submission to this this submission.
195 	 * Upon reaching this function, the currently submitted context is not
196 	 * supposed to get unpinned. If a misbehaving guest driver ever does
197 	 * this, it would corrupt itself.
198 	 */
199 	if (s->last_ctx[ring_id].valid &&
200 			(s->last_ctx[ring_id].lrca ==
201 				workload->ctx_desc.lrca) &&
202 			(s->last_ctx[ring_id].ring_context_gpa ==
203 				workload->ring_context_gpa))
204 		skip = true;
205 
206 	s->last_ctx[ring_id].lrca = workload->ctx_desc.lrca;
207 	s->last_ctx[ring_id].ring_context_gpa = workload->ring_context_gpa;
208 
209 	if (IS_RESTORE_INHIBIT(shadow_ring_context->ctx_ctrl.val) || skip)
210 		return 0;
211 
212 	s->last_ctx[ring_id].valid = false;
213 	context_page_num = workload->engine->context_size;
214 	context_page_num = context_page_num >> PAGE_SHIFT;
215 
216 	if (IS_BROADWELL(gvt->gt->i915) && workload->engine->id == RCS0)
217 		context_page_num = 19;
218 
219 	/* find consecutive GPAs from gma until the first inconsecutive GPA.
220 	 * read from the continuous GPAs into dst virtual address
221 	 */
222 	gpa_size = 0;
223 	for (i = 2; i < context_page_num; i++) {
224 		context_gpa = intel_vgpu_gma_to_gpa(vgpu->gtt.ggtt_mm,
225 				(u32)((workload->ctx_desc.lrca + i) <<
226 				I915_GTT_PAGE_SHIFT));
227 		if (context_gpa == INTEL_GVT_INVALID_ADDR) {
228 			gvt_vgpu_err("Invalid guest context descriptor\n");
229 			return -EFAULT;
230 		}
231 
232 		if (gpa_size == 0) {
233 			gpa_base = context_gpa;
234 			dst = context_base + (i << I915_GTT_PAGE_SHIFT);
235 		} else if (context_gpa != gpa_base + gpa_size)
236 			goto read;
237 
238 		gpa_size += I915_GTT_PAGE_SIZE;
239 
240 		if (i == context_page_num - 1)
241 			goto read;
242 
243 		continue;
244 
245 read:
246 		intel_gvt_hypervisor_read_gpa(vgpu, gpa_base, dst, gpa_size);
247 		gpa_base = context_gpa;
248 		gpa_size = I915_GTT_PAGE_SIZE;
249 		dst = context_base + (i << I915_GTT_PAGE_SHIFT);
250 	}
251 	ret = intel_gvt_scan_engine_context(workload);
252 	if (ret) {
253 		gvt_vgpu_err("invalid cmd found in guest context pages\n");
254 		return ret;
255 	}
256 	s->last_ctx[ring_id].valid = true;
257 	return 0;
258 }
259 
260 static inline bool is_gvt_request(struct i915_request *rq)
261 {
262 	return intel_context_force_single_submission(rq->context);
263 }
264 
265 static void save_ring_hw_state(struct intel_vgpu *vgpu,
266 			       const struct intel_engine_cs *engine)
267 {
268 	struct intel_uncore *uncore = engine->uncore;
269 	i915_reg_t reg;
270 
271 	reg = RING_INSTDONE(engine->mmio_base);
272 	vgpu_vreg(vgpu, i915_mmio_reg_offset(reg)) =
273 		intel_uncore_read(uncore, reg);
274 
275 	reg = RING_ACTHD(engine->mmio_base);
276 	vgpu_vreg(vgpu, i915_mmio_reg_offset(reg)) =
277 		intel_uncore_read(uncore, reg);
278 
279 	reg = RING_ACTHD_UDW(engine->mmio_base);
280 	vgpu_vreg(vgpu, i915_mmio_reg_offset(reg)) =
281 		intel_uncore_read(uncore, reg);
282 }
283 
284 static int shadow_context_status_change(struct notifier_block *nb,
285 		unsigned long action, void *data)
286 {
287 	struct i915_request *rq = data;
288 	struct intel_gvt *gvt = container_of(nb, struct intel_gvt,
289 				shadow_ctx_notifier_block[rq->engine->id]);
290 	struct intel_gvt_workload_scheduler *scheduler = &gvt->scheduler;
291 	enum intel_engine_id ring_id = rq->engine->id;
292 	struct intel_vgpu_workload *workload;
293 	unsigned long flags;
294 
295 	if (!is_gvt_request(rq)) {
296 		spin_lock_irqsave(&scheduler->mmio_context_lock, flags);
297 		if (action == INTEL_CONTEXT_SCHEDULE_IN &&
298 		    scheduler->engine_owner[ring_id]) {
299 			/* Switch ring from vGPU to host. */
300 			intel_gvt_switch_mmio(scheduler->engine_owner[ring_id],
301 					      NULL, rq->engine);
302 			scheduler->engine_owner[ring_id] = NULL;
303 		}
304 		spin_unlock_irqrestore(&scheduler->mmio_context_lock, flags);
305 
306 		return NOTIFY_OK;
307 	}
308 
309 	workload = scheduler->current_workload[ring_id];
310 	if (unlikely(!workload))
311 		return NOTIFY_OK;
312 
313 	switch (action) {
314 	case INTEL_CONTEXT_SCHEDULE_IN:
315 		spin_lock_irqsave(&scheduler->mmio_context_lock, flags);
316 		if (workload->vgpu != scheduler->engine_owner[ring_id]) {
317 			/* Switch ring from host to vGPU or vGPU to vGPU. */
318 			intel_gvt_switch_mmio(scheduler->engine_owner[ring_id],
319 					      workload->vgpu, rq->engine);
320 			scheduler->engine_owner[ring_id] = workload->vgpu;
321 		} else
322 			gvt_dbg_sched("skip ring %d mmio switch for vgpu%d\n",
323 				      ring_id, workload->vgpu->id);
324 		spin_unlock_irqrestore(&scheduler->mmio_context_lock, flags);
325 		atomic_set(&workload->shadow_ctx_active, 1);
326 		break;
327 	case INTEL_CONTEXT_SCHEDULE_OUT:
328 		save_ring_hw_state(workload->vgpu, rq->engine);
329 		atomic_set(&workload->shadow_ctx_active, 0);
330 		break;
331 	case INTEL_CONTEXT_SCHEDULE_PREEMPTED:
332 		save_ring_hw_state(workload->vgpu, rq->engine);
333 		break;
334 	default:
335 		WARN_ON(1);
336 		return NOTIFY_OK;
337 	}
338 	wake_up(&workload->shadow_ctx_status_wq);
339 	return NOTIFY_OK;
340 }
341 
342 static void
343 shadow_context_descriptor_update(struct intel_context *ce,
344 				 struct intel_vgpu_workload *workload)
345 {
346 	u64 desc = ce->lrc.desc;
347 
348 	/*
349 	 * Update bits 0-11 of the context descriptor which includes flags
350 	 * like GEN8_CTX_* cached in desc_template
351 	 */
352 	desc &= ~(0x3ull << GEN8_CTX_ADDRESSING_MODE_SHIFT);
353 	desc |= (u64)workload->ctx_desc.addressing_mode <<
354 		GEN8_CTX_ADDRESSING_MODE_SHIFT;
355 
356 	ce->lrc.desc = desc;
357 }
358 
359 static int copy_workload_to_ring_buffer(struct intel_vgpu_workload *workload)
360 {
361 	struct intel_vgpu *vgpu = workload->vgpu;
362 	struct i915_request *req = workload->req;
363 	void *shadow_ring_buffer_va;
364 	u32 *cs;
365 	int err;
366 
367 	if (IS_GEN(req->engine->i915, 9) && is_inhibit_context(req->context))
368 		intel_vgpu_restore_inhibit_context(vgpu, req);
369 
370 	/*
371 	 * To track whether a request has started on HW, we can emit a
372 	 * breadcrumb at the beginning of the request and check its
373 	 * timeline's HWSP to see if the breadcrumb has advanced past the
374 	 * start of this request. Actually, the request must have the
375 	 * init_breadcrumb if its timeline set has_init_bread_crumb, or the
376 	 * scheduler might get a wrong state of it during reset. Since the
377 	 * requests from gvt always set the has_init_breadcrumb flag, here
378 	 * need to do the emit_init_breadcrumb for all the requests.
379 	 */
380 	if (req->engine->emit_init_breadcrumb) {
381 		err = req->engine->emit_init_breadcrumb(req);
382 		if (err) {
383 			gvt_vgpu_err("fail to emit init breadcrumb\n");
384 			return err;
385 		}
386 	}
387 
388 	/* allocate shadow ring buffer */
389 	cs = intel_ring_begin(workload->req, workload->rb_len / sizeof(u32));
390 	if (IS_ERR(cs)) {
391 		gvt_vgpu_err("fail to alloc size =%ld shadow  ring buffer\n",
392 			workload->rb_len);
393 		return PTR_ERR(cs);
394 	}
395 
396 	shadow_ring_buffer_va = workload->shadow_ring_buffer_va;
397 
398 	/* get shadow ring buffer va */
399 	workload->shadow_ring_buffer_va = cs;
400 
401 	memcpy(cs, shadow_ring_buffer_va,
402 			workload->rb_len);
403 
404 	cs += workload->rb_len / sizeof(u32);
405 	intel_ring_advance(workload->req, cs);
406 
407 	return 0;
408 }
409 
410 static void release_shadow_wa_ctx(struct intel_shadow_wa_ctx *wa_ctx)
411 {
412 	if (!wa_ctx->indirect_ctx.obj)
413 		return;
414 
415 	i915_gem_object_unpin_map(wa_ctx->indirect_ctx.obj);
416 	i915_gem_object_put(wa_ctx->indirect_ctx.obj);
417 
418 	wa_ctx->indirect_ctx.obj = NULL;
419 	wa_ctx->indirect_ctx.shadow_va = NULL;
420 }
421 
422 static void set_dma_address(struct i915_page_directory *pd, dma_addr_t addr)
423 {
424 	struct scatterlist *sg = pd->pt.base->mm.pages->sgl;
425 
426 	/* This is not a good idea */
427 	sg->dma_address = addr;
428 }
429 
430 static void set_context_ppgtt_from_shadow(struct intel_vgpu_workload *workload,
431 					  struct intel_context *ce)
432 {
433 	struct intel_vgpu_mm *mm = workload->shadow_mm;
434 	struct i915_ppgtt *ppgtt = i915_vm_to_ppgtt(ce->vm);
435 	int i = 0;
436 
437 	if (mm->ppgtt_mm.root_entry_type == GTT_TYPE_PPGTT_ROOT_L4_ENTRY) {
438 		set_dma_address(ppgtt->pd, mm->ppgtt_mm.shadow_pdps[0]);
439 	} else {
440 		for (i = 0; i < GVT_RING_CTX_NR_PDPS; i++) {
441 			struct i915_page_directory * const pd =
442 				i915_pd_entry(ppgtt->pd, i);
443 			/* skip now as current i915 ppgtt alloc won't allocate
444 			   top level pdp for non 4-level table, won't impact
445 			   shadow ppgtt. */
446 			if (!pd)
447 				break;
448 
449 			set_dma_address(pd, mm->ppgtt_mm.shadow_pdps[i]);
450 		}
451 	}
452 }
453 
454 static int
455 intel_gvt_workload_req_alloc(struct intel_vgpu_workload *workload)
456 {
457 	struct intel_vgpu *vgpu = workload->vgpu;
458 	struct intel_vgpu_submission *s = &vgpu->submission;
459 	struct i915_request *rq;
460 
461 	if (workload->req)
462 		return 0;
463 
464 	rq = i915_request_create(s->shadow[workload->engine->id]);
465 	if (IS_ERR(rq)) {
466 		gvt_vgpu_err("fail to allocate gem request\n");
467 		return PTR_ERR(rq);
468 	}
469 
470 	workload->req = i915_request_get(rq);
471 	return 0;
472 }
473 
474 /**
475  * intel_gvt_scan_and_shadow_workload - audit the workload by scanning and
476  * shadow it as well, include ringbuffer,wa_ctx and ctx.
477  * @workload: an abstract entity for each execlist submission.
478  *
479  * This function is called before the workload submitting to i915, to make
480  * sure the content of the workload is valid.
481  */
482 int intel_gvt_scan_and_shadow_workload(struct intel_vgpu_workload *workload)
483 {
484 	struct intel_vgpu *vgpu = workload->vgpu;
485 	struct intel_vgpu_submission *s = &vgpu->submission;
486 	int ret;
487 
488 	lockdep_assert_held(&vgpu->vgpu_lock);
489 
490 	if (workload->shadow)
491 		return 0;
492 
493 	if (!test_and_set_bit(workload->engine->id, s->shadow_ctx_desc_updated))
494 		shadow_context_descriptor_update(s->shadow[workload->engine->id],
495 						 workload);
496 
497 	ret = intel_gvt_scan_and_shadow_ringbuffer(workload);
498 	if (ret)
499 		return ret;
500 
501 	if (workload->engine->id == RCS0 &&
502 	    workload->wa_ctx.indirect_ctx.size) {
503 		ret = intel_gvt_scan_and_shadow_wa_ctx(&workload->wa_ctx);
504 		if (ret)
505 			goto err_shadow;
506 	}
507 
508 	workload->shadow = true;
509 	return 0;
510 
511 err_shadow:
512 	release_shadow_wa_ctx(&workload->wa_ctx);
513 	return ret;
514 }
515 
516 static void release_shadow_batch_buffer(struct intel_vgpu_workload *workload);
517 
518 static int prepare_shadow_batch_buffer(struct intel_vgpu_workload *workload)
519 {
520 	struct intel_gvt *gvt = workload->vgpu->gvt;
521 	const int gmadr_bytes = gvt->device_info.gmadr_bytes_in_cmd;
522 	struct intel_vgpu_shadow_bb *bb;
523 	int ret;
524 
525 	list_for_each_entry(bb, &workload->shadow_bb, list) {
526 		/* For privilge batch buffer and not wa_ctx, the bb_start_cmd_va
527 		 * is only updated into ring_scan_buffer, not real ring address
528 		 * allocated in later copy_workload_to_ring_buffer. pls be noted
529 		 * shadow_ring_buffer_va is now pointed to real ring buffer va
530 		 * in copy_workload_to_ring_buffer.
531 		 */
532 
533 		if (bb->bb_offset)
534 			bb->bb_start_cmd_va = workload->shadow_ring_buffer_va
535 				+ bb->bb_offset;
536 
537 		/*
538 		 * For non-priv bb, scan&shadow is only for
539 		 * debugging purpose, so the content of shadow bb
540 		 * is the same as original bb. Therefore,
541 		 * here, rather than switch to shadow bb's gma
542 		 * address, we directly use original batch buffer's
543 		 * gma address, and send original bb to hardware
544 		 * directly
545 		 */
546 		if (!bb->ppgtt) {
547 			bb->vma = i915_gem_object_ggtt_pin(bb->obj,
548 							   NULL, 0, 0, 0);
549 			if (IS_ERR(bb->vma)) {
550 				ret = PTR_ERR(bb->vma);
551 				goto err;
552 			}
553 
554 			/* relocate shadow batch buffer */
555 			bb->bb_start_cmd_va[1] = i915_ggtt_offset(bb->vma);
556 			if (gmadr_bytes == 8)
557 				bb->bb_start_cmd_va[2] = 0;
558 
559 			ret = i915_vma_move_to_active(bb->vma,
560 						      workload->req,
561 						      0);
562 			if (ret)
563 				goto err;
564 		}
565 
566 		/* No one is going to touch shadow bb from now on. */
567 		i915_gem_object_flush_map(bb->obj);
568 	}
569 	return 0;
570 err:
571 	release_shadow_batch_buffer(workload);
572 	return ret;
573 }
574 
575 static void update_wa_ctx_2_shadow_ctx(struct intel_shadow_wa_ctx *wa_ctx)
576 {
577 	struct intel_vgpu_workload *workload =
578 		container_of(wa_ctx, struct intel_vgpu_workload, wa_ctx);
579 	struct i915_request *rq = workload->req;
580 	struct execlist_ring_context *shadow_ring_context =
581 		(struct execlist_ring_context *)rq->context->lrc_reg_state;
582 
583 	shadow_ring_context->bb_per_ctx_ptr.val =
584 		(shadow_ring_context->bb_per_ctx_ptr.val &
585 		(~PER_CTX_ADDR_MASK)) | wa_ctx->per_ctx.shadow_gma;
586 	shadow_ring_context->rcs_indirect_ctx.val =
587 		(shadow_ring_context->rcs_indirect_ctx.val &
588 		(~INDIRECT_CTX_ADDR_MASK)) | wa_ctx->indirect_ctx.shadow_gma;
589 }
590 
591 static int prepare_shadow_wa_ctx(struct intel_shadow_wa_ctx *wa_ctx)
592 {
593 	struct i915_vma *vma;
594 	unsigned char *per_ctx_va =
595 		(unsigned char *)wa_ctx->indirect_ctx.shadow_va +
596 		wa_ctx->indirect_ctx.size;
597 
598 	if (wa_ctx->indirect_ctx.size == 0)
599 		return 0;
600 
601 	vma = i915_gem_object_ggtt_pin(wa_ctx->indirect_ctx.obj, NULL,
602 				       0, CACHELINE_BYTES, 0);
603 	if (IS_ERR(vma))
604 		return PTR_ERR(vma);
605 
606 	/* FIXME: we are not tracking our pinned VMA leaving it
607 	 * up to the core to fix up the stray pin_count upon
608 	 * free.
609 	 */
610 
611 	wa_ctx->indirect_ctx.shadow_gma = i915_ggtt_offset(vma);
612 
613 	wa_ctx->per_ctx.shadow_gma = *((unsigned int *)per_ctx_va + 1);
614 	memset(per_ctx_va, 0, CACHELINE_BYTES);
615 
616 	update_wa_ctx_2_shadow_ctx(wa_ctx);
617 	return 0;
618 }
619 
620 static void update_vreg_in_ctx(struct intel_vgpu_workload *workload)
621 {
622 	vgpu_vreg_t(workload->vgpu, RING_START(workload->engine->mmio_base)) =
623 		workload->rb_start;
624 }
625 
626 static void release_shadow_batch_buffer(struct intel_vgpu_workload *workload)
627 {
628 	struct intel_vgpu_shadow_bb *bb, *pos;
629 
630 	if (list_empty(&workload->shadow_bb))
631 		return;
632 
633 	bb = list_first_entry(&workload->shadow_bb,
634 			struct intel_vgpu_shadow_bb, list);
635 
636 	list_for_each_entry_safe(bb, pos, &workload->shadow_bb, list) {
637 		if (bb->obj) {
638 			if (bb->va && !IS_ERR(bb->va))
639 				i915_gem_object_unpin_map(bb->obj);
640 
641 			if (bb->vma && !IS_ERR(bb->vma))
642 				i915_vma_unpin(bb->vma);
643 
644 			i915_gem_object_put(bb->obj);
645 		}
646 		list_del(&bb->list);
647 		kfree(bb);
648 	}
649 }
650 
651 static int
652 intel_vgpu_shadow_mm_pin(struct intel_vgpu_workload *workload)
653 {
654 	struct intel_vgpu *vgpu = workload->vgpu;
655 	struct intel_vgpu_mm *m;
656 	int ret = 0;
657 
658 	ret = intel_vgpu_pin_mm(workload->shadow_mm);
659 	if (ret) {
660 		gvt_vgpu_err("fail to vgpu pin mm\n");
661 		return ret;
662 	}
663 
664 	if (workload->shadow_mm->type != INTEL_GVT_MM_PPGTT ||
665 	    !workload->shadow_mm->ppgtt_mm.shadowed) {
666 		gvt_vgpu_err("workload shadow ppgtt isn't ready\n");
667 		return -EINVAL;
668 	}
669 
670 	if (!list_empty(&workload->lri_shadow_mm)) {
671 		list_for_each_entry(m, &workload->lri_shadow_mm,
672 				    ppgtt_mm.link) {
673 			ret = intel_vgpu_pin_mm(m);
674 			if (ret) {
675 				list_for_each_entry_from_reverse(m,
676 								 &workload->lri_shadow_mm,
677 								 ppgtt_mm.link)
678 					intel_vgpu_unpin_mm(m);
679 				gvt_vgpu_err("LRI shadow ppgtt fail to pin\n");
680 				break;
681 			}
682 		}
683 	}
684 
685 	if (ret)
686 		intel_vgpu_unpin_mm(workload->shadow_mm);
687 
688 	return ret;
689 }
690 
691 static void
692 intel_vgpu_shadow_mm_unpin(struct intel_vgpu_workload *workload)
693 {
694 	struct intel_vgpu_mm *m;
695 
696 	if (!list_empty(&workload->lri_shadow_mm)) {
697 		list_for_each_entry(m, &workload->lri_shadow_mm,
698 				    ppgtt_mm.link)
699 			intel_vgpu_unpin_mm(m);
700 	}
701 	intel_vgpu_unpin_mm(workload->shadow_mm);
702 }
703 
704 static int prepare_workload(struct intel_vgpu_workload *workload)
705 {
706 	struct intel_vgpu *vgpu = workload->vgpu;
707 	struct intel_vgpu_submission *s = &vgpu->submission;
708 	int ret = 0;
709 
710 	ret = intel_vgpu_shadow_mm_pin(workload);
711 	if (ret) {
712 		gvt_vgpu_err("fail to pin shadow mm\n");
713 		return ret;
714 	}
715 
716 	update_shadow_pdps(workload);
717 
718 	set_context_ppgtt_from_shadow(workload, s->shadow[workload->engine->id]);
719 
720 	ret = intel_vgpu_sync_oos_pages(workload->vgpu);
721 	if (ret) {
722 		gvt_vgpu_err("fail to vgpu sync oos pages\n");
723 		goto err_unpin_mm;
724 	}
725 
726 	ret = intel_vgpu_flush_post_shadow(workload->vgpu);
727 	if (ret) {
728 		gvt_vgpu_err("fail to flush post shadow\n");
729 		goto err_unpin_mm;
730 	}
731 
732 	ret = copy_workload_to_ring_buffer(workload);
733 	if (ret) {
734 		gvt_vgpu_err("fail to generate request\n");
735 		goto err_unpin_mm;
736 	}
737 
738 	ret = prepare_shadow_batch_buffer(workload);
739 	if (ret) {
740 		gvt_vgpu_err("fail to prepare_shadow_batch_buffer\n");
741 		goto err_unpin_mm;
742 	}
743 
744 	ret = prepare_shadow_wa_ctx(&workload->wa_ctx);
745 	if (ret) {
746 		gvt_vgpu_err("fail to prepare_shadow_wa_ctx\n");
747 		goto err_shadow_batch;
748 	}
749 
750 	if (workload->prepare) {
751 		ret = workload->prepare(workload);
752 		if (ret)
753 			goto err_shadow_wa_ctx;
754 	}
755 
756 	return 0;
757 err_shadow_wa_ctx:
758 	release_shadow_wa_ctx(&workload->wa_ctx);
759 err_shadow_batch:
760 	release_shadow_batch_buffer(workload);
761 err_unpin_mm:
762 	intel_vgpu_shadow_mm_unpin(workload);
763 	return ret;
764 }
765 
766 static int dispatch_workload(struct intel_vgpu_workload *workload)
767 {
768 	struct intel_vgpu *vgpu = workload->vgpu;
769 	struct i915_request *rq;
770 	int ret;
771 
772 	gvt_dbg_sched("ring id %s prepare to dispatch workload %p\n",
773 		      workload->engine->name, workload);
774 
775 	mutex_lock(&vgpu->vgpu_lock);
776 
777 	ret = intel_gvt_workload_req_alloc(workload);
778 	if (ret)
779 		goto err_req;
780 
781 	ret = intel_gvt_scan_and_shadow_workload(workload);
782 	if (ret)
783 		goto out;
784 
785 	ret = populate_shadow_context(workload);
786 	if (ret) {
787 		release_shadow_wa_ctx(&workload->wa_ctx);
788 		goto out;
789 	}
790 
791 	ret = prepare_workload(workload);
792 out:
793 	if (ret) {
794 		/* We might still need to add request with
795 		 * clean ctx to retire it properly..
796 		 */
797 		rq = fetch_and_zero(&workload->req);
798 		i915_request_put(rq);
799 	}
800 
801 	if (!IS_ERR_OR_NULL(workload->req)) {
802 		gvt_dbg_sched("ring id %s submit workload to i915 %p\n",
803 			      workload->engine->name, workload->req);
804 		i915_request_add(workload->req);
805 		workload->dispatched = true;
806 	}
807 err_req:
808 	if (ret)
809 		workload->status = ret;
810 	mutex_unlock(&vgpu->vgpu_lock);
811 	return ret;
812 }
813 
814 static struct intel_vgpu_workload *
815 pick_next_workload(struct intel_gvt *gvt, struct intel_engine_cs *engine)
816 {
817 	struct intel_gvt_workload_scheduler *scheduler = &gvt->scheduler;
818 	struct intel_vgpu_workload *workload = NULL;
819 
820 	mutex_lock(&gvt->sched_lock);
821 
822 	/*
823 	 * no current vgpu / will be scheduled out / no workload
824 	 * bail out
825 	 */
826 	if (!scheduler->current_vgpu) {
827 		gvt_dbg_sched("ring %s stop - no current vgpu\n", engine->name);
828 		goto out;
829 	}
830 
831 	if (scheduler->need_reschedule) {
832 		gvt_dbg_sched("ring %s stop - will reschedule\n", engine->name);
833 		goto out;
834 	}
835 
836 	if (!scheduler->current_vgpu->active ||
837 	    list_empty(workload_q_head(scheduler->current_vgpu, engine)))
838 		goto out;
839 
840 	/*
841 	 * still have current workload, maybe the workload disptacher
842 	 * fail to submit it for some reason, resubmit it.
843 	 */
844 	if (scheduler->current_workload[engine->id]) {
845 		workload = scheduler->current_workload[engine->id];
846 		gvt_dbg_sched("ring %s still have current workload %p\n",
847 			      engine->name, workload);
848 		goto out;
849 	}
850 
851 	/*
852 	 * pick a workload as current workload
853 	 * once current workload is set, schedule policy routines
854 	 * will wait the current workload is finished when trying to
855 	 * schedule out a vgpu.
856 	 */
857 	scheduler->current_workload[engine->id] =
858 		list_first_entry(workload_q_head(scheduler->current_vgpu,
859 						 engine),
860 				 struct intel_vgpu_workload, list);
861 
862 	workload = scheduler->current_workload[engine->id];
863 
864 	gvt_dbg_sched("ring %s pick new workload %p\n", engine->name, workload);
865 
866 	atomic_inc(&workload->vgpu->submission.running_workload_num);
867 out:
868 	mutex_unlock(&gvt->sched_lock);
869 	return workload;
870 }
871 
872 static void update_guest_pdps(struct intel_vgpu *vgpu,
873 			      u64 ring_context_gpa, u32 pdp[8])
874 {
875 	u64 gpa;
876 	int i;
877 
878 	gpa = ring_context_gpa + RING_CTX_OFF(pdps[0].val);
879 
880 	for (i = 0; i < 8; i++)
881 		intel_gvt_hypervisor_write_gpa(vgpu,
882 				gpa + i * 8, &pdp[7 - i], 4);
883 }
884 
885 static __maybe_unused bool
886 check_shadow_context_ppgtt(struct execlist_ring_context *c, struct intel_vgpu_mm *m)
887 {
888 	if (m->ppgtt_mm.root_entry_type == GTT_TYPE_PPGTT_ROOT_L4_ENTRY) {
889 		u64 shadow_pdp = c->pdps[7].val | (u64) c->pdps[6].val << 32;
890 
891 		if (shadow_pdp != m->ppgtt_mm.shadow_pdps[0]) {
892 			gvt_dbg_mm("4-level context ppgtt not match LRI command\n");
893 			return false;
894 		}
895 		return true;
896 	} else {
897 		/* see comment in LRI handler in cmd_parser.c */
898 		gvt_dbg_mm("invalid shadow mm type\n");
899 		return false;
900 	}
901 }
902 
903 static void update_guest_context(struct intel_vgpu_workload *workload)
904 {
905 	struct i915_request *rq = workload->req;
906 	struct intel_vgpu *vgpu = workload->vgpu;
907 	struct execlist_ring_context *shadow_ring_context;
908 	struct intel_context *ctx = workload->req->context;
909 	void *context_base;
910 	void *src;
911 	unsigned long context_gpa, context_page_num;
912 	unsigned long gpa_base; /* first gpa of consecutive GPAs */
913 	unsigned long gpa_size; /* size of consecutive GPAs*/
914 	int i;
915 	u32 ring_base;
916 	u32 head, tail;
917 	u16 wrap_count;
918 
919 	gvt_dbg_sched("ring id %d workload lrca %x\n", rq->engine->id,
920 		      workload->ctx_desc.lrca);
921 
922 	GEM_BUG_ON(!intel_context_is_pinned(ctx));
923 
924 	head = workload->rb_head;
925 	tail = workload->rb_tail;
926 	wrap_count = workload->guest_rb_head >> RB_HEAD_WRAP_CNT_OFF;
927 
928 	if (tail < head) {
929 		if (wrap_count == RB_HEAD_WRAP_CNT_MAX)
930 			wrap_count = 0;
931 		else
932 			wrap_count += 1;
933 	}
934 
935 	head = (wrap_count << RB_HEAD_WRAP_CNT_OFF) | tail;
936 
937 	ring_base = rq->engine->mmio_base;
938 	vgpu_vreg_t(vgpu, RING_TAIL(ring_base)) = tail;
939 	vgpu_vreg_t(vgpu, RING_HEAD(ring_base)) = head;
940 
941 	context_page_num = rq->engine->context_size;
942 	context_page_num = context_page_num >> PAGE_SHIFT;
943 
944 	if (IS_BROADWELL(rq->engine->i915) && rq->engine->id == RCS0)
945 		context_page_num = 19;
946 
947 	context_base = (void *) ctx->lrc_reg_state -
948 			(LRC_STATE_PN << I915_GTT_PAGE_SHIFT);
949 
950 	/* find consecutive GPAs from gma until the first inconsecutive GPA.
951 	 * write to the consecutive GPAs from src virtual address
952 	 */
953 	gpa_size = 0;
954 	for (i = 2; i < context_page_num; i++) {
955 		context_gpa = intel_vgpu_gma_to_gpa(vgpu->gtt.ggtt_mm,
956 				(u32)((workload->ctx_desc.lrca + i) <<
957 					I915_GTT_PAGE_SHIFT));
958 		if (context_gpa == INTEL_GVT_INVALID_ADDR) {
959 			gvt_vgpu_err("invalid guest context descriptor\n");
960 			return;
961 		}
962 
963 		if (gpa_size == 0) {
964 			gpa_base = context_gpa;
965 			src = context_base + (i << I915_GTT_PAGE_SHIFT);
966 		} else if (context_gpa != gpa_base + gpa_size)
967 			goto write;
968 
969 		gpa_size += I915_GTT_PAGE_SIZE;
970 
971 		if (i == context_page_num - 1)
972 			goto write;
973 
974 		continue;
975 
976 write:
977 		intel_gvt_hypervisor_write_gpa(vgpu, gpa_base, src, gpa_size);
978 		gpa_base = context_gpa;
979 		gpa_size = I915_GTT_PAGE_SIZE;
980 		src = context_base + (i << I915_GTT_PAGE_SHIFT);
981 	}
982 
983 	intel_gvt_hypervisor_write_gpa(vgpu, workload->ring_context_gpa +
984 		RING_CTX_OFF(ring_header.val), &workload->rb_tail, 4);
985 
986 	shadow_ring_context = (void *) ctx->lrc_reg_state;
987 
988 	if (!list_empty(&workload->lri_shadow_mm)) {
989 		struct intel_vgpu_mm *m = list_last_entry(&workload->lri_shadow_mm,
990 							  struct intel_vgpu_mm,
991 							  ppgtt_mm.link);
992 		GEM_BUG_ON(!check_shadow_context_ppgtt(shadow_ring_context, m));
993 		update_guest_pdps(vgpu, workload->ring_context_gpa,
994 				  (void *)m->ppgtt_mm.guest_pdps);
995 	}
996 
997 #define COPY_REG(name) \
998 	intel_gvt_hypervisor_write_gpa(vgpu, workload->ring_context_gpa + \
999 		RING_CTX_OFF(name.val), &shadow_ring_context->name.val, 4)
1000 
1001 	COPY_REG(ctx_ctrl);
1002 	COPY_REG(ctx_timestamp);
1003 
1004 #undef COPY_REG
1005 
1006 	intel_gvt_hypervisor_write_gpa(vgpu,
1007 			workload->ring_context_gpa +
1008 			sizeof(*shadow_ring_context),
1009 			(void *)shadow_ring_context +
1010 			sizeof(*shadow_ring_context),
1011 			I915_GTT_PAGE_SIZE - sizeof(*shadow_ring_context));
1012 }
1013 
1014 void intel_vgpu_clean_workloads(struct intel_vgpu *vgpu,
1015 				intel_engine_mask_t engine_mask)
1016 {
1017 	struct intel_vgpu_submission *s = &vgpu->submission;
1018 	struct drm_i915_private *dev_priv = vgpu->gvt->gt->i915;
1019 	struct intel_engine_cs *engine;
1020 	struct intel_vgpu_workload *pos, *n;
1021 	intel_engine_mask_t tmp;
1022 
1023 	/* free the unsubmited workloads in the queues. */
1024 	for_each_engine_masked(engine, &dev_priv->gt, engine_mask, tmp) {
1025 		list_for_each_entry_safe(pos, n,
1026 			&s->workload_q_head[engine->id], list) {
1027 			list_del_init(&pos->list);
1028 			intel_vgpu_destroy_workload(pos);
1029 		}
1030 		clear_bit(engine->id, s->shadow_ctx_desc_updated);
1031 	}
1032 }
1033 
1034 static void complete_current_workload(struct intel_gvt *gvt, int ring_id)
1035 {
1036 	struct intel_gvt_workload_scheduler *scheduler = &gvt->scheduler;
1037 	struct intel_vgpu_workload *workload =
1038 		scheduler->current_workload[ring_id];
1039 	struct intel_vgpu *vgpu = workload->vgpu;
1040 	struct intel_vgpu_submission *s = &vgpu->submission;
1041 	struct i915_request *rq = workload->req;
1042 	int event;
1043 
1044 	mutex_lock(&vgpu->vgpu_lock);
1045 	mutex_lock(&gvt->sched_lock);
1046 
1047 	/* For the workload w/ request, needs to wait for the context
1048 	 * switch to make sure request is completed.
1049 	 * For the workload w/o request, directly complete the workload.
1050 	 */
1051 	if (rq) {
1052 		wait_event(workload->shadow_ctx_status_wq,
1053 			   !atomic_read(&workload->shadow_ctx_active));
1054 
1055 		/* If this request caused GPU hang, req->fence.error will
1056 		 * be set to -EIO. Use -EIO to set workload status so
1057 		 * that when this request caused GPU hang, didn't trigger
1058 		 * context switch interrupt to guest.
1059 		 */
1060 		if (likely(workload->status == -EINPROGRESS)) {
1061 			if (workload->req->fence.error == -EIO)
1062 				workload->status = -EIO;
1063 			else
1064 				workload->status = 0;
1065 		}
1066 
1067 		if (!workload->status &&
1068 		    !(vgpu->resetting_eng & BIT(ring_id))) {
1069 			update_guest_context(workload);
1070 
1071 			for_each_set_bit(event, workload->pending_events,
1072 					 INTEL_GVT_EVENT_MAX)
1073 				intel_vgpu_trigger_virtual_event(vgpu, event);
1074 		}
1075 
1076 		i915_request_put(fetch_and_zero(&workload->req));
1077 	}
1078 
1079 	gvt_dbg_sched("ring id %d complete workload %p status %d\n",
1080 			ring_id, workload, workload->status);
1081 
1082 	scheduler->current_workload[ring_id] = NULL;
1083 
1084 	list_del_init(&workload->list);
1085 
1086 	if (workload->status || vgpu->resetting_eng & BIT(ring_id)) {
1087 		/* if workload->status is not successful means HW GPU
1088 		 * has occurred GPU hang or something wrong with i915/GVT,
1089 		 * and GVT won't inject context switch interrupt to guest.
1090 		 * So this error is a vGPU hang actually to the guest.
1091 		 * According to this we should emunlate a vGPU hang. If
1092 		 * there are pending workloads which are already submitted
1093 		 * from guest, we should clean them up like HW GPU does.
1094 		 *
1095 		 * if it is in middle of engine resetting, the pending
1096 		 * workloads won't be submitted to HW GPU and will be
1097 		 * cleaned up during the resetting process later, so doing
1098 		 * the workload clean up here doesn't have any impact.
1099 		 **/
1100 		intel_vgpu_clean_workloads(vgpu, BIT(ring_id));
1101 	}
1102 
1103 	workload->complete(workload);
1104 
1105 	intel_vgpu_shadow_mm_unpin(workload);
1106 	intel_vgpu_destroy_workload(workload);
1107 
1108 	atomic_dec(&s->running_workload_num);
1109 	wake_up(&scheduler->workload_complete_wq);
1110 
1111 	if (gvt->scheduler.need_reschedule)
1112 		intel_gvt_request_service(gvt, INTEL_GVT_REQUEST_EVENT_SCHED);
1113 
1114 	mutex_unlock(&gvt->sched_lock);
1115 	mutex_unlock(&vgpu->vgpu_lock);
1116 }
1117 
1118 static int workload_thread(void *arg)
1119 {
1120 	struct intel_engine_cs *engine = arg;
1121 	const bool need_force_wake = INTEL_GEN(engine->i915) >= 9;
1122 	struct intel_gvt *gvt = engine->i915->gvt;
1123 	struct intel_gvt_workload_scheduler *scheduler = &gvt->scheduler;
1124 	struct intel_vgpu_workload *workload = NULL;
1125 	struct intel_vgpu *vgpu = NULL;
1126 	int ret;
1127 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
1128 
1129 	gvt_dbg_core("workload thread for ring %s started\n", engine->name);
1130 
1131 	while (!kthread_should_stop()) {
1132 		intel_wakeref_t wakeref;
1133 
1134 		add_wait_queue(&scheduler->waitq[engine->id], &wait);
1135 		do {
1136 			workload = pick_next_workload(gvt, engine);
1137 			if (workload)
1138 				break;
1139 			wait_woken(&wait, TASK_INTERRUPTIBLE,
1140 				   MAX_SCHEDULE_TIMEOUT);
1141 		} while (!kthread_should_stop());
1142 		remove_wait_queue(&scheduler->waitq[engine->id], &wait);
1143 
1144 		if (!workload)
1145 			break;
1146 
1147 		gvt_dbg_sched("ring %s next workload %p vgpu %d\n",
1148 			      engine->name, workload,
1149 			      workload->vgpu->id);
1150 
1151 		wakeref = intel_runtime_pm_get(engine->uncore->rpm);
1152 
1153 		gvt_dbg_sched("ring %s will dispatch workload %p\n",
1154 			      engine->name, workload);
1155 
1156 		if (need_force_wake)
1157 			intel_uncore_forcewake_get(engine->uncore,
1158 						   FORCEWAKE_ALL);
1159 		/*
1160 		 * Update the vReg of the vGPU which submitted this
1161 		 * workload. The vGPU may use these registers for checking
1162 		 * the context state. The value comes from GPU commands
1163 		 * in this workload.
1164 		 */
1165 		update_vreg_in_ctx(workload);
1166 
1167 		ret = dispatch_workload(workload);
1168 
1169 		if (ret) {
1170 			vgpu = workload->vgpu;
1171 			gvt_vgpu_err("fail to dispatch workload, skip\n");
1172 			goto complete;
1173 		}
1174 
1175 		gvt_dbg_sched("ring %s wait workload %p\n",
1176 			      engine->name, workload);
1177 		i915_request_wait(workload->req, 0, MAX_SCHEDULE_TIMEOUT);
1178 
1179 complete:
1180 		gvt_dbg_sched("will complete workload %p, status: %d\n",
1181 			      workload, workload->status);
1182 
1183 		complete_current_workload(gvt, engine->id);
1184 
1185 		if (need_force_wake)
1186 			intel_uncore_forcewake_put(engine->uncore,
1187 						   FORCEWAKE_ALL);
1188 
1189 		intel_runtime_pm_put(engine->uncore->rpm, wakeref);
1190 		if (ret && (vgpu_is_vm_unhealthy(ret)))
1191 			enter_failsafe_mode(vgpu, GVT_FAILSAFE_GUEST_ERR);
1192 	}
1193 	return 0;
1194 }
1195 
1196 void intel_gvt_wait_vgpu_idle(struct intel_vgpu *vgpu)
1197 {
1198 	struct intel_vgpu_submission *s = &vgpu->submission;
1199 	struct intel_gvt *gvt = vgpu->gvt;
1200 	struct intel_gvt_workload_scheduler *scheduler = &gvt->scheduler;
1201 
1202 	if (atomic_read(&s->running_workload_num)) {
1203 		gvt_dbg_sched("wait vgpu idle\n");
1204 
1205 		wait_event(scheduler->workload_complete_wq,
1206 				!atomic_read(&s->running_workload_num));
1207 	}
1208 }
1209 
1210 void intel_gvt_clean_workload_scheduler(struct intel_gvt *gvt)
1211 {
1212 	struct intel_gvt_workload_scheduler *scheduler = &gvt->scheduler;
1213 	struct intel_engine_cs *engine;
1214 	enum intel_engine_id i;
1215 
1216 	gvt_dbg_core("clean workload scheduler\n");
1217 
1218 	for_each_engine(engine, gvt->gt, i) {
1219 		atomic_notifier_chain_unregister(
1220 					&engine->context_status_notifier,
1221 					&gvt->shadow_ctx_notifier_block[i]);
1222 		kthread_stop(scheduler->thread[i]);
1223 	}
1224 }
1225 
1226 int intel_gvt_init_workload_scheduler(struct intel_gvt *gvt)
1227 {
1228 	struct intel_gvt_workload_scheduler *scheduler = &gvt->scheduler;
1229 	struct intel_engine_cs *engine;
1230 	enum intel_engine_id i;
1231 	int ret;
1232 
1233 	gvt_dbg_core("init workload scheduler\n");
1234 
1235 	init_waitqueue_head(&scheduler->workload_complete_wq);
1236 
1237 	for_each_engine(engine, gvt->gt, i) {
1238 		init_waitqueue_head(&scheduler->waitq[i]);
1239 
1240 		scheduler->thread[i] = kthread_run(workload_thread, engine,
1241 						   "gvt:%s", engine->name);
1242 		if (IS_ERR(scheduler->thread[i])) {
1243 			gvt_err("fail to create workload thread\n");
1244 			ret = PTR_ERR(scheduler->thread[i]);
1245 			goto err;
1246 		}
1247 
1248 		gvt->shadow_ctx_notifier_block[i].notifier_call =
1249 					shadow_context_status_change;
1250 		atomic_notifier_chain_register(&engine->context_status_notifier,
1251 					&gvt->shadow_ctx_notifier_block[i]);
1252 	}
1253 
1254 	return 0;
1255 
1256 err:
1257 	intel_gvt_clean_workload_scheduler(gvt);
1258 	return ret;
1259 }
1260 
1261 static void
1262 i915_context_ppgtt_root_restore(struct intel_vgpu_submission *s,
1263 				struct i915_ppgtt *ppgtt)
1264 {
1265 	int i;
1266 
1267 	if (i915_vm_is_4lvl(&ppgtt->vm)) {
1268 		set_dma_address(ppgtt->pd, s->i915_context_pml4);
1269 	} else {
1270 		for (i = 0; i < GEN8_3LVL_PDPES; i++) {
1271 			struct i915_page_directory * const pd =
1272 				i915_pd_entry(ppgtt->pd, i);
1273 
1274 			set_dma_address(pd, s->i915_context_pdps[i]);
1275 		}
1276 	}
1277 }
1278 
1279 /**
1280  * intel_vgpu_clean_submission - free submission-related resource for vGPU
1281  * @vgpu: a vGPU
1282  *
1283  * This function is called when a vGPU is being destroyed.
1284  *
1285  */
1286 void intel_vgpu_clean_submission(struct intel_vgpu *vgpu)
1287 {
1288 	struct intel_vgpu_submission *s = &vgpu->submission;
1289 	struct intel_engine_cs *engine;
1290 	enum intel_engine_id id;
1291 
1292 	intel_vgpu_select_submission_ops(vgpu, ALL_ENGINES, 0);
1293 
1294 	i915_context_ppgtt_root_restore(s, i915_vm_to_ppgtt(s->shadow[0]->vm));
1295 	for_each_engine(engine, vgpu->gvt->gt, id)
1296 		intel_context_put(s->shadow[id]);
1297 
1298 	kmem_cache_destroy(s->workloads);
1299 }
1300 
1301 
1302 /**
1303  * intel_vgpu_reset_submission - reset submission-related resource for vGPU
1304  * @vgpu: a vGPU
1305  * @engine_mask: engines expected to be reset
1306  *
1307  * This function is called when a vGPU is being destroyed.
1308  *
1309  */
1310 void intel_vgpu_reset_submission(struct intel_vgpu *vgpu,
1311 				 intel_engine_mask_t engine_mask)
1312 {
1313 	struct intel_vgpu_submission *s = &vgpu->submission;
1314 
1315 	if (!s->active)
1316 		return;
1317 
1318 	intel_vgpu_clean_workloads(vgpu, engine_mask);
1319 	s->ops->reset(vgpu, engine_mask);
1320 }
1321 
1322 static void
1323 i915_context_ppgtt_root_save(struct intel_vgpu_submission *s,
1324 			     struct i915_ppgtt *ppgtt)
1325 {
1326 	int i;
1327 
1328 	if (i915_vm_is_4lvl(&ppgtt->vm)) {
1329 		s->i915_context_pml4 = px_dma(ppgtt->pd);
1330 	} else {
1331 		for (i = 0; i < GEN8_3LVL_PDPES; i++) {
1332 			struct i915_page_directory * const pd =
1333 				i915_pd_entry(ppgtt->pd, i);
1334 
1335 			s->i915_context_pdps[i] = px_dma(pd);
1336 		}
1337 	}
1338 }
1339 
1340 /**
1341  * intel_vgpu_setup_submission - setup submission-related resource for vGPU
1342  * @vgpu: a vGPU
1343  *
1344  * This function is called when a vGPU is being created.
1345  *
1346  * Returns:
1347  * Zero on success, negative error code if failed.
1348  *
1349  */
1350 int intel_vgpu_setup_submission(struct intel_vgpu *vgpu)
1351 {
1352 	struct drm_i915_private *i915 = vgpu->gvt->gt->i915;
1353 	struct intel_vgpu_submission *s = &vgpu->submission;
1354 	struct intel_engine_cs *engine;
1355 	struct i915_ppgtt *ppgtt;
1356 	enum intel_engine_id i;
1357 	int ret;
1358 
1359 	ppgtt = i915_ppgtt_create(&i915->gt);
1360 	if (IS_ERR(ppgtt))
1361 		return PTR_ERR(ppgtt);
1362 
1363 	i915_context_ppgtt_root_save(s, ppgtt);
1364 
1365 	for_each_engine(engine, vgpu->gvt->gt, i) {
1366 		struct intel_context *ce;
1367 
1368 		INIT_LIST_HEAD(&s->workload_q_head[i]);
1369 		s->shadow[i] = ERR_PTR(-EINVAL);
1370 
1371 		ce = intel_context_create(engine);
1372 		if (IS_ERR(ce)) {
1373 			ret = PTR_ERR(ce);
1374 			goto out_shadow_ctx;
1375 		}
1376 
1377 		i915_vm_put(ce->vm);
1378 		ce->vm = i915_vm_get(&ppgtt->vm);
1379 		intel_context_set_single_submission(ce);
1380 
1381 		/* Max ring buffer size */
1382 		if (!intel_uc_wants_guc_submission(&engine->gt->uc)) {
1383 			const unsigned int ring_size = 512 * SZ_4K;
1384 
1385 			ce->ring = __intel_context_ring_size(ring_size);
1386 		}
1387 
1388 		s->shadow[i] = ce;
1389 	}
1390 
1391 	bitmap_zero(s->shadow_ctx_desc_updated, I915_NUM_ENGINES);
1392 
1393 	s->workloads = kmem_cache_create_usercopy("gvt-g_vgpu_workload",
1394 						  sizeof(struct intel_vgpu_workload), 0,
1395 						  SLAB_HWCACHE_ALIGN,
1396 						  offsetof(struct intel_vgpu_workload, rb_tail),
1397 						  sizeof_field(struct intel_vgpu_workload, rb_tail),
1398 						  NULL);
1399 
1400 	if (!s->workloads) {
1401 		ret = -ENOMEM;
1402 		goto out_shadow_ctx;
1403 	}
1404 
1405 	atomic_set(&s->running_workload_num, 0);
1406 	bitmap_zero(s->tlb_handle_pending, I915_NUM_ENGINES);
1407 
1408 	memset(s->last_ctx, 0, sizeof(s->last_ctx));
1409 
1410 	i915_vm_put(&ppgtt->vm);
1411 	return 0;
1412 
1413 out_shadow_ctx:
1414 	i915_context_ppgtt_root_restore(s, ppgtt);
1415 	for_each_engine(engine, vgpu->gvt->gt, i) {
1416 		if (IS_ERR(s->shadow[i]))
1417 			break;
1418 
1419 		intel_context_put(s->shadow[i]);
1420 	}
1421 	i915_vm_put(&ppgtt->vm);
1422 	return ret;
1423 }
1424 
1425 /**
1426  * intel_vgpu_select_submission_ops - select virtual submission interface
1427  * @vgpu: a vGPU
1428  * @engine_mask: either ALL_ENGINES or target engine mask
1429  * @interface: expected vGPU virtual submission interface
1430  *
1431  * This function is called when guest configures submission interface.
1432  *
1433  * Returns:
1434  * Zero on success, negative error code if failed.
1435  *
1436  */
1437 int intel_vgpu_select_submission_ops(struct intel_vgpu *vgpu,
1438 				     intel_engine_mask_t engine_mask,
1439 				     unsigned int interface)
1440 {
1441 	struct drm_i915_private *i915 = vgpu->gvt->gt->i915;
1442 	struct intel_vgpu_submission *s = &vgpu->submission;
1443 	const struct intel_vgpu_submission_ops *ops[] = {
1444 		[INTEL_VGPU_EXECLIST_SUBMISSION] =
1445 			&intel_vgpu_execlist_submission_ops,
1446 	};
1447 	int ret;
1448 
1449 	if (drm_WARN_ON(&i915->drm, interface >= ARRAY_SIZE(ops)))
1450 		return -EINVAL;
1451 
1452 	if (drm_WARN_ON(&i915->drm,
1453 			interface == 0 && engine_mask != ALL_ENGINES))
1454 		return -EINVAL;
1455 
1456 	if (s->active)
1457 		s->ops->clean(vgpu, engine_mask);
1458 
1459 	if (interface == 0) {
1460 		s->ops = NULL;
1461 		s->virtual_submission_interface = 0;
1462 		s->active = false;
1463 		gvt_dbg_core("vgpu%d: remove submission ops\n", vgpu->id);
1464 		return 0;
1465 	}
1466 
1467 	ret = ops[interface]->init(vgpu, engine_mask);
1468 	if (ret)
1469 		return ret;
1470 
1471 	s->ops = ops[interface];
1472 	s->virtual_submission_interface = interface;
1473 	s->active = true;
1474 
1475 	gvt_dbg_core("vgpu%d: activate ops [ %s ]\n",
1476 			vgpu->id, s->ops->name);
1477 
1478 	return 0;
1479 }
1480 
1481 /**
1482  * intel_vgpu_destroy_workload - destroy a vGPU workload
1483  * @workload: workload to destroy
1484  *
1485  * This function is called when destroy a vGPU workload.
1486  *
1487  */
1488 void intel_vgpu_destroy_workload(struct intel_vgpu_workload *workload)
1489 {
1490 	struct intel_vgpu_submission *s = &workload->vgpu->submission;
1491 
1492 	intel_context_unpin(s->shadow[workload->engine->id]);
1493 	release_shadow_batch_buffer(workload);
1494 	release_shadow_wa_ctx(&workload->wa_ctx);
1495 
1496 	if (!list_empty(&workload->lri_shadow_mm)) {
1497 		struct intel_vgpu_mm *m, *mm;
1498 		list_for_each_entry_safe(m, mm, &workload->lri_shadow_mm,
1499 					 ppgtt_mm.link) {
1500 			list_del(&m->ppgtt_mm.link);
1501 			intel_vgpu_mm_put(m);
1502 		}
1503 	}
1504 
1505 	GEM_BUG_ON(!list_empty(&workload->lri_shadow_mm));
1506 	if (workload->shadow_mm)
1507 		intel_vgpu_mm_put(workload->shadow_mm);
1508 
1509 	kmem_cache_free(s->workloads, workload);
1510 }
1511 
1512 static struct intel_vgpu_workload *
1513 alloc_workload(struct intel_vgpu *vgpu)
1514 {
1515 	struct intel_vgpu_submission *s = &vgpu->submission;
1516 	struct intel_vgpu_workload *workload;
1517 
1518 	workload = kmem_cache_zalloc(s->workloads, GFP_KERNEL);
1519 	if (!workload)
1520 		return ERR_PTR(-ENOMEM);
1521 
1522 	INIT_LIST_HEAD(&workload->list);
1523 	INIT_LIST_HEAD(&workload->shadow_bb);
1524 	INIT_LIST_HEAD(&workload->lri_shadow_mm);
1525 
1526 	init_waitqueue_head(&workload->shadow_ctx_status_wq);
1527 	atomic_set(&workload->shadow_ctx_active, 0);
1528 
1529 	workload->status = -EINPROGRESS;
1530 	workload->vgpu = vgpu;
1531 
1532 	return workload;
1533 }
1534 
1535 #define RING_CTX_OFF(x) \
1536 	offsetof(struct execlist_ring_context, x)
1537 
1538 static void read_guest_pdps(struct intel_vgpu *vgpu,
1539 		u64 ring_context_gpa, u32 pdp[8])
1540 {
1541 	u64 gpa;
1542 	int i;
1543 
1544 	gpa = ring_context_gpa + RING_CTX_OFF(pdps[0].val);
1545 
1546 	for (i = 0; i < 8; i++)
1547 		intel_gvt_hypervisor_read_gpa(vgpu,
1548 				gpa + i * 8, &pdp[7 - i], 4);
1549 }
1550 
1551 static int prepare_mm(struct intel_vgpu_workload *workload)
1552 {
1553 	struct execlist_ctx_descriptor_format *desc = &workload->ctx_desc;
1554 	struct intel_vgpu_mm *mm;
1555 	struct intel_vgpu *vgpu = workload->vgpu;
1556 	enum intel_gvt_gtt_type root_entry_type;
1557 	u64 pdps[GVT_RING_CTX_NR_PDPS];
1558 
1559 	switch (desc->addressing_mode) {
1560 	case 1: /* legacy 32-bit */
1561 		root_entry_type = GTT_TYPE_PPGTT_ROOT_L3_ENTRY;
1562 		break;
1563 	case 3: /* legacy 64-bit */
1564 		root_entry_type = GTT_TYPE_PPGTT_ROOT_L4_ENTRY;
1565 		break;
1566 	default:
1567 		gvt_vgpu_err("Advanced Context mode(SVM) is not supported!\n");
1568 		return -EINVAL;
1569 	}
1570 
1571 	read_guest_pdps(workload->vgpu, workload->ring_context_gpa, (void *)pdps);
1572 
1573 	mm = intel_vgpu_get_ppgtt_mm(workload->vgpu, root_entry_type, pdps);
1574 	if (IS_ERR(mm))
1575 		return PTR_ERR(mm);
1576 
1577 	workload->shadow_mm = mm;
1578 	return 0;
1579 }
1580 
1581 #define same_context(a, b) (((a)->context_id == (b)->context_id) && \
1582 		((a)->lrca == (b)->lrca))
1583 
1584 /**
1585  * intel_vgpu_create_workload - create a vGPU workload
1586  * @vgpu: a vGPU
1587  * @engine: the engine
1588  * @desc: a guest context descriptor
1589  *
1590  * This function is called when creating a vGPU workload.
1591  *
1592  * Returns:
1593  * struct intel_vgpu_workload * on success, negative error code in
1594  * pointer if failed.
1595  *
1596  */
1597 struct intel_vgpu_workload *
1598 intel_vgpu_create_workload(struct intel_vgpu *vgpu,
1599 			   const struct intel_engine_cs *engine,
1600 			   struct execlist_ctx_descriptor_format *desc)
1601 {
1602 	struct intel_vgpu_submission *s = &vgpu->submission;
1603 	struct list_head *q = workload_q_head(vgpu, engine);
1604 	struct intel_vgpu_workload *last_workload = NULL;
1605 	struct intel_vgpu_workload *workload = NULL;
1606 	u64 ring_context_gpa;
1607 	u32 head, tail, start, ctl, ctx_ctl, per_ctx, indirect_ctx;
1608 	u32 guest_head;
1609 	int ret;
1610 
1611 	ring_context_gpa = intel_vgpu_gma_to_gpa(vgpu->gtt.ggtt_mm,
1612 			(u32)((desc->lrca + 1) << I915_GTT_PAGE_SHIFT));
1613 	if (ring_context_gpa == INTEL_GVT_INVALID_ADDR) {
1614 		gvt_vgpu_err("invalid guest context LRCA: %x\n", desc->lrca);
1615 		return ERR_PTR(-EINVAL);
1616 	}
1617 
1618 	intel_gvt_hypervisor_read_gpa(vgpu, ring_context_gpa +
1619 			RING_CTX_OFF(ring_header.val), &head, 4);
1620 
1621 	intel_gvt_hypervisor_read_gpa(vgpu, ring_context_gpa +
1622 			RING_CTX_OFF(ring_tail.val), &tail, 4);
1623 
1624 	guest_head = head;
1625 
1626 	head &= RB_HEAD_OFF_MASK;
1627 	tail &= RB_TAIL_OFF_MASK;
1628 
1629 	list_for_each_entry_reverse(last_workload, q, list) {
1630 
1631 		if (same_context(&last_workload->ctx_desc, desc)) {
1632 			gvt_dbg_el("ring %s cur workload == last\n",
1633 				   engine->name);
1634 			gvt_dbg_el("ctx head %x real head %lx\n", head,
1635 				   last_workload->rb_tail);
1636 			/*
1637 			 * cannot use guest context head pointer here,
1638 			 * as it might not be updated at this time
1639 			 */
1640 			head = last_workload->rb_tail;
1641 			break;
1642 		}
1643 	}
1644 
1645 	gvt_dbg_el("ring %s begin a new workload\n", engine->name);
1646 
1647 	/* record some ring buffer register values for scan and shadow */
1648 	intel_gvt_hypervisor_read_gpa(vgpu, ring_context_gpa +
1649 			RING_CTX_OFF(rb_start.val), &start, 4);
1650 	intel_gvt_hypervisor_read_gpa(vgpu, ring_context_gpa +
1651 			RING_CTX_OFF(rb_ctrl.val), &ctl, 4);
1652 	intel_gvt_hypervisor_read_gpa(vgpu, ring_context_gpa +
1653 			RING_CTX_OFF(ctx_ctrl.val), &ctx_ctl, 4);
1654 
1655 	if (!intel_gvt_ggtt_validate_range(vgpu, start,
1656 				_RING_CTL_BUF_SIZE(ctl))) {
1657 		gvt_vgpu_err("context contain invalid rb at: 0x%x\n", start);
1658 		return ERR_PTR(-EINVAL);
1659 	}
1660 
1661 	workload = alloc_workload(vgpu);
1662 	if (IS_ERR(workload))
1663 		return workload;
1664 
1665 	workload->engine = engine;
1666 	workload->ctx_desc = *desc;
1667 	workload->ring_context_gpa = ring_context_gpa;
1668 	workload->rb_head = head;
1669 	workload->guest_rb_head = guest_head;
1670 	workload->rb_tail = tail;
1671 	workload->rb_start = start;
1672 	workload->rb_ctl = ctl;
1673 
1674 	if (engine->id == RCS0) {
1675 		intel_gvt_hypervisor_read_gpa(vgpu, ring_context_gpa +
1676 			RING_CTX_OFF(bb_per_ctx_ptr.val), &per_ctx, 4);
1677 		intel_gvt_hypervisor_read_gpa(vgpu, ring_context_gpa +
1678 			RING_CTX_OFF(rcs_indirect_ctx.val), &indirect_ctx, 4);
1679 
1680 		workload->wa_ctx.indirect_ctx.guest_gma =
1681 			indirect_ctx & INDIRECT_CTX_ADDR_MASK;
1682 		workload->wa_ctx.indirect_ctx.size =
1683 			(indirect_ctx & INDIRECT_CTX_SIZE_MASK) *
1684 			CACHELINE_BYTES;
1685 
1686 		if (workload->wa_ctx.indirect_ctx.size != 0) {
1687 			if (!intel_gvt_ggtt_validate_range(vgpu,
1688 				workload->wa_ctx.indirect_ctx.guest_gma,
1689 				workload->wa_ctx.indirect_ctx.size)) {
1690 				gvt_vgpu_err("invalid wa_ctx at: 0x%lx\n",
1691 				    workload->wa_ctx.indirect_ctx.guest_gma);
1692 				kmem_cache_free(s->workloads, workload);
1693 				return ERR_PTR(-EINVAL);
1694 			}
1695 		}
1696 
1697 		workload->wa_ctx.per_ctx.guest_gma =
1698 			per_ctx & PER_CTX_ADDR_MASK;
1699 		workload->wa_ctx.per_ctx.valid = per_ctx & 1;
1700 		if (workload->wa_ctx.per_ctx.valid) {
1701 			if (!intel_gvt_ggtt_validate_range(vgpu,
1702 				workload->wa_ctx.per_ctx.guest_gma,
1703 				CACHELINE_BYTES)) {
1704 				gvt_vgpu_err("invalid per_ctx at: 0x%lx\n",
1705 					workload->wa_ctx.per_ctx.guest_gma);
1706 				kmem_cache_free(s->workloads, workload);
1707 				return ERR_PTR(-EINVAL);
1708 			}
1709 		}
1710 	}
1711 
1712 	gvt_dbg_el("workload %p ring %s head %x tail %x start %x ctl %x\n",
1713 		   workload, engine->name, head, tail, start, ctl);
1714 
1715 	ret = prepare_mm(workload);
1716 	if (ret) {
1717 		kmem_cache_free(s->workloads, workload);
1718 		return ERR_PTR(ret);
1719 	}
1720 
1721 	/* Only scan and shadow the first workload in the queue
1722 	 * as there is only one pre-allocated buf-obj for shadow.
1723 	 */
1724 	if (list_empty(q)) {
1725 		intel_wakeref_t wakeref;
1726 
1727 		with_intel_runtime_pm(engine->gt->uncore->rpm, wakeref)
1728 			ret = intel_gvt_scan_and_shadow_workload(workload);
1729 	}
1730 
1731 	if (ret) {
1732 		if (vgpu_is_vm_unhealthy(ret))
1733 			enter_failsafe_mode(vgpu, GVT_FAILSAFE_GUEST_ERR);
1734 		intel_vgpu_destroy_workload(workload);
1735 		return ERR_PTR(ret);
1736 	}
1737 
1738 	ret = intel_context_pin(s->shadow[engine->id]);
1739 	if (ret) {
1740 		intel_vgpu_destroy_workload(workload);
1741 		return ERR_PTR(ret);
1742 	}
1743 
1744 	return workload;
1745 }
1746 
1747 /**
1748  * intel_vgpu_queue_workload - Qeue a vGPU workload
1749  * @workload: the workload to queue in
1750  */
1751 void intel_vgpu_queue_workload(struct intel_vgpu_workload *workload)
1752 {
1753 	list_add_tail(&workload->list,
1754 		      workload_q_head(workload->vgpu, workload->engine));
1755 	intel_gvt_kick_schedule(workload->vgpu->gvt);
1756 	wake_up(&workload->vgpu->gvt->scheduler.waitq[workload->engine->id]);
1757 }
1758