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