xref: /linux/drivers/gpu/drm/amd/amdgpu/amdgpu_ctx.c (revision 3ccdad15ae81a65875e4fe961f4e9c80b6d15829)
1 /*
2  * Copyright 2015 Advanced Micro Devices, Inc.
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 shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
17  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
18  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20  * OTHER DEALINGS IN THE SOFTWARE.
21  *
22  * Authors: monk liu <monk.liu@amd.com>
23  */
24 
25 #include <drm/drm_auth.h>
26 #include <drm/drm_drv.h>
27 #include "amdgpu.h"
28 #include "amdgpu_sched.h"
29 #include "amdgpu_ras.h"
30 #include <linux/nospec.h>
31 
32 #define to_amdgpu_ctx_entity(e)	\
33 	container_of((e), struct amdgpu_ctx_entity, entity)
34 
35 const unsigned int amdgpu_ctx_num_entities[AMDGPU_HW_IP_NUM] = {
36 	[AMDGPU_HW_IP_GFX]	=	1,
37 	[AMDGPU_HW_IP_COMPUTE]	=	4,
38 	[AMDGPU_HW_IP_DMA]	=	2,
39 	[AMDGPU_HW_IP_UVD]	=	1,
40 	[AMDGPU_HW_IP_VCE]	=	1,
41 	[AMDGPU_HW_IP_UVD_ENC]	=	1,
42 	[AMDGPU_HW_IP_VCN_DEC]	=	1,
43 	[AMDGPU_HW_IP_VCN_ENC]	=	1,
44 	[AMDGPU_HW_IP_VCN_JPEG]	=	1,
45 	[AMDGPU_HW_IP_VPE]	=	1,
46 };
47 
48 bool amdgpu_ctx_priority_is_valid(int32_t ctx_prio)
49 {
50 	switch (ctx_prio) {
51 	case AMDGPU_CTX_PRIORITY_VERY_LOW:
52 	case AMDGPU_CTX_PRIORITY_LOW:
53 	case AMDGPU_CTX_PRIORITY_NORMAL:
54 	case AMDGPU_CTX_PRIORITY_HIGH:
55 	case AMDGPU_CTX_PRIORITY_VERY_HIGH:
56 		return true;
57 	default:
58 	case AMDGPU_CTX_PRIORITY_UNSET:
59 		/* UNSET priority is not valid and we don't carry that
60 		 * around, but set it to NORMAL in the only place this
61 		 * function is called, amdgpu_ctx_ioctl().
62 		 */
63 		return false;
64 	}
65 }
66 
67 static enum drm_sched_priority
68 amdgpu_ctx_to_drm_sched_prio(int32_t ctx_prio)
69 {
70 	switch (ctx_prio) {
71 	case AMDGPU_CTX_PRIORITY_UNSET:
72 		pr_warn_once("AMD-->DRM context priority value UNSET-->NORMAL");
73 		return DRM_SCHED_PRIORITY_NORMAL;
74 
75 	case AMDGPU_CTX_PRIORITY_VERY_LOW:
76 		return DRM_SCHED_PRIORITY_LOW;
77 
78 	case AMDGPU_CTX_PRIORITY_LOW:
79 		return DRM_SCHED_PRIORITY_LOW;
80 
81 	case AMDGPU_CTX_PRIORITY_NORMAL:
82 		return DRM_SCHED_PRIORITY_NORMAL;
83 
84 	case AMDGPU_CTX_PRIORITY_HIGH:
85 		return DRM_SCHED_PRIORITY_HIGH;
86 
87 	case AMDGPU_CTX_PRIORITY_VERY_HIGH:
88 		return DRM_SCHED_PRIORITY_HIGH;
89 
90 	/* This should not happen as we sanitized userspace provided priority
91 	 * already, WARN if this happens.
92 	 */
93 	default:
94 		WARN(1, "Invalid context priority %d\n", ctx_prio);
95 		return DRM_SCHED_PRIORITY_NORMAL;
96 	}
97 
98 }
99 
100 static int amdgpu_ctx_priority_permit(struct drm_file *filp,
101 				      int32_t priority)
102 {
103 	/* NORMAL and below are accessible by everyone */
104 	if (priority <= AMDGPU_CTX_PRIORITY_NORMAL)
105 		return 0;
106 
107 	if (capable(CAP_SYS_NICE))
108 		return 0;
109 
110 	if (drm_is_current_master(filp))
111 		return 0;
112 
113 	return -EACCES;
114 }
115 
116 static enum amdgpu_gfx_pipe_priority amdgpu_ctx_prio_to_gfx_pipe_prio(int32_t prio)
117 {
118 	switch (prio) {
119 	case AMDGPU_CTX_PRIORITY_HIGH:
120 	case AMDGPU_CTX_PRIORITY_VERY_HIGH:
121 		return AMDGPU_GFX_PIPE_PRIO_HIGH;
122 	default:
123 		return AMDGPU_GFX_PIPE_PRIO_NORMAL;
124 	}
125 }
126 
127 static enum amdgpu_ring_priority_level amdgpu_ctx_sched_prio_to_ring_prio(int32_t prio)
128 {
129 	switch (prio) {
130 	case AMDGPU_CTX_PRIORITY_HIGH:
131 		return AMDGPU_RING_PRIO_1;
132 	case AMDGPU_CTX_PRIORITY_VERY_HIGH:
133 		return AMDGPU_RING_PRIO_2;
134 	default:
135 		return AMDGPU_RING_PRIO_0;
136 	}
137 }
138 
139 static unsigned int amdgpu_ctx_get_hw_prio(struct amdgpu_ctx *ctx, u32 hw_ip)
140 {
141 	struct amdgpu_device *adev = ctx->mgr->adev;
142 	unsigned int hw_prio;
143 	int32_t ctx_prio;
144 
145 	ctx_prio = (ctx->override_priority == AMDGPU_CTX_PRIORITY_UNSET) ?
146 			ctx->init_priority : ctx->override_priority;
147 
148 	switch (hw_ip) {
149 	case AMDGPU_HW_IP_GFX:
150 	case AMDGPU_HW_IP_COMPUTE:
151 		hw_prio = amdgpu_ctx_prio_to_gfx_pipe_prio(ctx_prio);
152 		break;
153 	case AMDGPU_HW_IP_VCE:
154 	case AMDGPU_HW_IP_VCN_ENC:
155 		hw_prio = amdgpu_ctx_sched_prio_to_ring_prio(ctx_prio);
156 		break;
157 	default:
158 		hw_prio = AMDGPU_RING_PRIO_DEFAULT;
159 		break;
160 	}
161 
162 	hw_ip = array_index_nospec(hw_ip, AMDGPU_HW_IP_NUM);
163 	if (adev->gpu_sched[hw_ip][hw_prio].num_scheds == 0)
164 		hw_prio = AMDGPU_RING_PRIO_DEFAULT;
165 
166 	return hw_prio;
167 }
168 
169 /* Calculate the time spend on the hw */
170 static ktime_t amdgpu_ctx_fence_time(struct dma_fence *fence)
171 {
172 	struct drm_sched_fence *s_fence;
173 
174 	if (!fence)
175 		return ns_to_ktime(0);
176 
177 	/* When the fence is not even scheduled it can't have spend time */
178 	s_fence = to_drm_sched_fence(fence);
179 	if (!test_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &s_fence->scheduled.flags))
180 		return ns_to_ktime(0);
181 
182 	/* When it is still running account how much already spend */
183 	if (!test_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &s_fence->finished.flags))
184 		return ktime_sub(ktime_get(), s_fence->scheduled.timestamp);
185 
186 	return ktime_sub(s_fence->finished.timestamp,
187 			 s_fence->scheduled.timestamp);
188 }
189 
190 static ktime_t amdgpu_ctx_entity_time(struct amdgpu_ctx *ctx,
191 				      struct amdgpu_ctx_entity *centity)
192 {
193 	ktime_t res = ns_to_ktime(0);
194 	uint32_t i;
195 
196 	spin_lock(&ctx->ring_lock);
197 	for (i = 0; i < amdgpu_sched_jobs; i++) {
198 		res = ktime_add(res, amdgpu_ctx_fence_time(centity->fences[i]));
199 	}
200 	spin_unlock(&ctx->ring_lock);
201 	return res;
202 }
203 
204 static int amdgpu_ctx_init_entity(struct amdgpu_ctx *ctx, u32 hw_ip,
205 				  const u32 ring)
206 {
207 	struct drm_gpu_scheduler **scheds = NULL, *sched = NULL;
208 	struct amdgpu_device *adev = ctx->mgr->adev;
209 	struct amdgpu_ctx_entity *entity;
210 	enum drm_sched_priority drm_prio;
211 	unsigned int hw_prio, num_scheds;
212 	int32_t ctx_prio;
213 	int r;
214 
215 	entity = kzalloc_flex(*entity, fences, amdgpu_sched_jobs);
216 	if (!entity)
217 		return  -ENOMEM;
218 
219 	ctx_prio = (ctx->override_priority == AMDGPU_CTX_PRIORITY_UNSET) ?
220 			ctx->init_priority : ctx->override_priority;
221 	entity->hw_ip = hw_ip;
222 	entity->sequence = 1;
223 	hw_prio = amdgpu_ctx_get_hw_prio(ctx, hw_ip);
224 	drm_prio = amdgpu_ctx_to_drm_sched_prio(ctx_prio);
225 
226 	hw_ip = array_index_nospec(hw_ip, AMDGPU_HW_IP_NUM);
227 
228 	if (!(adev)->xcp_mgr) {
229 		scheds = adev->gpu_sched[hw_ip][hw_prio].sched;
230 		num_scheds = adev->gpu_sched[hw_ip][hw_prio].num_scheds;
231 	} else {
232 		struct amdgpu_fpriv *fpriv;
233 
234 		/* TODO: Stop using fpriv here, we only need the xcp_id. */
235 		fpriv = container_of(ctx->mgr, struct amdgpu_fpriv, ctx_mgr);
236 		r = amdgpu_xcp_select_scheds(adev, hw_ip, hw_prio, fpriv,
237 						&num_scheds, &scheds);
238 		if (r)
239 			goto error_free_entity;
240 	}
241 
242 	if (num_scheds == 0) {
243 		r = -EINVAL;
244 		goto error_free_entity;
245 	}
246 
247 	/* disable load balance if the hw engine retains context among dependent jobs */
248 	if (hw_ip == AMDGPU_HW_IP_VCN_ENC ||
249 	    hw_ip == AMDGPU_HW_IP_VCN_DEC ||
250 	    hw_ip == AMDGPU_HW_IP_UVD_ENC ||
251 	    hw_ip == AMDGPU_HW_IP_UVD) {
252 		sched = drm_sched_pick_best(scheds, num_scheds);
253 		scheds = &sched;
254 		num_scheds = 1;
255 	}
256 
257 	r = drm_sched_entity_init(&entity->entity, drm_prio, scheds, num_scheds,
258 				  &ctx->guilty);
259 	if (r)
260 		goto error_free_entity;
261 
262 	/* It's not an error if we fail to install the new entity */
263 	if (cmpxchg(&ctx->entities[hw_ip][ring], NULL, entity))
264 		goto cleanup_entity;
265 
266 	return 0;
267 
268 cleanup_entity:
269 	drm_sched_entity_fini(&entity->entity);
270 
271 error_free_entity:
272 	kfree(entity);
273 
274 	return r;
275 }
276 
277 static ktime_t amdgpu_ctx_fini_entity(struct amdgpu_device *adev,
278 				  struct amdgpu_ctx_entity *entity)
279 {
280 	ktime_t res = ns_to_ktime(0);
281 	int i;
282 
283 	if (!entity)
284 		return res;
285 
286 	for (i = 0; i < amdgpu_sched_jobs; ++i) {
287 		res = ktime_add(res, amdgpu_ctx_fence_time(entity->fences[i]));
288 		dma_fence_put(entity->fences[i]);
289 	}
290 
291 	amdgpu_xcp_release_sched(adev, entity);
292 
293 	kfree(entity);
294 	return res;
295 }
296 
297 static int amdgpu_ctx_get_stable_pstate(struct amdgpu_ctx *ctx,
298 					u32 *stable_pstate)
299 {
300 	struct amdgpu_device *adev = ctx->mgr->adev;
301 	enum amd_dpm_forced_level current_level;
302 
303 	current_level = amdgpu_dpm_get_performance_level(adev);
304 
305 	switch (current_level) {
306 	case AMD_DPM_FORCED_LEVEL_PROFILE_STANDARD:
307 		*stable_pstate = AMDGPU_CTX_STABLE_PSTATE_STANDARD;
308 		break;
309 	case AMD_DPM_FORCED_LEVEL_PROFILE_MIN_SCLK:
310 		*stable_pstate = AMDGPU_CTX_STABLE_PSTATE_MIN_SCLK;
311 		break;
312 	case AMD_DPM_FORCED_LEVEL_PROFILE_MIN_MCLK:
313 		*stable_pstate = AMDGPU_CTX_STABLE_PSTATE_MIN_MCLK;
314 		break;
315 	case AMD_DPM_FORCED_LEVEL_PROFILE_PEAK:
316 		*stable_pstate = AMDGPU_CTX_STABLE_PSTATE_PEAK;
317 		break;
318 	default:
319 		*stable_pstate = AMDGPU_CTX_STABLE_PSTATE_NONE;
320 		break;
321 	}
322 	return 0;
323 }
324 
325 static int amdgpu_ctx_init(struct amdgpu_ctx_mgr *mgr, int32_t priority,
326 			   struct drm_file *filp, struct amdgpu_ctx *ctx)
327 {
328 	struct amdgpu_fpriv *fpriv = filp->driver_priv;
329 	u32 current_stable_pstate;
330 	int r;
331 
332 	r = amdgpu_ctx_priority_permit(filp, priority);
333 	if (r)
334 		return r;
335 
336 	memset(ctx, 0, sizeof(*ctx));
337 
338 	kref_init(&ctx->refcount);
339 	ctx->mgr = mgr;
340 	spin_lock_init(&ctx->ring_lock);
341 
342 	ctx->reset_counter = atomic_read(&mgr->adev->gpu_reset_counter);
343 	ctx->reset_counter_query = ctx->reset_counter;
344 	ctx->generation = amdgpu_vm_generation(mgr->adev, &fpriv->vm);
345 	ctx->init_priority = priority;
346 	ctx->override_priority = AMDGPU_CTX_PRIORITY_UNSET;
347 
348 	r = amdgpu_ctx_get_stable_pstate(ctx, &current_stable_pstate);
349 	if (r)
350 		return r;
351 
352 	if (mgr->adev->pm.stable_pstate_ctx)
353 		ctx->stable_pstate = mgr->adev->pm.stable_pstate_ctx->stable_pstate;
354 	else
355 		ctx->stable_pstate = current_stable_pstate;
356 
357 	return 0;
358 }
359 
360 static int amdgpu_ctx_set_stable_pstate(struct amdgpu_ctx *ctx,
361 					u32 stable_pstate)
362 {
363 	struct amdgpu_device *adev = ctx->mgr->adev;
364 	enum amd_dpm_forced_level level;
365 	u32 current_stable_pstate;
366 	int r;
367 
368 	mutex_lock(&adev->pm.stable_pstate_ctx_lock);
369 	if (adev->pm.stable_pstate_ctx && adev->pm.stable_pstate_ctx != ctx) {
370 		r = -EBUSY;
371 		goto done;
372 	}
373 
374 	r = amdgpu_ctx_get_stable_pstate(ctx, &current_stable_pstate);
375 	if (r || (stable_pstate == current_stable_pstate))
376 		goto done;
377 
378 	switch (stable_pstate) {
379 	case AMDGPU_CTX_STABLE_PSTATE_NONE:
380 		level = AMD_DPM_FORCED_LEVEL_AUTO;
381 		break;
382 	case AMDGPU_CTX_STABLE_PSTATE_STANDARD:
383 		level = AMD_DPM_FORCED_LEVEL_PROFILE_STANDARD;
384 		break;
385 	case AMDGPU_CTX_STABLE_PSTATE_MIN_SCLK:
386 		level = AMD_DPM_FORCED_LEVEL_PROFILE_MIN_SCLK;
387 		break;
388 	case AMDGPU_CTX_STABLE_PSTATE_MIN_MCLK:
389 		level = AMD_DPM_FORCED_LEVEL_PROFILE_MIN_MCLK;
390 		break;
391 	case AMDGPU_CTX_STABLE_PSTATE_PEAK:
392 		level = AMD_DPM_FORCED_LEVEL_PROFILE_PEAK;
393 		break;
394 	default:
395 		r = -EINVAL;
396 		goto done;
397 	}
398 
399 	r = amdgpu_dpm_force_performance_level(adev, level);
400 
401 	if (level == AMD_DPM_FORCED_LEVEL_AUTO)
402 		adev->pm.stable_pstate_ctx = NULL;
403 	else
404 		adev->pm.stable_pstate_ctx = ctx;
405 done:
406 	mutex_unlock(&adev->pm.stable_pstate_ctx_lock);
407 
408 	return r;
409 }
410 
411 static void amdgpu_ctx_fini(struct kref *ref)
412 {
413 	struct amdgpu_ctx *ctx = container_of(ref, struct amdgpu_ctx, refcount);
414 	struct amdgpu_ctx_mgr *mgr = ctx->mgr;
415 	struct amdgpu_device *adev = mgr->adev;
416 	unsigned i, j, idx;
417 
418 	if (!adev)
419 		return;
420 
421 	for (i = 0; i < AMDGPU_HW_IP_NUM; ++i) {
422 		for (j = 0; j < AMDGPU_MAX_ENTITY_NUM; ++j) {
423 			ktime_t spend;
424 
425 			spend = amdgpu_ctx_fini_entity(adev, ctx->entities[i][j]);
426 			atomic64_add(ktime_to_ns(spend), &mgr->time_spend[i]);
427 		}
428 	}
429 
430 	if (drm_dev_enter(adev_to_drm(adev), &idx)) {
431 		amdgpu_ctx_set_stable_pstate(ctx, ctx->stable_pstate);
432 		drm_dev_exit(idx);
433 	}
434 
435 	kfree(ctx);
436 }
437 
438 int amdgpu_ctx_get_entity(struct amdgpu_ctx *ctx, u32 hw_ip, u32 instance,
439 			  u32 ring, struct drm_sched_entity **entity)
440 {
441 	int r;
442 	struct drm_sched_entity *ctx_entity;
443 
444 	if (hw_ip >= AMDGPU_HW_IP_NUM) {
445 		drm_err(adev_to_drm(ctx->mgr->adev),
446 			"unknown HW IP type: %d\n", hw_ip);
447 		return -EINVAL;
448 	}
449 
450 	/* Right now all IPs have only one instance - multiple rings. */
451 	if (instance != 0) {
452 		drm_dbg(adev_to_drm(ctx->mgr->adev),
453 			"invalid ip instance: %d\n", instance);
454 		return -EINVAL;
455 	}
456 
457 	if (ring >= amdgpu_ctx_num_entities[hw_ip]) {
458 		drm_dbg(adev_to_drm(ctx->mgr->adev),
459 			"invalid ring: %d %d\n", hw_ip, ring);
460 		return -EINVAL;
461 	}
462 
463 	if (ctx->entities[hw_ip][ring] == NULL) {
464 		r = amdgpu_ctx_init_entity(ctx, hw_ip, ring);
465 		if (r)
466 			return r;
467 	}
468 
469 	ctx_entity = &ctx->entities[hw_ip][ring]->entity;
470 	r = drm_sched_entity_error(ctx_entity);
471 	if (r) {
472 		DRM_DEBUG("error entity %p\n", ctx_entity);
473 		return r;
474 	}
475 
476 	*entity = ctx_entity;
477 	return 0;
478 }
479 
480 static int amdgpu_ctx_alloc(struct amdgpu_device *adev,
481 			    struct amdgpu_fpriv *fpriv,
482 			    struct drm_file *filp,
483 			    int32_t priority,
484 			    uint32_t *id)
485 {
486 	struct amdgpu_ctx_mgr *mgr = &fpriv->ctx_mgr;
487 	struct amdgpu_ctx *ctx;
488 	int r;
489 
490 	ctx = kmalloc_obj(*ctx);
491 	if (!ctx)
492 		return -ENOMEM;
493 
494 	mutex_lock(&mgr->lock);
495 	r = idr_alloc(&mgr->ctx_handles, ctx, 1, AMDGPU_VM_MAX_NUM_CTX, GFP_KERNEL);
496 	if (r < 0) {
497 		mutex_unlock(&mgr->lock);
498 		kfree(ctx);
499 		return r;
500 	}
501 
502 	*id = (uint32_t)r;
503 	r = amdgpu_ctx_init(mgr, priority, filp, ctx);
504 	if (r) {
505 		idr_remove(&mgr->ctx_handles, *id);
506 		*id = 0;
507 		kfree(ctx);
508 	}
509 	mutex_unlock(&mgr->lock);
510 	return r;
511 }
512 
513 static void amdgpu_ctx_do_release(struct kref *ref)
514 {
515 	struct amdgpu_ctx *ctx;
516 	u32 i, j;
517 
518 	ctx = container_of(ref, struct amdgpu_ctx, refcount);
519 	for (i = 0; i < AMDGPU_HW_IP_NUM; ++i) {
520 		for (j = 0; j < amdgpu_ctx_num_entities[i]; ++j) {
521 			if (!ctx->entities[i][j])
522 				continue;
523 
524 			drm_sched_entity_destroy(&ctx->entities[i][j]->entity);
525 		}
526 	}
527 
528 	amdgpu_ctx_fini(ref);
529 }
530 
531 static int amdgpu_ctx_free(struct amdgpu_fpriv *fpriv, uint32_t id)
532 {
533 	struct amdgpu_ctx_mgr *mgr = &fpriv->ctx_mgr;
534 	struct amdgpu_ctx *ctx;
535 
536 	mutex_lock(&mgr->lock);
537 	ctx = idr_remove(&mgr->ctx_handles, id);
538 	if (ctx)
539 		kref_put(&ctx->refcount, amdgpu_ctx_do_release);
540 	mutex_unlock(&mgr->lock);
541 	return ctx ? 0 : -EINVAL;
542 }
543 
544 static int amdgpu_ctx_query(struct amdgpu_device *adev,
545 			    struct amdgpu_fpriv *fpriv, uint32_t id,
546 			    union drm_amdgpu_ctx_out *out)
547 {
548 	struct amdgpu_ctx *ctx;
549 	struct amdgpu_ctx_mgr *mgr;
550 	unsigned reset_counter;
551 
552 	if (!fpriv)
553 		return -EINVAL;
554 
555 	mgr = &fpriv->ctx_mgr;
556 	mutex_lock(&mgr->lock);
557 	ctx = idr_find(&mgr->ctx_handles, id);
558 	if (!ctx) {
559 		mutex_unlock(&mgr->lock);
560 		return -EINVAL;
561 	}
562 
563 	/* TODO: these two are always zero */
564 	out->state.flags = 0x0;
565 	out->state.hangs = 0x0;
566 
567 	/* determine if a GPU reset has occured since the last call */
568 	reset_counter = atomic_read(&adev->gpu_reset_counter);
569 	/* TODO: this should ideally return NO, GUILTY, or INNOCENT. */
570 	if (ctx->reset_counter_query == reset_counter)
571 		out->state.reset_status = AMDGPU_CTX_NO_RESET;
572 	else
573 		out->state.reset_status = AMDGPU_CTX_UNKNOWN_RESET;
574 	ctx->reset_counter_query = reset_counter;
575 
576 	mutex_unlock(&mgr->lock);
577 	return 0;
578 }
579 
580 #define AMDGPU_RAS_COUNTE_DELAY_MS 3000
581 
582 static int amdgpu_ctx_query2(struct amdgpu_device *adev,
583 			     struct amdgpu_fpriv *fpriv, uint32_t id,
584 			     union drm_amdgpu_ctx_out *out)
585 {
586 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
587 	struct amdgpu_ctx *ctx;
588 	struct amdgpu_ctx_mgr *mgr;
589 
590 	if (!fpriv)
591 		return -EINVAL;
592 
593 	mgr = &fpriv->ctx_mgr;
594 	mutex_lock(&mgr->lock);
595 	ctx = idr_find(&mgr->ctx_handles, id);
596 	if (!ctx) {
597 		mutex_unlock(&mgr->lock);
598 		return -EINVAL;
599 	}
600 
601 	out->state.flags = 0x0;
602 	out->state.hangs = 0x0;
603 
604 	if (ctx->reset_counter != atomic_read(&adev->gpu_reset_counter))
605 		out->state.flags |= AMDGPU_CTX_QUERY2_FLAGS_RESET;
606 
607 	if (ctx->generation != amdgpu_vm_generation(adev, &fpriv->vm))
608 		out->state.flags |= AMDGPU_CTX_QUERY2_FLAGS_VRAMLOST;
609 
610 	if (atomic_read(&ctx->guilty))
611 		out->state.flags |= AMDGPU_CTX_QUERY2_FLAGS_GUILTY;
612 
613 	if (amdgpu_in_reset(adev))
614 		out->state.flags |= AMDGPU_CTX_QUERY2_FLAGS_RESET_IN_PROGRESS;
615 
616 	if (adev->ras_enabled && con) {
617 		/* Return the cached values in O(1),
618 		 * and schedule delayed work to cache
619 		 * new vaues.
620 		 */
621 		int ce_count, ue_count;
622 
623 		ce_count = atomic_read(&con->ras_ce_count);
624 		ue_count = atomic_read(&con->ras_ue_count);
625 
626 		if (ce_count != ctx->ras_counter_ce) {
627 			ctx->ras_counter_ce = ce_count;
628 			out->state.flags |= AMDGPU_CTX_QUERY2_FLAGS_RAS_CE;
629 		}
630 
631 		if (ue_count != ctx->ras_counter_ue) {
632 			ctx->ras_counter_ue = ue_count;
633 			out->state.flags |= AMDGPU_CTX_QUERY2_FLAGS_RAS_UE;
634 		}
635 
636 		schedule_delayed_work(&con->ras_counte_delay_work,
637 				      msecs_to_jiffies(AMDGPU_RAS_COUNTE_DELAY_MS));
638 	}
639 
640 	mutex_unlock(&mgr->lock);
641 	return 0;
642 }
643 
644 static int amdgpu_ctx_stable_pstate(struct amdgpu_device *adev,
645 				    struct amdgpu_fpriv *fpriv, uint32_t id,
646 				    bool set, u32 *stable_pstate)
647 {
648 	struct amdgpu_ctx *ctx;
649 	struct amdgpu_ctx_mgr *mgr;
650 	int r;
651 
652 	if (!fpriv)
653 		return -EINVAL;
654 
655 	mgr = &fpriv->ctx_mgr;
656 	mutex_lock(&mgr->lock);
657 	ctx = idr_find(&mgr->ctx_handles, id);
658 	if (!ctx) {
659 		mutex_unlock(&mgr->lock);
660 		return -EINVAL;
661 	}
662 
663 	if (set)
664 		r = amdgpu_ctx_set_stable_pstate(ctx, *stable_pstate);
665 	else
666 		r = amdgpu_ctx_get_stable_pstate(ctx, stable_pstate);
667 
668 	mutex_unlock(&mgr->lock);
669 	return r;
670 }
671 
672 int amdgpu_ctx_ioctl(struct drm_device *dev, void *data,
673 		     struct drm_file *filp)
674 {
675 	int r;
676 	uint32_t id, stable_pstate;
677 	int32_t priority;
678 
679 	union drm_amdgpu_ctx *args = data;
680 	struct amdgpu_device *adev = drm_to_adev(dev);
681 	struct amdgpu_fpriv *fpriv = filp->driver_priv;
682 
683 	id = args->in.ctx_id;
684 	priority = args->in.priority;
685 
686 	/* For backwards compatibility, we need to accept ioctls with garbage
687 	 * in the priority field. Garbage values in the priority field, result
688 	 * in the priority being set to NORMAL.
689 	 */
690 	if (!amdgpu_ctx_priority_is_valid(priority))
691 		priority = AMDGPU_CTX_PRIORITY_NORMAL;
692 
693 	switch (args->in.op) {
694 	case AMDGPU_CTX_OP_ALLOC_CTX:
695 		if (args->in.flags)
696 			return -EINVAL;
697 		r = amdgpu_ctx_alloc(adev, fpriv, filp, priority, &id);
698 		args->out.alloc.ctx_id = id;
699 		break;
700 	case AMDGPU_CTX_OP_FREE_CTX:
701 		if (args->in.flags)
702 			return -EINVAL;
703 		r = amdgpu_ctx_free(fpriv, id);
704 		break;
705 	case AMDGPU_CTX_OP_QUERY_STATE:
706 		if (args->in.flags)
707 			return -EINVAL;
708 		r = amdgpu_ctx_query(adev, fpriv, id, &args->out);
709 		break;
710 	case AMDGPU_CTX_OP_QUERY_STATE2:
711 		if (args->in.flags)
712 			return -EINVAL;
713 		r = amdgpu_ctx_query2(adev, fpriv, id, &args->out);
714 		break;
715 	case AMDGPU_CTX_OP_GET_STABLE_PSTATE:
716 		if (args->in.flags)
717 			return -EINVAL;
718 		r = amdgpu_ctx_stable_pstate(adev, fpriv, id, false, &stable_pstate);
719 		if (!r)
720 			args->out.pstate.flags = stable_pstate;
721 		break;
722 	case AMDGPU_CTX_OP_SET_STABLE_PSTATE:
723 		if (args->in.flags & ~AMDGPU_CTX_STABLE_PSTATE_FLAGS_MASK)
724 			return -EINVAL;
725 		stable_pstate = args->in.flags & AMDGPU_CTX_STABLE_PSTATE_FLAGS_MASK;
726 		if (stable_pstate > AMDGPU_CTX_STABLE_PSTATE_PEAK)
727 			return -EINVAL;
728 		r = amdgpu_ctx_stable_pstate(adev, fpriv, id, true, &stable_pstate);
729 		break;
730 	default:
731 		return -EINVAL;
732 	}
733 
734 	return r;
735 }
736 
737 struct amdgpu_ctx *amdgpu_ctx_get(struct amdgpu_fpriv *fpriv, uint32_t id)
738 {
739 	struct amdgpu_ctx *ctx;
740 	struct amdgpu_ctx_mgr *mgr;
741 
742 	if (!fpriv)
743 		return NULL;
744 
745 	mgr = &fpriv->ctx_mgr;
746 
747 	mutex_lock(&mgr->lock);
748 	ctx = idr_find(&mgr->ctx_handles, id);
749 	if (ctx)
750 		kref_get(&ctx->refcount);
751 	mutex_unlock(&mgr->lock);
752 	return ctx;
753 }
754 
755 int amdgpu_ctx_put(struct amdgpu_ctx *ctx)
756 {
757 	if (ctx == NULL)
758 		return -EINVAL;
759 
760 	kref_put(&ctx->refcount, amdgpu_ctx_do_release);
761 	return 0;
762 }
763 
764 uint64_t amdgpu_ctx_add_fence(struct amdgpu_ctx *ctx,
765 			      struct drm_sched_entity *entity,
766 			      struct dma_fence *fence)
767 {
768 	struct amdgpu_ctx_entity *centity = to_amdgpu_ctx_entity(entity);
769 	uint64_t seq = centity->sequence;
770 	struct dma_fence *other = NULL;
771 	unsigned idx = 0;
772 
773 	idx = seq & (amdgpu_sched_jobs - 1);
774 	other = centity->fences[idx];
775 	WARN_ON(other && !dma_fence_is_signaled(other));
776 
777 	dma_fence_get(fence);
778 
779 	spin_lock(&ctx->ring_lock);
780 	centity->fences[idx] = fence;
781 	centity->sequence++;
782 	spin_unlock(&ctx->ring_lock);
783 
784 	atomic64_add(ktime_to_ns(amdgpu_ctx_fence_time(other)),
785 		     &ctx->mgr->time_spend[centity->hw_ip]);
786 
787 	dma_fence_put(other);
788 	return seq;
789 }
790 
791 struct dma_fence *amdgpu_ctx_get_fence(struct amdgpu_ctx *ctx,
792 				       struct drm_sched_entity *entity,
793 				       uint64_t seq)
794 {
795 	struct amdgpu_ctx_entity *centity = to_amdgpu_ctx_entity(entity);
796 	struct dma_fence *fence;
797 
798 	spin_lock(&ctx->ring_lock);
799 
800 	if (seq == ~0ull)
801 		seq = centity->sequence - 1;
802 
803 	if (seq >= centity->sequence) {
804 		spin_unlock(&ctx->ring_lock);
805 		return ERR_PTR(-EINVAL);
806 	}
807 
808 
809 	if (seq + amdgpu_sched_jobs < centity->sequence) {
810 		spin_unlock(&ctx->ring_lock);
811 		return NULL;
812 	}
813 
814 	fence = dma_fence_get(centity->fences[seq & (amdgpu_sched_jobs - 1)]);
815 	spin_unlock(&ctx->ring_lock);
816 
817 	return fence;
818 }
819 
820 static void amdgpu_ctx_set_entity_priority(struct amdgpu_ctx *ctx,
821 					   struct amdgpu_ctx_entity *aentity,
822 					   int hw_ip,
823 					   int32_t priority)
824 {
825 	struct amdgpu_device *adev = ctx->mgr->adev;
826 	unsigned int hw_prio;
827 	struct drm_gpu_scheduler **scheds = NULL;
828 	unsigned num_scheds;
829 
830 	/* set sw priority */
831 	drm_sched_entity_set_priority(&aentity->entity,
832 				      amdgpu_ctx_to_drm_sched_prio(priority));
833 
834 	/* set hw priority */
835 	if (hw_ip == AMDGPU_HW_IP_COMPUTE || hw_ip == AMDGPU_HW_IP_GFX) {
836 		hw_prio = amdgpu_ctx_get_hw_prio(ctx, hw_ip);
837 		hw_prio = array_index_nospec(hw_prio, AMDGPU_RING_PRIO_MAX);
838 		scheds = adev->gpu_sched[hw_ip][hw_prio].sched;
839 		num_scheds = adev->gpu_sched[hw_ip][hw_prio].num_scheds;
840 		drm_sched_entity_modify_sched(&aentity->entity, scheds,
841 					      num_scheds);
842 	}
843 }
844 
845 void amdgpu_ctx_priority_override(struct amdgpu_ctx *ctx,
846 				  int32_t priority)
847 {
848 	int32_t ctx_prio;
849 	unsigned i, j;
850 
851 	ctx->override_priority = priority;
852 
853 	ctx_prio = (ctx->override_priority == AMDGPU_CTX_PRIORITY_UNSET) ?
854 			ctx->init_priority : ctx->override_priority;
855 	for (i = 0; i < AMDGPU_HW_IP_NUM; ++i) {
856 		for (j = 0; j < amdgpu_ctx_num_entities[i]; ++j) {
857 			if (!ctx->entities[i][j])
858 				continue;
859 
860 			amdgpu_ctx_set_entity_priority(ctx, ctx->entities[i][j],
861 						       i, ctx_prio);
862 		}
863 	}
864 }
865 
866 int amdgpu_ctx_wait_prev_fence(struct amdgpu_ctx *ctx,
867 			       struct drm_sched_entity *entity)
868 {
869 	struct amdgpu_ctx_entity *centity = to_amdgpu_ctx_entity(entity);
870 	struct dma_fence *other;
871 	unsigned idx;
872 	long r;
873 
874 	spin_lock(&ctx->ring_lock);
875 	idx = centity->sequence & (amdgpu_sched_jobs - 1);
876 	other = dma_fence_get(centity->fences[idx]);
877 	spin_unlock(&ctx->ring_lock);
878 
879 	if (!other)
880 		return 0;
881 
882 	r = dma_fence_wait(other, true);
883 	if (r < 0 && r != -ERESTARTSYS)
884 		drm_err(adev_to_drm(ctx->mgr->adev),
885 			"AMDGPU: Error waiting for fence in ctx %p\n", ctx);
886 
887 	dma_fence_put(other);
888 	return r;
889 }
890 
891 void amdgpu_ctx_mgr_init(struct amdgpu_ctx_mgr *mgr,
892 			 struct amdgpu_device *adev)
893 {
894 	unsigned int i;
895 
896 	mgr->adev = adev;
897 	mutex_init(&mgr->lock);
898 	idr_init_base(&mgr->ctx_handles, 1);
899 
900 	for (i = 0; i < AMDGPU_HW_IP_NUM; ++i)
901 		atomic64_set(&mgr->time_spend[i], 0);
902 }
903 
904 long amdgpu_ctx_mgr_entity_flush(struct amdgpu_ctx_mgr *mgr, long timeout)
905 {
906 	struct amdgpu_ctx *ctx;
907 	struct idr *idp;
908 	uint32_t id, i, j;
909 
910 	idp = &mgr->ctx_handles;
911 
912 	mutex_lock(&mgr->lock);
913 	idr_for_each_entry(idp, ctx, id) {
914 		for (i = 0; i < AMDGPU_HW_IP_NUM; ++i) {
915 			for (j = 0; j < amdgpu_ctx_num_entities[i]; ++j) {
916 				struct drm_sched_entity *entity;
917 
918 				if (!ctx->entities[i][j])
919 					continue;
920 
921 				entity = &ctx->entities[i][j]->entity;
922 				timeout = drm_sched_entity_flush(entity, timeout);
923 			}
924 		}
925 	}
926 	mutex_unlock(&mgr->lock);
927 	return timeout;
928 }
929 
930 static void amdgpu_ctx_mgr_entity_fini(struct amdgpu_ctx_mgr *mgr)
931 {
932 	struct amdgpu_ctx *ctx;
933 	struct idr *idp;
934 	uint32_t id, i, j;
935 
936 	idp = &mgr->ctx_handles;
937 
938 	idr_for_each_entry(idp, ctx, id) {
939 		if (kref_read(&ctx->refcount) != 1) {
940 			drm_err(adev_to_drm(mgr->adev), "ctx %p is still alive\n", ctx);
941 			continue;
942 		}
943 
944 		for (i = 0; i < AMDGPU_HW_IP_NUM; ++i) {
945 			for (j = 0; j < amdgpu_ctx_num_entities[i]; ++j) {
946 				struct drm_sched_entity *entity;
947 
948 				if (!ctx->entities[i][j])
949 					continue;
950 
951 				entity = &ctx->entities[i][j]->entity;
952 				drm_sched_entity_fini(entity);
953 			}
954 		}
955 		kref_put(&ctx->refcount, amdgpu_ctx_fini);
956 	}
957 }
958 
959 void amdgpu_ctx_mgr_fini(struct amdgpu_ctx_mgr *mgr)
960 {
961 	amdgpu_ctx_mgr_entity_fini(mgr);
962 	idr_destroy(&mgr->ctx_handles);
963 	mutex_destroy(&mgr->lock);
964 }
965 
966 void amdgpu_ctx_mgr_usage(struct amdgpu_ctx_mgr *mgr,
967 			  ktime_t usage[AMDGPU_HW_IP_NUM])
968 {
969 	struct amdgpu_ctx *ctx;
970 	unsigned int hw_ip, i;
971 	uint32_t id;
972 
973 	/*
974 	 * This is a little bit racy because it can be that a ctx or a fence are
975 	 * destroyed just in the moment we try to account them. But that is ok
976 	 * since exactly that case is explicitely allowed by the interface.
977 	 */
978 	mutex_lock(&mgr->lock);
979 	for (hw_ip = 0; hw_ip < AMDGPU_HW_IP_NUM; ++hw_ip) {
980 		uint64_t ns = atomic64_read(&mgr->time_spend[hw_ip]);
981 
982 		usage[hw_ip] = ns_to_ktime(ns);
983 	}
984 
985 	idr_for_each_entry(&mgr->ctx_handles, ctx, id) {
986 		for (hw_ip = 0; hw_ip < AMDGPU_HW_IP_NUM; ++hw_ip) {
987 			for (i = 0; i < amdgpu_ctx_num_entities[hw_ip]; ++i) {
988 				struct amdgpu_ctx_entity *centity;
989 				ktime_t spend;
990 
991 				centity = ctx->entities[hw_ip][i];
992 				if (!centity)
993 					continue;
994 				spend = amdgpu_ctx_entity_time(ctx, centity);
995 				usage[hw_ip] = ktime_add(usage[hw_ip], spend);
996 			}
997 		}
998 	}
999 	mutex_unlock(&mgr->lock);
1000 }
1001