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