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