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 static void drm_sched_entity_kill_jobs_work(struct work_struct *wrk)
194 {
195 	struct drm_sched_job *job = container_of(wrk, typeof(*job), work);
196 
197 	drm_sched_fence_finished(job->s_fence);
198 	WARN_ON(job->s_fence->parent);
199 	job->sched->ops->free_job(job);
200 }
201 
202 
203 /* Signal the scheduler finished fence when the entity in question is killed. */
204 static void drm_sched_entity_kill_jobs_cb(struct dma_fence *f,
205 					  struct dma_fence_cb *cb)
206 {
207 	struct drm_sched_job *job = container_of(cb, struct drm_sched_job,
208 						 finish_cb);
209 
210 	dma_fence_put(f);
211 	INIT_WORK(&job->work, drm_sched_entity_kill_jobs_work);
212 	schedule_work(&job->work);
213 }
214 
215 static struct dma_fence *
216 drm_sched_job_dependency(struct drm_sched_job *job,
217 			 struct drm_sched_entity *entity)
218 {
219 	if (!xa_empty(&job->dependencies))
220 		return xa_erase(&job->dependencies, job->last_dependency++);
221 
222 	if (job->sched->ops->dependency)
223 		return job->sched->ops->dependency(job, entity);
224 
225 	return NULL;
226 }
227 
228 static void drm_sched_entity_kill_jobs(struct drm_sched_entity *entity)
229 {
230 	struct drm_sched_job *job;
231 	struct dma_fence *f;
232 	int r;
233 
234 	while ((job = to_drm_sched_job(spsc_queue_pop(&entity->job_queue)))) {
235 		struct drm_sched_fence *s_fence = job->s_fence;
236 
237 		/* Wait for all dependencies to avoid data corruptions */
238 		while ((f = drm_sched_job_dependency(job, entity))) {
239 			dma_fence_wait(f, false);
240 			dma_fence_put(f);
241 		}
242 
243 		drm_sched_fence_scheduled(s_fence);
244 		dma_fence_set_error(&s_fence->finished, -ESRCH);
245 
246 		/*
247 		 * When pipe is hanged by older entity, new entity might
248 		 * not even have chance to submit it's first job to HW
249 		 * and so entity->last_scheduled will remain NULL
250 		 */
251 		if (!entity->last_scheduled) {
252 			drm_sched_entity_kill_jobs_cb(NULL, &job->finish_cb);
253 			continue;
254 		}
255 
256 		dma_fence_get(entity->last_scheduled);
257 		r = dma_fence_add_callback(entity->last_scheduled,
258 					   &job->finish_cb,
259 					   drm_sched_entity_kill_jobs_cb);
260 		if (r == -ENOENT)
261 			drm_sched_entity_kill_jobs_cb(NULL, &job->finish_cb);
262 		else if (r)
263 			DRM_ERROR("fence add callback failed (%d)\n", r);
264 	}
265 }
266 
267 /**
268  * drm_sched_entity_fini - Destroy a context entity
269  *
270  * @entity: scheduler entity
271  *
272  * Cleanups up @entity which has been initialized by drm_sched_entity_init().
273  *
274  * If there are potentially job still in flight or getting newly queued
275  * drm_sched_entity_flush() must be called first. This function then goes over
276  * the entity and signals all jobs with an error code if the process was killed.
277  */
278 void drm_sched_entity_fini(struct drm_sched_entity *entity)
279 {
280 	struct drm_gpu_scheduler *sched = NULL;
281 
282 	if (entity->rq) {
283 		sched = entity->rq->sched;
284 		drm_sched_rq_remove_entity(entity->rq, entity);
285 	}
286 
287 	/* Consumption of existing IBs wasn't completed. Forcefully
288 	 * remove them here.
289 	 */
290 	if (spsc_queue_count(&entity->job_queue)) {
291 		if (sched) {
292 			/*
293 			 * Wait for thread to idle to make sure it isn't processing
294 			 * this entity.
295 			 */
296 			wait_for_completion(&entity->entity_idle);
297 
298 		}
299 		if (entity->dependency) {
300 			dma_fence_remove_callback(entity->dependency,
301 						  &entity->cb);
302 			dma_fence_put(entity->dependency);
303 			entity->dependency = NULL;
304 		}
305 
306 		drm_sched_entity_kill_jobs(entity);
307 	}
308 
309 	dma_fence_put(entity->last_scheduled);
310 	entity->last_scheduled = NULL;
311 }
312 EXPORT_SYMBOL(drm_sched_entity_fini);
313 
314 /**
315  * drm_sched_entity_destroy - Destroy a context entity
316  * @entity: scheduler entity
317  *
318  * Calls drm_sched_entity_flush() and drm_sched_entity_fini() as a
319  * convenience wrapper.
320  */
321 void drm_sched_entity_destroy(struct drm_sched_entity *entity)
322 {
323 	drm_sched_entity_flush(entity, MAX_WAIT_SCHED_ENTITY_Q_EMPTY);
324 	drm_sched_entity_fini(entity);
325 }
326 EXPORT_SYMBOL(drm_sched_entity_destroy);
327 
328 /* drm_sched_entity_clear_dep - callback to clear the entities dependency */
329 static void drm_sched_entity_clear_dep(struct dma_fence *f,
330 				       struct dma_fence_cb *cb)
331 {
332 	struct drm_sched_entity *entity =
333 		container_of(cb, struct drm_sched_entity, cb);
334 
335 	entity->dependency = NULL;
336 	dma_fence_put(f);
337 }
338 
339 /*
340  * drm_sched_entity_clear_dep - callback to clear the entities dependency and
341  * wake up scheduler
342  */
343 static void drm_sched_entity_wakeup(struct dma_fence *f,
344 				    struct dma_fence_cb *cb)
345 {
346 	struct drm_sched_entity *entity =
347 		container_of(cb, struct drm_sched_entity, cb);
348 
349 	drm_sched_entity_clear_dep(f, cb);
350 	drm_sched_wakeup(entity->rq->sched);
351 }
352 
353 /**
354  * drm_sched_entity_set_priority - Sets priority of the entity
355  *
356  * @entity: scheduler entity
357  * @priority: scheduler priority
358  *
359  * Update the priority of runqueus used for the entity.
360  */
361 void drm_sched_entity_set_priority(struct drm_sched_entity *entity,
362 				   enum drm_sched_priority priority)
363 {
364 	spin_lock(&entity->rq_lock);
365 	entity->priority = priority;
366 	spin_unlock(&entity->rq_lock);
367 }
368 EXPORT_SYMBOL(drm_sched_entity_set_priority);
369 
370 /*
371  * Add a callback to the current dependency of the entity to wake up the
372  * scheduler when the entity becomes available.
373  */
374 static bool drm_sched_entity_add_dependency_cb(struct drm_sched_entity *entity)
375 {
376 	struct drm_gpu_scheduler *sched = entity->rq->sched;
377 	struct dma_fence *fence = entity->dependency;
378 	struct drm_sched_fence *s_fence;
379 
380 	if (fence->context == entity->fence_context ||
381 	    fence->context == entity->fence_context + 1) {
382 		/*
383 		 * Fence is a scheduled/finished fence from a job
384 		 * which belongs to the same entity, we can ignore
385 		 * fences from ourself
386 		 */
387 		dma_fence_put(entity->dependency);
388 		return false;
389 	}
390 
391 	s_fence = to_drm_sched_fence(fence);
392 	if (s_fence && s_fence->sched == sched &&
393 	    !test_bit(DRM_SCHED_FENCE_DONT_PIPELINE, &fence->flags)) {
394 
395 		/*
396 		 * Fence is from the same scheduler, only need to wait for
397 		 * it to be scheduled
398 		 */
399 		fence = dma_fence_get(&s_fence->scheduled);
400 		dma_fence_put(entity->dependency);
401 		entity->dependency = fence;
402 		if (!dma_fence_add_callback(fence, &entity->cb,
403 					    drm_sched_entity_clear_dep))
404 			return true;
405 
406 		/* Ignore it when it is already scheduled */
407 		dma_fence_put(fence);
408 		return false;
409 	}
410 
411 	if (!dma_fence_add_callback(entity->dependency, &entity->cb,
412 				    drm_sched_entity_wakeup))
413 		return true;
414 
415 	dma_fence_put(entity->dependency);
416 	return false;
417 }
418 
419 struct drm_sched_job *drm_sched_entity_pop_job(struct drm_sched_entity *entity)
420 {
421 	struct drm_sched_job *sched_job;
422 
423 	sched_job = to_drm_sched_job(spsc_queue_peek(&entity->job_queue));
424 	if (!sched_job)
425 		return NULL;
426 
427 	while ((entity->dependency =
428 			drm_sched_job_dependency(sched_job, entity))) {
429 		trace_drm_sched_job_wait_dep(sched_job, entity->dependency);
430 
431 		if (drm_sched_entity_add_dependency_cb(entity))
432 			return NULL;
433 	}
434 
435 	/* skip jobs from entity that marked guilty */
436 	if (entity->guilty && atomic_read(entity->guilty))
437 		dma_fence_set_error(&sched_job->s_fence->finished, -ECANCELED);
438 
439 	dma_fence_put(entity->last_scheduled);
440 
441 	entity->last_scheduled = dma_fence_get(&sched_job->s_fence->finished);
442 
443 	/*
444 	 * If the queue is empty we allow drm_sched_entity_select_rq() to
445 	 * locklessly access ->last_scheduled. This only works if we set the
446 	 * pointer before we dequeue and if we a write barrier here.
447 	 */
448 	smp_wmb();
449 
450 	spsc_queue_pop(&entity->job_queue);
451 	return sched_job;
452 }
453 
454 void drm_sched_entity_select_rq(struct drm_sched_entity *entity)
455 {
456 	struct dma_fence *fence;
457 	struct drm_gpu_scheduler *sched;
458 	struct drm_sched_rq *rq;
459 
460 	/* single possible engine and already selected */
461 	if (!entity->sched_list)
462 		return;
463 
464 	/* queue non-empty, stay on the same engine */
465 	if (spsc_queue_count(&entity->job_queue))
466 		return;
467 
468 	/*
469 	 * Only when the queue is empty are we guaranteed that the scheduler
470 	 * thread cannot change ->last_scheduled. To enforce ordering we need
471 	 * a read barrier here. See drm_sched_entity_pop_job() for the other
472 	 * side.
473 	 */
474 	smp_rmb();
475 
476 	fence = entity->last_scheduled;
477 
478 	/* stay on the same engine if the previous job hasn't finished */
479 	if (fence && !dma_fence_is_signaled(fence))
480 		return;
481 
482 	spin_lock(&entity->rq_lock);
483 	sched = drm_sched_pick_best(entity->sched_list, entity->num_sched_list);
484 	rq = sched ? &sched->sched_rq[entity->priority] : NULL;
485 	if (rq != entity->rq) {
486 		drm_sched_rq_remove_entity(entity->rq, entity);
487 		entity->rq = rq;
488 	}
489 	spin_unlock(&entity->rq_lock);
490 
491 	if (entity->num_sched_list == 1)
492 		entity->sched_list = NULL;
493 }
494 
495 /**
496  * drm_sched_entity_push_job - Submit a job to the entity's job queue
497  * @sched_job: job to submit
498  *
499  * Note: To guarantee that the order of insertion to queue matches the job's
500  * fence sequence number this function should be called with drm_sched_job_arm()
501  * under common lock for the struct drm_sched_entity that was set up for
502  * @sched_job in drm_sched_job_init().
503  *
504  * Returns 0 for success, negative error code otherwise.
505  */
506 void drm_sched_entity_push_job(struct drm_sched_job *sched_job)
507 {
508 	struct drm_sched_entity *entity = sched_job->entity;
509 	bool first;
510 
511 	trace_drm_sched_job(sched_job, entity);
512 	atomic_inc(entity->rq->sched->score);
513 	WRITE_ONCE(entity->last_user, current->group_leader);
514 	first = spsc_queue_push(&entity->job_queue, &sched_job->queue_node);
515 
516 	/* first job wakes up scheduler */
517 	if (first) {
518 		/* Add the entity to the run queue */
519 		spin_lock(&entity->rq_lock);
520 		if (entity->stopped) {
521 			spin_unlock(&entity->rq_lock);
522 
523 			DRM_ERROR("Trying to push to a killed entity\n");
524 			return;
525 		}
526 		drm_sched_rq_add_entity(entity->rq, entity);
527 		spin_unlock(&entity->rq_lock);
528 		drm_sched_wakeup(entity->rq->sched);
529 	}
530 }
531 EXPORT_SYMBOL(drm_sched_entity_push_job);
532