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  */
23 
24 #include <linux/kthread.h>
25 #include <linux/slab.h>
26 #include <linux/completion.h>
27 
28 #include <drm/drm_print.h>
29 #include <drm/gpu_scheduler.h>
30 
31 #include "gpu_scheduler_trace.h"
32 
33 #define to_drm_sched_job(sched_job)		\
34 		container_of((sched_job), struct drm_sched_job, queue_node)
35 
36 /**
37  * drm_sched_entity_init - Init a context entity used by scheduler when
38  * submit to HW ring.
39  *
40  * @entity: scheduler entity to init
41  * @priority: priority of the entity
42  * @sched_list: the list of drm scheds on which jobs from this
43  *           entity can be submitted
44  * @num_sched_list: number of drm sched in sched_list
45  * @guilty: atomic_t set to 1 when a job on this queue
46  *          is found to be guilty causing a timeout
47  *
48  * Note that the &sched_list must have at least one element to schedule the entity.
49  *
50  * For changing @priority later on at runtime see
51  * drm_sched_entity_set_priority(). For changing the set of schedulers
52  * @sched_list at runtime see drm_sched_entity_modify_sched().
53  *
54  * An entity is cleaned up by callind drm_sched_entity_fini(). See also
55  * drm_sched_entity_destroy().
56  *
57  * Returns 0 on success or a negative error code on failure.
58  */
59 int drm_sched_entity_init(struct drm_sched_entity *entity,
60 			  enum drm_sched_priority priority,
61 			  struct drm_gpu_scheduler **sched_list,
62 			  unsigned int num_sched_list,
63 			  atomic_t *guilty)
64 {
65 	if (!(entity && sched_list && (num_sched_list == 0 || sched_list[0])))
66 		return -EINVAL;
67 
68 	memset(entity, 0, sizeof(struct drm_sched_entity));
69 	INIT_LIST_HEAD(&entity->list);
70 	entity->rq = NULL;
71 	entity->guilty = guilty;
72 	entity->num_sched_list = num_sched_list;
73 	entity->priority = priority;
74 	entity->sched_list = num_sched_list > 1 ? sched_list : NULL;
75 	entity->last_scheduled = NULL;
76 
77 	if(num_sched_list)
78 		entity->rq = &sched_list[0]->sched_rq[entity->priority];
79 
80 	init_completion(&entity->entity_idle);
81 
82 	/* We start in an idle state. */
83 	complete(&entity->entity_idle);
84 
85 	spin_lock_init(&entity->rq_lock);
86 	spsc_queue_init(&entity->job_queue);
87 
88 	atomic_set(&entity->fence_seq, 0);
89 	entity->fence_context = dma_fence_context_alloc(2);
90 
91 	return 0;
92 }
93 EXPORT_SYMBOL(drm_sched_entity_init);
94 
95 /**
96  * drm_sched_entity_modify_sched - Modify sched of an entity
97  * @entity: scheduler entity to init
98  * @sched_list: the list of new drm scheds which will replace
99  *		 existing entity->sched_list
100  * @num_sched_list: number of drm sched in sched_list
101  *
102  * Note that this must be called under the same common lock for @entity as
103  * drm_sched_job_arm() and drm_sched_entity_push_job(), or the driver needs to
104  * guarantee through some other means that this is never called while new jobs
105  * can be pushed to @entity.
106  */
107 void drm_sched_entity_modify_sched(struct drm_sched_entity *entity,
108 				    struct drm_gpu_scheduler **sched_list,
109 				    unsigned int num_sched_list)
110 {
111 	WARN_ON(!num_sched_list || !sched_list);
112 
113 	entity->sched_list = sched_list;
114 	entity->num_sched_list = num_sched_list;
115 }
116 EXPORT_SYMBOL(drm_sched_entity_modify_sched);
117 
118 static bool drm_sched_entity_is_idle(struct drm_sched_entity *entity)
119 {
120 	rmb(); /* for list_empty to work without lock */
121 
122 	if (list_empty(&entity->list) ||
123 	    spsc_queue_count(&entity->job_queue) == 0 ||
124 	    entity->stopped)
125 		return true;
126 
127 	return false;
128 }
129 
130 /* Return true if entity could provide a job. */
131 bool drm_sched_entity_is_ready(struct drm_sched_entity *entity)
132 {
133 	if (spsc_queue_peek(&entity->job_queue) == NULL)
134 		return false;
135 
136 	if (READ_ONCE(entity->dependency))
137 		return false;
138 
139 	return true;
140 }
141 
142 /**
143  * drm_sched_entity_flush - Flush a context entity
144  *
145  * @entity: scheduler entity
146  * @timeout: time to wait in for Q to become empty in jiffies.
147  *
148  * Splitting drm_sched_entity_fini() into two functions, The first one does the
149  * waiting, removes the entity from the runqueue and returns an error when the
150  * process was killed.
151  *
152  * Returns the remaining time in jiffies left from the input timeout
153  */
154 long drm_sched_entity_flush(struct drm_sched_entity *entity, long timeout)
155 {
156 	struct drm_gpu_scheduler *sched;
157 	struct task_struct *last_user;
158 	long ret = timeout;
159 
160 	if (!entity->rq)
161 		return 0;
162 
163 	sched = entity->rq->sched;
164 	/**
165 	 * The client will not queue more IBs during this fini, consume existing
166 	 * queued IBs or discard them on SIGKILL
167 	 */
168 	if (current->flags & PF_EXITING) {
169 		if (timeout)
170 			ret = wait_event_timeout(
171 					sched->job_scheduled,
172 					drm_sched_entity_is_idle(entity),
173 					timeout);
174 	} else {
175 		wait_event_killable(sched->job_scheduled,
176 				    drm_sched_entity_is_idle(entity));
177 	}
178 
179 	/* For killed process disable any more IBs enqueue right now */
180 	last_user = cmpxchg(&entity->last_user, current->group_leader, NULL);
181 	if ((!last_user || last_user == current->group_leader) &&
182 	    (current->flags & PF_EXITING) && (current->exit_code == SIGKILL)) {
183 		spin_lock(&entity->rq_lock);
184 		entity->stopped = true;
185 		drm_sched_rq_remove_entity(entity->rq, entity);
186 		spin_unlock(&entity->rq_lock);
187 	}
188 
189 	return ret;
190 }
191 EXPORT_SYMBOL(drm_sched_entity_flush);
192 
193 /* Signal the scheduler finished fence when the entity in question is killed. */
194 static void drm_sched_entity_kill_jobs_cb(struct dma_fence *f,
195 					  struct dma_fence_cb *cb)
196 {
197 	struct drm_sched_job *job = container_of(cb, struct drm_sched_job,
198 						 finish_cb);
199 
200 	drm_sched_fence_finished(job->s_fence);
201 	WARN_ON(job->s_fence->parent);
202 	job->sched->ops->free_job(job);
203 }
204 
205 static struct dma_fence *
206 drm_sched_job_dependency(struct drm_sched_job *job,
207 			 struct drm_sched_entity *entity)
208 {
209 	if (!xa_empty(&job->dependencies))
210 		return xa_erase(&job->dependencies, job->last_dependency++);
211 
212 	if (job->sched->ops->dependency)
213 		return job->sched->ops->dependency(job, entity);
214 
215 	return NULL;
216 }
217 
218 static void drm_sched_entity_kill_jobs(struct drm_sched_entity *entity)
219 {
220 	struct drm_sched_job *job;
221 	struct dma_fence *f;
222 	int r;
223 
224 	while ((job = to_drm_sched_job(spsc_queue_pop(&entity->job_queue)))) {
225 		struct drm_sched_fence *s_fence = job->s_fence;
226 
227 		/* Wait for all dependencies to avoid data corruptions */
228 		while ((f = drm_sched_job_dependency(job, entity)))
229 			dma_fence_wait(f, false);
230 
231 		drm_sched_fence_scheduled(s_fence);
232 		dma_fence_set_error(&s_fence->finished, -ESRCH);
233 
234 		/*
235 		 * When pipe is hanged by older entity, new entity might
236 		 * not even have chance to submit it's first job to HW
237 		 * and so entity->last_scheduled will remain NULL
238 		 */
239 		if (!entity->last_scheduled) {
240 			drm_sched_entity_kill_jobs_cb(NULL, &job->finish_cb);
241 			continue;
242 		}
243 
244 		r = dma_fence_add_callback(entity->last_scheduled,
245 					   &job->finish_cb,
246 					   drm_sched_entity_kill_jobs_cb);
247 		if (r == -ENOENT)
248 			drm_sched_entity_kill_jobs_cb(NULL, &job->finish_cb);
249 		else if (r)
250 			DRM_ERROR("fence add callback failed (%d)\n", r);
251 	}
252 }
253 
254 /**
255  * drm_sched_entity_fini - Destroy a context entity
256  *
257  * @entity: scheduler entity
258  *
259  * Cleanups up @entity which has been initialized by drm_sched_entity_init().
260  *
261  * If there are potentially job still in flight or getting newly queued
262  * drm_sched_entity_flush() must be called first. This function then goes over
263  * the entity and signals all jobs with an error code if the process was killed.
264  */
265 void drm_sched_entity_fini(struct drm_sched_entity *entity)
266 {
267 	struct drm_gpu_scheduler *sched = NULL;
268 
269 	if (entity->rq) {
270 		sched = entity->rq->sched;
271 		drm_sched_rq_remove_entity(entity->rq, entity);
272 	}
273 
274 	/* Consumption of existing IBs wasn't completed. Forcefully
275 	 * remove them here.
276 	 */
277 	if (spsc_queue_count(&entity->job_queue)) {
278 		if (sched) {
279 			/*
280 			 * Wait for thread to idle to make sure it isn't processing
281 			 * this entity.
282 			 */
283 			wait_for_completion(&entity->entity_idle);
284 
285 		}
286 		if (entity->dependency) {
287 			dma_fence_remove_callback(entity->dependency,
288 						  &entity->cb);
289 			dma_fence_put(entity->dependency);
290 			entity->dependency = NULL;
291 		}
292 
293 		drm_sched_entity_kill_jobs(entity);
294 	}
295 
296 	dma_fence_put(entity->last_scheduled);
297 	entity->last_scheduled = NULL;
298 }
299 EXPORT_SYMBOL(drm_sched_entity_fini);
300 
301 /**
302  * drm_sched_entity_destroy - Destroy a context entity
303  * @entity: scheduler entity
304  *
305  * Calls drm_sched_entity_flush() and drm_sched_entity_fini() as a
306  * convenience wrapper.
307  */
308 void drm_sched_entity_destroy(struct drm_sched_entity *entity)
309 {
310 	drm_sched_entity_flush(entity, MAX_WAIT_SCHED_ENTITY_Q_EMPTY);
311 	drm_sched_entity_fini(entity);
312 }
313 EXPORT_SYMBOL(drm_sched_entity_destroy);
314 
315 /* drm_sched_entity_clear_dep - callback to clear the entities dependency */
316 static void drm_sched_entity_clear_dep(struct dma_fence *f,
317 				       struct dma_fence_cb *cb)
318 {
319 	struct drm_sched_entity *entity =
320 		container_of(cb, struct drm_sched_entity, cb);
321 
322 	entity->dependency = NULL;
323 	dma_fence_put(f);
324 }
325 
326 /*
327  * drm_sched_entity_clear_dep - callback to clear the entities dependency and
328  * wake up scheduler
329  */
330 static void drm_sched_entity_wakeup(struct dma_fence *f,
331 				    struct dma_fence_cb *cb)
332 {
333 	struct drm_sched_entity *entity =
334 		container_of(cb, struct drm_sched_entity, cb);
335 
336 	drm_sched_entity_clear_dep(f, cb);
337 	drm_sched_wakeup(entity->rq->sched);
338 }
339 
340 /**
341  * drm_sched_entity_set_priority - Sets priority of the entity
342  *
343  * @entity: scheduler entity
344  * @priority: scheduler priority
345  *
346  * Update the priority of runqueus used for the entity.
347  */
348 void drm_sched_entity_set_priority(struct drm_sched_entity *entity,
349 				   enum drm_sched_priority priority)
350 {
351 	spin_lock(&entity->rq_lock);
352 	entity->priority = priority;
353 	spin_unlock(&entity->rq_lock);
354 }
355 EXPORT_SYMBOL(drm_sched_entity_set_priority);
356 
357 /*
358  * Add a callback to the current dependency of the entity to wake up the
359  * scheduler when the entity becomes available.
360  */
361 static bool drm_sched_entity_add_dependency_cb(struct drm_sched_entity *entity)
362 {
363 	struct drm_gpu_scheduler *sched = entity->rq->sched;
364 	struct dma_fence *fence = entity->dependency;
365 	struct drm_sched_fence *s_fence;
366 
367 	if (fence->context == entity->fence_context ||
368 	    fence->context == entity->fence_context + 1) {
369 		/*
370 		 * Fence is a scheduled/finished fence from a job
371 		 * which belongs to the same entity, we can ignore
372 		 * fences from ourself
373 		 */
374 		dma_fence_put(entity->dependency);
375 		return false;
376 	}
377 
378 	s_fence = to_drm_sched_fence(fence);
379 	if (s_fence && s_fence->sched == sched) {
380 
381 		/*
382 		 * Fence is from the same scheduler, only need to wait for
383 		 * it to be scheduled
384 		 */
385 		fence = dma_fence_get(&s_fence->scheduled);
386 		dma_fence_put(entity->dependency);
387 		entity->dependency = fence;
388 		if (!dma_fence_add_callback(fence, &entity->cb,
389 					    drm_sched_entity_clear_dep))
390 			return true;
391 
392 		/* Ignore it when it is already scheduled */
393 		dma_fence_put(fence);
394 		return false;
395 	}
396 
397 	if (!dma_fence_add_callback(entity->dependency, &entity->cb,
398 				    drm_sched_entity_wakeup))
399 		return true;
400 
401 	dma_fence_put(entity->dependency);
402 	return false;
403 }
404 
405 struct drm_sched_job *drm_sched_entity_pop_job(struct drm_sched_entity *entity)
406 {
407 	struct drm_sched_job *sched_job;
408 
409 	sched_job = to_drm_sched_job(spsc_queue_peek(&entity->job_queue));
410 	if (!sched_job)
411 		return NULL;
412 
413 	while ((entity->dependency =
414 			drm_sched_job_dependency(sched_job, entity))) {
415 		trace_drm_sched_job_wait_dep(sched_job, entity->dependency);
416 
417 		if (drm_sched_entity_add_dependency_cb(entity))
418 			return NULL;
419 	}
420 
421 	/* skip jobs from entity that marked guilty */
422 	if (entity->guilty && atomic_read(entity->guilty))
423 		dma_fence_set_error(&sched_job->s_fence->finished, -ECANCELED);
424 
425 	dma_fence_put(entity->last_scheduled);
426 
427 	entity->last_scheduled = dma_fence_get(&sched_job->s_fence->finished);
428 
429 	/*
430 	 * If the queue is empty we allow drm_sched_entity_select_rq() to
431 	 * locklessly access ->last_scheduled. This only works if we set the
432 	 * pointer before we dequeue and if we a write barrier here.
433 	 */
434 	smp_wmb();
435 
436 	spsc_queue_pop(&entity->job_queue);
437 	return sched_job;
438 }
439 
440 void drm_sched_entity_select_rq(struct drm_sched_entity *entity)
441 {
442 	struct dma_fence *fence;
443 	struct drm_gpu_scheduler *sched;
444 	struct drm_sched_rq *rq;
445 
446 	/* single possible engine and already selected */
447 	if (!entity->sched_list)
448 		return;
449 
450 	/* queue non-empty, stay on the same engine */
451 	if (spsc_queue_count(&entity->job_queue))
452 		return;
453 
454 	/*
455 	 * Only when the queue is empty are we guaranteed that the scheduler
456 	 * thread cannot change ->last_scheduled. To enforce ordering we need
457 	 * a read barrier here. See drm_sched_entity_pop_job() for the other
458 	 * side.
459 	 */
460 	smp_rmb();
461 
462 	fence = entity->last_scheduled;
463 
464 	/* stay on the same engine if the previous job hasn't finished */
465 	if (fence && !dma_fence_is_signaled(fence))
466 		return;
467 
468 	spin_lock(&entity->rq_lock);
469 	sched = drm_sched_pick_best(entity->sched_list, entity->num_sched_list);
470 	rq = sched ? &sched->sched_rq[entity->priority] : NULL;
471 	if (rq != entity->rq) {
472 		drm_sched_rq_remove_entity(entity->rq, entity);
473 		entity->rq = rq;
474 	}
475 	spin_unlock(&entity->rq_lock);
476 
477 	if (entity->num_sched_list == 1)
478 		entity->sched_list = NULL;
479 }
480 
481 /**
482  * drm_sched_entity_push_job - Submit a job to the entity's job queue
483  * @sched_job: job to submit
484  *
485  * Note: To guarantee that the order of insertion to queue matches the job's
486  * fence sequence number this function should be called with drm_sched_job_arm()
487  * under common lock for the struct drm_sched_entity that was set up for
488  * @sched_job in drm_sched_job_init().
489  *
490  * Returns 0 for success, negative error code otherwise.
491  */
492 void drm_sched_entity_push_job(struct drm_sched_job *sched_job)
493 {
494 	struct drm_sched_entity *entity = sched_job->entity;
495 	bool first;
496 
497 	trace_drm_sched_job(sched_job, entity);
498 	atomic_inc(entity->rq->sched->score);
499 	WRITE_ONCE(entity->last_user, current->group_leader);
500 	first = spsc_queue_push(&entity->job_queue, &sched_job->queue_node);
501 
502 	/* first job wakes up scheduler */
503 	if (first) {
504 		/* Add the entity to the run queue */
505 		spin_lock(&entity->rq_lock);
506 		if (entity->stopped) {
507 			spin_unlock(&entity->rq_lock);
508 
509 			DRM_ERROR("Trying to push to a killed entity\n");
510 			return;
511 		}
512 		drm_sched_rq_add_entity(entity->rq, entity);
513 		spin_unlock(&entity->rq_lock);
514 		drm_sched_wakeup(entity->rq->sched);
515 	}
516 }
517 EXPORT_SYMBOL(drm_sched_entity_push_job);
518