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