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