xref: /linux/drivers/gpu/drm/scheduler/sched_main.c (revision 16e7698bc04d3dd19d95a688e4b0297a0e28a93b)
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 /**
25  * DOC: Overview
26  *
27  * The GPU scheduler provides entities which allow userspace to push jobs
28  * into software queues which are then scheduled on a hardware run queue.
29  * The software queues have a priority among them. The scheduler selects the entities
30  * from the run queue using a FIFO. The scheduler provides dependency handling
31  * features among jobs. The driver is supposed to provide callback functions for
32  * backend operations to the scheduler like submitting a job to hardware run queue,
33  * returning the dependencies of a job etc.
34  *
35  * The organisation of the scheduler is the following:
36  *
37  * 1. Each hw run queue has one scheduler
38  * 2. Each scheduler has multiple run queues with different priorities
39  *    (e.g., HIGH_HW,HIGH_SW, KERNEL, NORMAL)
40  * 3. Each scheduler run queue has a queue of entities to schedule
41  * 4. Entities themselves maintain a queue of jobs that will be scheduled on
42  *    the hardware.
43  *
44  * The jobs in an entity are always scheduled in the order in which they were pushed.
45  *
46  * Note that once a job was taken from the entities queue and pushed to the
47  * hardware, i.e. the pending queue, the entity must not be referenced anymore
48  * through the jobs entity pointer.
49  */
50 
51 /**
52  * DOC: Flow Control
53  *
54  * The DRM GPU scheduler provides a flow control mechanism to regulate the rate
55  * in which the jobs fetched from scheduler entities are executed.
56  *
57  * In this context the &drm_gpu_scheduler keeps track of a driver specified
58  * credit limit representing the capacity of this scheduler and a credit count;
59  * every &drm_sched_job carries a driver specified number of credits.
60  *
61  * Once a job is executed (but not yet finished), the job's credits contribute
62  * to the scheduler's credit count until the job is finished. If by executing
63  * one more job the scheduler's credit count would exceed the scheduler's
64  * credit limit, the job won't be executed. Instead, the scheduler will wait
65  * until the credit count has decreased enough to not overflow its credit limit.
66  * This implies waiting for previously executed jobs.
67  */
68 
69 #include <linux/export.h>
70 #include <linux/wait.h>
71 #include <linux/sched.h>
72 #include <linux/completion.h>
73 #include <linux/dma-resv.h>
74 #include <uapi/linux/sched/types.h>
75 
76 #include <drm/drm_print.h>
77 #include <drm/drm_gem.h>
78 #include <drm/drm_syncobj.h>
79 #include <drm/gpu_scheduler.h>
80 #include <drm/spsc_queue.h>
81 
82 #include "sched_internal.h"
83 
84 #define CREATE_TRACE_POINTS
85 #include "gpu_scheduler_trace.h"
86 
87 static u32 drm_sched_available_credits(struct drm_gpu_scheduler *sched)
88 {
89 	u32 credits;
90 
91 	WARN_ON(check_sub_overflow(sched->credit_limit,
92 				   atomic_read(&sched->credit_count),
93 				   &credits));
94 
95 	return credits;
96 }
97 
98 /**
99  * drm_sched_can_queue -- Can we queue more to the hardware?
100  * @sched: scheduler instance
101  * @entity: the scheduler entity
102  *
103  * Return true if we can push at least one more job from @entity, false
104  * otherwise.
105  */
106 bool drm_sched_can_queue(struct drm_gpu_scheduler *sched,
107 			 struct drm_sched_entity *entity)
108 {
109 	struct drm_sched_job *s_job;
110 
111 	s_job = drm_sched_entity_queue_peek(entity);
112 	if (!s_job)
113 		return false;
114 
115 	/* If a job exceeds the credit limit, truncate it to the credit limit
116 	 * itself to guarantee forward progress.
117 	 */
118 	if (s_job->credits > sched->credit_limit) {
119 		dev_WARN(sched->dev,
120 			 "Jobs may not exceed the credit limit, truncate.\n");
121 		s_job->credits = sched->credit_limit;
122 	}
123 
124 	return drm_sched_available_credits(sched) >= s_job->credits;
125 }
126 
127 /**
128  * drm_sched_run_job_queue - enqueue run-job work
129  * @sched: scheduler instance
130  */
131 static void drm_sched_run_job_queue(struct drm_gpu_scheduler *sched)
132 {
133 	if (!drm_sched_is_stopped(sched))
134 		queue_work(sched->submit_wq, &sched->work_run_job);
135 }
136 
137 /**
138  * drm_sched_run_free_queue - enqueue free-job work
139  * @sched: scheduler instance
140  */
141 static void drm_sched_run_free_queue(struct drm_gpu_scheduler *sched)
142 {
143 	if (!drm_sched_is_stopped(sched))
144 		queue_work(sched->submit_wq, &sched->work_free_job);
145 }
146 
147 /**
148  * drm_sched_job_done - complete a job
149  * @s_job: pointer to the job which is done
150  * @result: 0 on success, -ERRNO on error
151  *
152  * Finish the job's fence and resubmit the work items.
153  */
154 static void drm_sched_job_done(struct drm_sched_job *s_job, int result)
155 {
156 	struct drm_sched_fence *s_fence = s_job->s_fence;
157 	struct drm_gpu_scheduler *sched = s_fence->sched;
158 
159 	atomic_sub(s_job->credits, &sched->credit_count);
160 	atomic_dec(sched->score);
161 
162 	trace_drm_sched_job_done(s_fence);
163 
164 	dma_fence_get(&s_fence->finished);
165 	drm_sched_fence_finished(s_fence, result);
166 	dma_fence_put(&s_fence->finished);
167 	drm_sched_run_free_queue(sched);
168 }
169 
170 /**
171  * drm_sched_job_done_cb - the callback for a done job
172  * @f: fence
173  * @cb: fence callbacks
174  */
175 static void drm_sched_job_done_cb(struct dma_fence *f, struct dma_fence_cb *cb)
176 {
177 	struct drm_sched_job *s_job = container_of(cb, struct drm_sched_job, cb);
178 
179 	drm_sched_job_done(s_job, f->error);
180 }
181 
182 /**
183  * drm_sched_start_timeout - start timeout for reset worker
184  *
185  * @sched: scheduler instance to start the worker for
186  *
187  * Start the timeout for the given scheduler.
188  */
189 static void drm_sched_start_timeout(struct drm_gpu_scheduler *sched)
190 {
191 	lockdep_assert_held(&sched->job_list_lock);
192 
193 	if (sched->timeout != MAX_SCHEDULE_TIMEOUT &&
194 	    !list_empty(&sched->pending_list))
195 		mod_delayed_work(sched->timeout_wq, &sched->work_tdr, sched->timeout);
196 }
197 
198 static void drm_sched_start_timeout_unlocked(struct drm_gpu_scheduler *sched)
199 {
200 	spin_lock(&sched->job_list_lock);
201 	drm_sched_start_timeout(sched);
202 	spin_unlock(&sched->job_list_lock);
203 }
204 
205 /**
206  * drm_sched_tdr_queue_imm: - immediately start job timeout handler
207  *
208  * @sched: scheduler for which the timeout handling should be started.
209  *
210  * Start timeout handling immediately for the named scheduler.
211  */
212 void drm_sched_tdr_queue_imm(struct drm_gpu_scheduler *sched)
213 {
214 	spin_lock(&sched->job_list_lock);
215 	sched->timeout = 0;
216 	drm_sched_start_timeout(sched);
217 	spin_unlock(&sched->job_list_lock);
218 }
219 EXPORT_SYMBOL(drm_sched_tdr_queue_imm);
220 
221 /**
222  * drm_sched_fault - immediately start timeout handler
223  *
224  * @sched: scheduler where the timeout handling should be started.
225  *
226  * Start timeout handling immediately when the driver detects a hardware fault.
227  */
228 void drm_sched_fault(struct drm_gpu_scheduler *sched)
229 {
230 	if (sched->timeout_wq)
231 		mod_delayed_work(sched->timeout_wq, &sched->work_tdr, 0);
232 }
233 EXPORT_SYMBOL(drm_sched_fault);
234 
235 /**
236  * drm_sched_suspend_timeout - Suspend scheduler job timeout
237  *
238  * @sched: scheduler instance for which to suspend the timeout
239  *
240  * Suspend the delayed work timeout for the scheduler. This is done by
241  * modifying the delayed work timeout to an arbitrary large value,
242  * MAX_SCHEDULE_TIMEOUT in this case.
243  *
244  * Returns the timeout remaining
245  *
246  */
247 unsigned long drm_sched_suspend_timeout(struct drm_gpu_scheduler *sched)
248 {
249 	unsigned long sched_timeout, now = jiffies;
250 
251 	sched_timeout = sched->work_tdr.timer.expires;
252 
253 	/*
254 	 * Modify the timeout to an arbitrarily large value. This also prevents
255 	 * the timeout to be restarted when new submissions arrive
256 	 */
257 	if (mod_delayed_work(sched->timeout_wq, &sched->work_tdr, MAX_SCHEDULE_TIMEOUT)
258 			&& time_after(sched_timeout, now))
259 		return sched_timeout - now;
260 	else
261 		return sched->timeout;
262 }
263 EXPORT_SYMBOL(drm_sched_suspend_timeout);
264 
265 /**
266  * drm_sched_resume_timeout - Resume scheduler job timeout
267  *
268  * @sched: scheduler instance for which to resume the timeout
269  * @remaining: remaining timeout
270  *
271  * Resume the delayed work timeout for the scheduler.
272  */
273 void drm_sched_resume_timeout(struct drm_gpu_scheduler *sched,
274 		unsigned long remaining)
275 {
276 	spin_lock(&sched->job_list_lock);
277 
278 	if (list_empty(&sched->pending_list))
279 		cancel_delayed_work(&sched->work_tdr);
280 	else
281 		mod_delayed_work(sched->timeout_wq, &sched->work_tdr, remaining);
282 
283 	spin_unlock(&sched->job_list_lock);
284 }
285 EXPORT_SYMBOL(drm_sched_resume_timeout);
286 
287 static void drm_sched_job_begin(struct drm_sched_job *s_job)
288 {
289 	struct drm_gpu_scheduler *sched = s_job->sched;
290 
291 	spin_lock(&sched->job_list_lock);
292 	list_add_tail(&s_job->list, &sched->pending_list);
293 	drm_sched_start_timeout(sched);
294 	spin_unlock(&sched->job_list_lock);
295 }
296 
297 /**
298  * drm_sched_job_reinsert_on_false_timeout - reinsert the job on a false timeout
299  * @sched: scheduler instance
300  * @job: job to be reinserted on the pending list
301  *
302  * In the case of a "false timeout" - when a timeout occurs but the GPU isn't
303  * hung and is making progress, the scheduler must reinsert the job back into
304  * @sched->pending_list. Otherwise, the job and its resources won't be freed
305  * through the &struct drm_sched_backend_ops.free_job callback.
306  *
307  * This function must be used in "false timeout" cases only.
308  */
309 static void drm_sched_job_reinsert_on_false_timeout(struct drm_gpu_scheduler *sched,
310 						    struct drm_sched_job *job)
311 {
312 	spin_lock(&sched->job_list_lock);
313 	list_add(&job->list, &sched->pending_list);
314 
315 	/* After reinserting the job, the scheduler enqueues the free-job work
316 	 * again if ready. Otherwise, a signaled job could be added to the
317 	 * pending list, but never freed.
318 	 */
319 	drm_sched_run_free_queue(sched);
320 	spin_unlock(&sched->job_list_lock);
321 }
322 
323 static void drm_sched_job_timedout(struct work_struct *work)
324 {
325 	struct drm_gpu_scheduler *sched;
326 	struct drm_sched_job *job;
327 	enum drm_gpu_sched_stat status = DRM_GPU_SCHED_STAT_RESET;
328 
329 	sched = container_of(work, struct drm_gpu_scheduler, work_tdr.work);
330 
331 	/* Protects against concurrent deletion in drm_sched_get_finished_job */
332 	spin_lock(&sched->job_list_lock);
333 	job = list_first_entry_or_null(&sched->pending_list,
334 				       struct drm_sched_job, list);
335 
336 	if (job) {
337 		/*
338 		 * Remove the bad job so it cannot be freed by a concurrent
339 		 * &struct drm_sched_backend_ops.free_job. It will be
340 		 * reinserted after the scheduler's work items have been
341 		 * cancelled, at which point it's safe.
342 		 */
343 		list_del_init(&job->list);
344 		spin_unlock(&sched->job_list_lock);
345 
346 		status = job->sched->ops->timedout_job(job);
347 
348 		/*
349 		 * Guilty job did complete and hence needs to be manually removed
350 		 * See drm_sched_stop doc.
351 		 */
352 		if (sched->free_guilty) {
353 			job->sched->ops->free_job(job);
354 			sched->free_guilty = false;
355 		}
356 
357 		if (status == DRM_GPU_SCHED_STAT_NO_HANG)
358 			drm_sched_job_reinsert_on_false_timeout(sched, job);
359 	} else {
360 		spin_unlock(&sched->job_list_lock);
361 	}
362 
363 	if (status != DRM_GPU_SCHED_STAT_ENODEV)
364 		drm_sched_start_timeout_unlocked(sched);
365 }
366 
367 /**
368  * drm_sched_stop - stop the scheduler
369  *
370  * @sched: scheduler instance
371  * @bad: job which caused the time out
372  *
373  * Stop the scheduler and also removes and frees all completed jobs.
374  * Note: bad job will not be freed as it might be used later and so it's
375  * callers responsibility to release it manually if it's not part of the
376  * pending list any more.
377  *
378  * This function is typically used for reset recovery (see the docu of
379  * drm_sched_backend_ops.timedout_job() for details). Do not call it for
380  * scheduler teardown, i.e., before calling drm_sched_fini().
381  *
382  * As it's only used for reset recovery, drivers must not call this function
383  * in their &struct drm_sched_backend_ops.timedout_job callback when they
384  * skip a reset using &enum drm_gpu_sched_stat.DRM_GPU_SCHED_STAT_NO_HANG.
385  */
386 void drm_sched_stop(struct drm_gpu_scheduler *sched, struct drm_sched_job *bad)
387 {
388 	struct drm_sched_job *s_job, *tmp;
389 
390 	drm_sched_wqueue_stop(sched);
391 
392 	/*
393 	 * Reinsert back the bad job here - now it's safe as
394 	 * drm_sched_get_finished_job() cannot race against us and release the
395 	 * bad job at this point - we parked (waited for) any in progress
396 	 * (earlier) cleanups and drm_sched_get_finished_job() will not be
397 	 * called now until the scheduler's work items are submitted again.
398 	 */
399 	if (bad && bad->sched == sched)
400 		/*
401 		 * Add at the head of the queue to reflect it was the earliest
402 		 * job extracted.
403 		 */
404 		list_add(&bad->list, &sched->pending_list);
405 
406 	/*
407 	 * Iterate the job list from later to  earlier one and either deactive
408 	 * their HW callbacks or remove them from pending list if they already
409 	 * signaled.
410 	 * This iteration is thread safe as the scheduler's work items have been
411 	 * cancelled.
412 	 */
413 	list_for_each_entry_safe_reverse(s_job, tmp, &sched->pending_list,
414 					 list) {
415 		if (s_job->s_fence->parent &&
416 		    dma_fence_remove_callback(s_job->s_fence->parent,
417 					      &s_job->cb)) {
418 			dma_fence_put(s_job->s_fence->parent);
419 			s_job->s_fence->parent = NULL;
420 			atomic_sub(s_job->credits, &sched->credit_count);
421 		} else {
422 			/*
423 			 * remove job from pending_list.
424 			 * Locking here is for concurrent resume timeout
425 			 */
426 			spin_lock(&sched->job_list_lock);
427 			list_del_init(&s_job->list);
428 			spin_unlock(&sched->job_list_lock);
429 
430 			/*
431 			 * Wait for job's HW fence callback to finish using s_job
432 			 * before releasing it.
433 			 *
434 			 * Job is still alive so fence refcount at least 1
435 			 */
436 			dma_fence_wait(&s_job->s_fence->finished, false);
437 
438 			/*
439 			 * We must keep bad job alive for later use during
440 			 * recovery by some of the drivers but leave a hint
441 			 * that the guilty job must be released.
442 			 */
443 			if (bad != s_job)
444 				sched->ops->free_job(s_job);
445 			else
446 				sched->free_guilty = true;
447 		}
448 	}
449 
450 	/*
451 	 * Stop pending timer in flight as we rearm it in  drm_sched_start. This
452 	 * avoids the pending timeout work in progress to fire right away after
453 	 * this TDR finished and before the newly restarted jobs had a
454 	 * chance to complete.
455 	 */
456 	cancel_delayed_work(&sched->work_tdr);
457 }
458 EXPORT_SYMBOL(drm_sched_stop);
459 
460 /**
461  * drm_sched_start - recover jobs after a reset
462  *
463  * @sched: scheduler instance
464  * @errno: error to set on the pending fences
465  *
466  * This function is typically used for reset recovery (see the docu of
467  * drm_sched_backend_ops.timedout_job() for details). Do not call it for
468  * scheduler startup. The scheduler itself is fully operational after
469  * drm_sched_init() succeeded.
470  *
471  * As it's only used for reset recovery, drivers must not call this function
472  * in their &struct drm_sched_backend_ops.timedout_job callback when they
473  * skip a reset using &enum drm_gpu_sched_stat.DRM_GPU_SCHED_STAT_NO_HANG.
474  */
475 void drm_sched_start(struct drm_gpu_scheduler *sched, int errno)
476 {
477 	struct drm_sched_job *s_job, *tmp;
478 
479 	/*
480 	 * Locking the list is not required here as the scheduler's work items
481 	 * are currently not running, so no new jobs are being inserted or
482 	 * removed. Also concurrent GPU recovers can't run in parallel.
483 	 */
484 	list_for_each_entry_safe(s_job, tmp, &sched->pending_list, list) {
485 		struct dma_fence *fence = s_job->s_fence->parent;
486 
487 		atomic_add(s_job->credits, &sched->credit_count);
488 
489 		if (!fence) {
490 			drm_sched_job_done(s_job, errno ?: -ECANCELED);
491 			continue;
492 		}
493 
494 		if (dma_fence_add_callback(fence, &s_job->cb,
495 					   drm_sched_job_done_cb))
496 			drm_sched_job_done(s_job, fence->error ?: errno);
497 	}
498 
499 	drm_sched_start_timeout_unlocked(sched);
500 	drm_sched_wqueue_start(sched);
501 }
502 EXPORT_SYMBOL(drm_sched_start);
503 
504 /**
505  * drm_sched_resubmit_jobs - Deprecated, don't use in new code!
506  *
507  * @sched: scheduler instance
508  *
509  * Re-submitting jobs was a concept AMD came up as cheap way to implement
510  * recovery after a job timeout.
511  *
512  * This turned out to be not working very well. First of all there are many
513  * problem with the dma_fence implementation and requirements. Either the
514  * implementation is risking deadlocks with core memory management or violating
515  * documented implementation details of the dma_fence object.
516  *
517  * Drivers can still save and restore their state for recovery operations, but
518  * we shouldn't make this a general scheduler feature around the dma_fence
519  * interface. The suggested driver-side replacement is to use
520  * drm_sched_for_each_pending_job() after stopping the scheduler and implement
521  * their own recovery operations.
522  */
523 void drm_sched_resubmit_jobs(struct drm_gpu_scheduler *sched)
524 {
525 	struct drm_sched_job *s_job, *tmp;
526 	uint64_t guilty_context;
527 	bool found_guilty = false;
528 	struct dma_fence *fence;
529 
530 	list_for_each_entry_safe(s_job, tmp, &sched->pending_list, list) {
531 		struct drm_sched_fence *s_fence = s_job->s_fence;
532 
533 		if (!found_guilty && atomic_read(&s_job->karma) > sched->hang_limit) {
534 			found_guilty = true;
535 			guilty_context = s_job->s_fence->scheduled.context;
536 		}
537 
538 		if (found_guilty && s_job->s_fence->scheduled.context == guilty_context)
539 			dma_fence_set_error(&s_fence->finished, -ECANCELED);
540 
541 		fence = sched->ops->run_job(s_job);
542 
543 		if (IS_ERR_OR_NULL(fence)) {
544 			if (IS_ERR(fence))
545 				dma_fence_set_error(&s_fence->finished, PTR_ERR(fence));
546 
547 			s_job->s_fence->parent = NULL;
548 		} else {
549 
550 			s_job->s_fence->parent = dma_fence_get(fence);
551 
552 			/* Drop for orignal kref_init */
553 			dma_fence_put(fence);
554 		}
555 	}
556 }
557 EXPORT_SYMBOL(drm_sched_resubmit_jobs);
558 
559 /**
560  * drm_sched_job_init - init a scheduler job
561  * @job: scheduler job to init
562  * @entity: scheduler entity to use
563  * @credits: the number of credits this job contributes to the schedulers
564  * credit limit
565  * @owner: job owner for debugging
566  * @drm_client_id: &struct drm_file.client_id of the owner (used by trace
567  * events)
568  *
569  * Refer to drm_sched_entity_push_job() documentation
570  * for locking considerations.
571  *
572  * Drivers must make sure drm_sched_job_cleanup() if this function returns
573  * successfully, even when @job is aborted before drm_sched_job_arm() is called.
574  *
575  * Note that this function does not assign a valid value to each struct member
576  * of struct drm_sched_job. Take a look at that struct's documentation to see
577  * who sets which struct member with what lifetime.
578  *
579  * WARNING: amdgpu abuses &drm_sched.ready to signal when the hardware
580  * has died, which can mean that there's no valid runqueue for a @entity.
581  * This function returns -ENOENT in this case (which probably should be -EIO as
582  * a more meanigful return value).
583  *
584  * Returns 0 for success, negative error code otherwise.
585  */
586 int drm_sched_job_init(struct drm_sched_job *job,
587 		       struct drm_sched_entity *entity,
588 		       u32 credits, void *owner,
589 		       uint64_t drm_client_id)
590 {
591 	if (!entity->rq) {
592 		/* This will most likely be followed by missing frames
593 		 * or worse--a blank screen--leave a trail in the
594 		 * logs, so this can be debugged easier.
595 		 */
596 		dev_err(job->sched->dev, "%s: entity has no rq!\n", __func__);
597 		return -ENOENT;
598 	}
599 
600 	if (unlikely(!credits)) {
601 		pr_err("*ERROR* %s: credits cannot be 0!\n", __func__);
602 		return -EINVAL;
603 	}
604 
605 	/*
606 	 * We don't know for sure how the user has allocated. Thus, zero the
607 	 * struct so that unallowed (i.e., too early) usage of pointers that
608 	 * this function does not set is guaranteed to lead to a NULL pointer
609 	 * exception instead of UB.
610 	 */
611 	memset(job, 0, sizeof(*job));
612 
613 	job->entity = entity;
614 	job->credits = credits;
615 	job->s_fence = drm_sched_fence_alloc(entity, owner, drm_client_id);
616 	if (!job->s_fence)
617 		return -ENOMEM;
618 
619 	INIT_LIST_HEAD(&job->list);
620 
621 	xa_init_flags(&job->dependencies, XA_FLAGS_ALLOC);
622 
623 	return 0;
624 }
625 EXPORT_SYMBOL(drm_sched_job_init);
626 
627 /**
628  * drm_sched_job_arm - arm a scheduler job for execution
629  * @job: scheduler job to arm
630  *
631  * This arms a scheduler job for execution. Specifically it initializes the
632  * &drm_sched_job.s_fence of @job, so that it can be attached to struct dma_resv
633  * or other places that need to track the completion of this job. It also
634  * initializes sequence numbers, which are fundamental for fence ordering.
635  *
636  * Refer to drm_sched_entity_push_job() documentation for locking
637  * considerations.
638  *
639  * Once this function was called, you *must* submit @job with
640  * drm_sched_entity_push_job().
641  *
642  * This can only be called if drm_sched_job_init() succeeded.
643  */
644 void drm_sched_job_arm(struct drm_sched_job *job)
645 {
646 	struct drm_gpu_scheduler *sched;
647 	struct drm_sched_entity *entity = job->entity;
648 
649 	BUG_ON(!entity);
650 	drm_sched_entity_select_rq(entity);
651 	sched = container_of(entity->rq, typeof(*sched), rq);
652 
653 	job->sched = sched;
654 	job->s_priority = entity->priority;
655 	job->entity_stats = drm_sched_entity_stats_get(entity->stats);
656 
657 	drm_sched_fence_init(job->s_fence, job->entity);
658 }
659 EXPORT_SYMBOL(drm_sched_job_arm);
660 
661 /**
662  * drm_sched_job_add_dependency - adds the fence as a job dependency
663  * @job: scheduler job to add the dependencies to
664  * @fence: the dma_fence to add to the list of dependencies.
665  *
666  * Note that @fence is consumed in both the success and error cases.
667  *
668  * Returns:
669  * 0 on success, or an error on failing to expand the array.
670  */
671 int drm_sched_job_add_dependency(struct drm_sched_job *job,
672 				 struct dma_fence *fence)
673 {
674 	struct dma_fence *entry;
675 	unsigned long index;
676 	u32 id = 0;
677 	int ret;
678 
679 	if (!fence)
680 		return 0;
681 
682 	/* Deduplicate if we already depend on a fence from the same context.
683 	 * This lets the size of the array of deps scale with the number of
684 	 * engines involved, rather than the number of BOs.
685 	 */
686 	xa_for_each(&job->dependencies, index, entry) {
687 		if (entry->context != fence->context)
688 			continue;
689 
690 		if (dma_fence_is_later(fence, entry)) {
691 			dma_fence_put(entry);
692 			xa_store(&job->dependencies, index, fence, GFP_KERNEL);
693 		} else {
694 			dma_fence_put(fence);
695 		}
696 		return 0;
697 	}
698 
699 	ret = xa_alloc(&job->dependencies, &id, fence, xa_limit_32b, GFP_KERNEL);
700 	if (ret != 0)
701 		dma_fence_put(fence);
702 
703 	return ret;
704 }
705 EXPORT_SYMBOL(drm_sched_job_add_dependency);
706 
707 /**
708  * drm_sched_job_add_syncobj_dependency - adds a syncobj's fence as a job dependency
709  * @job: scheduler job to add the dependencies to
710  * @file: drm file private pointer
711  * @handle: syncobj handle to lookup
712  * @point: timeline point
713  *
714  * This adds the fence matching the given syncobj to @job.
715  *
716  * Returns:
717  * 0 on success, or an error on failing to expand the array.
718  */
719 int drm_sched_job_add_syncobj_dependency(struct drm_sched_job *job,
720 					 struct drm_file *file,
721 					 u32 handle,
722 					 u32 point)
723 {
724 	struct dma_fence *fence;
725 	int ret;
726 
727 	ret = drm_syncobj_find_fence(file, handle, point, 0, &fence);
728 	if (ret)
729 		return ret;
730 
731 	return drm_sched_job_add_dependency(job, fence);
732 }
733 EXPORT_SYMBOL(drm_sched_job_add_syncobj_dependency);
734 
735 /**
736  * drm_sched_job_add_resv_dependencies - add all fences from the resv to the job
737  * @job: scheduler job to add the dependencies to
738  * @resv: the dma_resv object to get the fences from
739  * @usage: the dma_resv_usage to use to filter the fences
740  *
741  * This adds all fences matching the given usage from @resv to @job.
742  * Must be called with the @resv lock held.
743  *
744  * Returns:
745  * 0 on success, or an error on failing to expand the array.
746  */
747 int drm_sched_job_add_resv_dependencies(struct drm_sched_job *job,
748 					struct dma_resv *resv,
749 					enum dma_resv_usage usage)
750 {
751 	struct dma_resv_iter cursor;
752 	struct dma_fence *fence;
753 	int ret;
754 
755 	dma_resv_assert_held(resv);
756 
757 	dma_resv_for_each_fence(&cursor, resv, usage, fence) {
758 		/*
759 		 * As drm_sched_job_add_dependency always consumes the fence
760 		 * reference (even when it fails), and dma_resv_for_each_fence
761 		 * is not obtaining one, we need to grab one before calling.
762 		 */
763 		ret = drm_sched_job_add_dependency(job, dma_fence_get(fence));
764 		if (ret)
765 			return ret;
766 	}
767 	return 0;
768 }
769 EXPORT_SYMBOL(drm_sched_job_add_resv_dependencies);
770 
771 /**
772  * drm_sched_job_add_implicit_dependencies - adds implicit dependencies as job
773  *   dependencies
774  * @job: scheduler job to add the dependencies to
775  * @obj: the gem object to add new dependencies from.
776  * @write: whether the job might write the object (so we need to depend on
777  * shared fences in the reservation object).
778  *
779  * This should be called after drm_gem_lock_reservations() on your array of
780  * GEM objects used in the job but before updating the reservations with your
781  * own fences.
782  *
783  * Returns:
784  * 0 on success, or an error on failing to expand the array.
785  */
786 int drm_sched_job_add_implicit_dependencies(struct drm_sched_job *job,
787 					    struct drm_gem_object *obj,
788 					    bool write)
789 {
790 	return drm_sched_job_add_resv_dependencies(job, obj->resv,
791 						   dma_resv_usage_rw(write));
792 }
793 EXPORT_SYMBOL(drm_sched_job_add_implicit_dependencies);
794 
795 /**
796  * drm_sched_job_has_dependency - check whether fence is the job's dependency
797  * @job: scheduler job to check
798  * @fence: fence to look for
799  *
800  * Returns:
801  * True if @fence is found within the job's dependencies, or otherwise false.
802  */
803 bool drm_sched_job_has_dependency(struct drm_sched_job *job,
804 				  struct dma_fence *fence)
805 {
806 	struct dma_fence *f;
807 	unsigned long index;
808 
809 	xa_for_each(&job->dependencies, index, f) {
810 		if (f == fence)
811 			return true;
812 	}
813 
814 	return false;
815 }
816 EXPORT_SYMBOL(drm_sched_job_has_dependency);
817 
818 /**
819  * drm_sched_job_cleanup - clean up scheduler job resources
820  * @job: scheduler job to clean up
821  *
822  * Cleans up the resources allocated with drm_sched_job_init().
823  *
824  * Drivers should call this from their error unwind code if @job is aborted
825  * before drm_sched_job_arm() is called.
826  *
827  * drm_sched_job_arm() is a point of no return since it initializes the fences
828  * and their sequence number etc. Once that function has been called, you *must*
829  * submit it with drm_sched_entity_push_job() and cannot simply abort it by
830  * calling drm_sched_job_cleanup().
831  *
832  * This function should be called in the &drm_sched_backend_ops.free_job callback.
833  */
834 void drm_sched_job_cleanup(struct drm_sched_job *job)
835 {
836 	struct dma_fence *fence;
837 	unsigned long index;
838 
839 	if (kref_read(&job->s_fence->finished.refcount)) {
840 		/* The job has been processed by the scheduler, i.e.,
841 		 * drm_sched_job_arm() and drm_sched_entity_push_job() have
842 		 * been called.
843 		 */
844 		dma_fence_put(&job->s_fence->finished);
845 		drm_sched_entity_stats_put(job->entity_stats);
846 	} else {
847 		/* The job was aborted before it has been committed to be run;
848 		 * notably, drm_sched_job_arm() has not been called.
849 		 */
850 		drm_sched_fence_free(job->s_fence);
851 	}
852 
853 	job->s_fence = NULL;
854 
855 	xa_for_each(&job->dependencies, index, fence) {
856 		dma_fence_put(fence);
857 	}
858 	xa_destroy(&job->dependencies);
859 
860 }
861 EXPORT_SYMBOL(drm_sched_job_cleanup);
862 
863 /**
864  * drm_sched_wakeup - Wake up the scheduler if it is ready to queue
865  * @sched: scheduler instance
866  *
867  * Wake up the scheduler if we can queue jobs.
868  */
869 void drm_sched_wakeup(struct drm_gpu_scheduler *sched)
870 {
871 	drm_sched_run_job_queue(sched);
872 }
873 
874 /**
875  * drm_sched_get_finished_job - fetch the next finished job to be destroyed
876  *
877  * @sched: scheduler instance
878  *
879  * Informs the caller through @have_more whether there are more finished jobs
880  * besides the returned one.
881  *
882  * Returns the next finished job from the pending list (if there is one)
883  * ready for it to be destroyed.
884  */
885 static struct drm_sched_job *
886 drm_sched_get_finished_job(struct drm_gpu_scheduler *sched)
887 {
888 	struct drm_sched_job *job, *next;
889 
890 	spin_lock(&sched->job_list_lock);
891 
892 	job = list_first_entry_or_null(&sched->pending_list,
893 				       struct drm_sched_job, list);
894 	if (job && dma_fence_is_signaled(&job->s_fence->finished)) {
895 		/* remove job from pending_list */
896 		list_del_init(&job->list);
897 
898 		/* cancel this job's TO timer */
899 		cancel_delayed_work(&sched->work_tdr);
900 
901 		next = list_first_entry_or_null(&sched->pending_list,
902 						typeof(*next), list);
903 		if (next) {
904 			/* make the scheduled timestamp more accurate */
905 			if (test_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT,
906 				     &next->s_fence->scheduled.flags))
907 				next->s_fence->scheduled.timestamp =
908 					dma_fence_timestamp(&job->s_fence->finished);
909 
910 			/* start TO timer for next job */
911 			drm_sched_start_timeout(sched);
912 		}
913 	} else {
914 		job = NULL;
915 	}
916 
917 	spin_unlock(&sched->job_list_lock);
918 
919 	return job;
920 }
921 
922 /**
923  * drm_sched_pick_best - Get a drm sched from a sched_list with the least load
924  * @sched_list: list of drm_gpu_schedulers
925  * @num_sched_list: number of drm_gpu_schedulers in the sched_list
926  *
927  * Returns pointer of the sched with the least load or NULL if none of the
928  * drm_gpu_schedulers are ready
929  */
930 struct drm_gpu_scheduler *
931 drm_sched_pick_best(struct drm_gpu_scheduler **sched_list,
932 		     unsigned int num_sched_list)
933 {
934 	struct drm_gpu_scheduler *sched, *picked_sched = NULL;
935 	int i;
936 	unsigned int min_score = UINT_MAX, num_score;
937 
938 	for (i = 0; i < num_sched_list; ++i) {
939 		sched = sched_list[i];
940 
941 		if (!sched->ready) {
942 			DRM_WARN("scheduler %s is not ready, skipping",
943 				 sched->name);
944 			continue;
945 		}
946 
947 		num_score = atomic_read(sched->score);
948 		if (num_score < min_score) {
949 			min_score = num_score;
950 			picked_sched = sched;
951 		}
952 	}
953 
954 	return picked_sched;
955 }
956 EXPORT_SYMBOL(drm_sched_pick_best);
957 
958 /**
959  * drm_sched_free_job_work - worker to call free_job
960  *
961  * @w: free job work
962  */
963 static void drm_sched_free_job_work(struct work_struct *w)
964 {
965 	struct drm_gpu_scheduler *sched =
966 		container_of(w, struct drm_gpu_scheduler, work_free_job);
967 	struct drm_sched_job *job;
968 
969 	while ((job = drm_sched_get_finished_job(sched))) {
970 		ktime_t duration = drm_sched_entity_stats_job_add_gpu_time(job);
971 
972 		/* Serialized by the worker. */
973 		ewma_drm_sched_avgtime_add(&sched->avg_job_us,
974 					   ktime_to_us(duration));
975 
976 		sched->ops->free_job(job);
977 	}
978 
979 	drm_sched_run_job_queue(sched);
980 }
981 
982 /**
983  * drm_sched_run_job_work - worker to call run_job
984  *
985  * @w: run job work
986  */
987 static void drm_sched_run_job_work(struct work_struct *w)
988 {
989 	struct drm_gpu_scheduler *sched =
990 		container_of(w, struct drm_gpu_scheduler, work_run_job);
991 	struct drm_sched_entity *entity;
992 	struct dma_fence *fence;
993 	struct drm_sched_fence *s_fence;
994 	struct drm_sched_job *sched_job;
995 	int r;
996 
997 	/* Find entity with a ready job */
998 	entity = drm_sched_select_entity(sched);
999 	if (IS_ERR_OR_NULL(entity)) {
1000 		/*
1001 		 * Either no more work to do, or the next ready job needs more
1002 		 * credits than the scheduler has currently available.
1003 		 */
1004 		return;
1005 	}
1006 
1007 	sched_job = drm_sched_entity_pop_job(entity);
1008 	if (!sched_job) {
1009 		complete_all(&entity->entity_idle);
1010 		drm_sched_run_job_queue(sched);
1011 		return;
1012 	}
1013 
1014 	s_fence = sched_job->s_fence;
1015 
1016 	atomic_add(sched_job->credits, &sched->credit_count);
1017 	drm_sched_job_begin(sched_job);
1018 
1019 	trace_drm_sched_job_run(sched_job, entity);
1020 	/*
1021 	 * The run_job() callback must by definition return a fence whose
1022 	 * refcount has been incremented for the scheduler already.
1023 	 */
1024 	fence = sched->ops->run_job(sched_job);
1025 	complete_all(&entity->entity_idle);
1026 	drm_sched_fence_scheduled(s_fence, fence);
1027 
1028 	if (!IS_ERR_OR_NULL(fence)) {
1029 		r = dma_fence_add_callback(fence, &sched_job->cb,
1030 					   drm_sched_job_done_cb);
1031 		if (r == -ENOENT)
1032 			drm_sched_job_done(sched_job, fence->error);
1033 		else if (r)
1034 			DRM_DEV_ERROR(sched->dev, "fence add callback failed (%d)\n", r);
1035 
1036 		dma_fence_put(fence);
1037 	} else {
1038 		drm_sched_job_done(sched_job, IS_ERR(fence) ?
1039 				   PTR_ERR(fence) : 0);
1040 	}
1041 
1042 	wake_up(&sched->job_scheduled);
1043 	drm_sched_run_job_queue(sched);
1044 }
1045 
1046 static struct workqueue_struct *drm_sched_alloc_wq(const char *name)
1047 {
1048 #if (IS_ENABLED(CONFIG_LOCKDEP))
1049 	static struct lockdep_map map = {
1050 		.name = "drm_sched_lockdep_map"
1051 	};
1052 
1053 	/*
1054 	 * Avoid leaking a lockdep map on each drm sched creation and
1055 	 * destruction by using a single lockdep map for all drm sched
1056 	 * allocated submit_wq.
1057 	 */
1058 
1059 	return alloc_ordered_workqueue_lockdep_map(name, WQ_MEM_RECLAIM, &map);
1060 #else
1061 	return alloc_ordered_workqueue(name, WQ_MEM_RECLAIM);
1062 #endif
1063 }
1064 
1065 /**
1066  * drm_sched_init - Init a gpu scheduler instance
1067  *
1068  * @sched: scheduler instance
1069  * @args: scheduler initialization arguments
1070  *
1071  * Return 0 on success, otherwise error code.
1072  */
1073 int drm_sched_init(struct drm_gpu_scheduler *sched, const struct drm_sched_init_args *args)
1074 {
1075 	sched->ops = args->ops;
1076 	sched->credit_limit = args->credit_limit;
1077 	sched->name = args->name;
1078 	sched->timeout = args->timeout;
1079 	sched->hang_limit = args->hang_limit;
1080 	sched->timeout_wq = args->timeout_wq ? args->timeout_wq : system_percpu_wq;
1081 	sched->score = args->score ? args->score : &sched->_score;
1082 	sched->dev = args->dev;
1083 
1084 	if (args->submit_wq) {
1085 		sched->submit_wq = args->submit_wq;
1086 		sched->own_submit_wq = false;
1087 	} else {
1088 		sched->submit_wq = drm_sched_alloc_wq(args->name);
1089 		if (!sched->submit_wq)
1090 			return -ENOMEM;
1091 
1092 		sched->own_submit_wq = true;
1093 	}
1094 
1095 	drm_sched_rq_init(&sched->rq);
1096 
1097 	init_waitqueue_head(&sched->job_scheduled);
1098 	INIT_LIST_HEAD(&sched->pending_list);
1099 	spin_lock_init(&sched->job_list_lock);
1100 	atomic_set(&sched->credit_count, 0);
1101 	INIT_DELAYED_WORK(&sched->work_tdr, drm_sched_job_timedout);
1102 	INIT_WORK(&sched->work_run_job, drm_sched_run_job_work);
1103 	INIT_WORK(&sched->work_free_job, drm_sched_free_job_work);
1104 	atomic_set(&sched->_score, 0);
1105 	atomic64_set(&sched->job_id_count, 0);
1106 	sched->pause_submit = false;
1107 	ewma_drm_sched_avgtime_init(&sched->avg_job_us);
1108 
1109 	sched->ready = true;
1110 	return 0;
1111 }
1112 EXPORT_SYMBOL(drm_sched_init);
1113 
1114 static void drm_sched_cancel_remaining_jobs(struct drm_gpu_scheduler *sched)
1115 {
1116 	struct drm_sched_job *job, *tmp;
1117 
1118 	/* All other accessors are stopped. No locking necessary. */
1119 	list_for_each_entry_safe_reverse(job, tmp, &sched->pending_list, list) {
1120 		sched->ops->cancel_job(job);
1121 		list_del(&job->list);
1122 		sched->ops->free_job(job);
1123 	}
1124 }
1125 
1126 /**
1127  * drm_sched_fini - Destroy a gpu scheduler
1128  *
1129  * @sched: scheduler instance
1130  *
1131  * Tears down and cleans up the scheduler.
1132  *
1133  * This stops submission of new jobs to the hardware through &struct
1134  * drm_sched_backend_ops.run_job. If &struct drm_sched_backend_ops.cancel_job
1135  * is implemented, all jobs will be canceled through it and afterwards cleaned
1136  * up through &struct drm_sched_backend_ops.free_job. If cancel_job is not
1137  * implemented, memory could leak.
1138  */
1139 void drm_sched_fini(struct drm_gpu_scheduler *sched)
1140 {
1141 	drm_sched_wqueue_stop(sched);
1142 
1143 	/* Wakeup everyone stuck in drm_sched_entity_flush for this scheduler */
1144 	wake_up_all(&sched->job_scheduled);
1145 
1146 	/* Confirm no work left behind accessing device structures */
1147 	cancel_delayed_work_sync(&sched->work_tdr);
1148 
1149 	/* Avoid memory leaks if supported by the driver. */
1150 	if (sched->ops->cancel_job)
1151 		drm_sched_cancel_remaining_jobs(sched);
1152 
1153 	if (sched->own_submit_wq)
1154 		destroy_workqueue(sched->submit_wq);
1155 	sched->ready = false;
1156 
1157 	if (!list_empty(&sched->pending_list))
1158 		dev_warn(sched->dev, "Tearing down scheduler while jobs are pending!\n");
1159 }
1160 EXPORT_SYMBOL(drm_sched_fini);
1161 
1162 /**
1163  * drm_sched_increase_karma - Update sched_entity guilty flag
1164  *
1165  * @bad: The job guilty of time out
1166  *
1167  * Increment on every hang caused by the 'bad' job. If this exceeds the hang
1168  * limit of the scheduler then the respective sched entity is marked guilty and
1169  * jobs from it will not be scheduled further
1170  */
1171 void drm_sched_increase_karma(struct drm_sched_job *bad)
1172 {
1173 	struct drm_gpu_scheduler *sched = bad->sched;
1174 	struct drm_sched_entity *entity, *tmp;
1175 	struct drm_sched_rq *rq = &sched->rq;
1176 
1177 	/* don't change @bad's karma if it's from KERNEL RQ,
1178 	 * because sometimes GPU hang would cause kernel jobs (like VM updating jobs)
1179 	 * corrupt but keep in mind that kernel jobs always considered good.
1180 	 */
1181 	if (bad->s_priority == DRM_SCHED_PRIORITY_KERNEL)
1182 		return;
1183 
1184 	atomic_inc(&bad->karma);
1185 
1186 	spin_lock(&rq->lock);
1187 	list_for_each_entry_safe(entity, tmp, &rq->entities, list) {
1188 		if (bad->s_fence->scheduled.context == entity->fence_context) {
1189 			if (entity->guilty)
1190 				atomic_set(entity->guilty, 1);
1191 			break;
1192 		}
1193 	}
1194 	spin_unlock(&rq->lock);
1195 }
1196 EXPORT_SYMBOL(drm_sched_increase_karma);
1197 
1198 /**
1199  * drm_sched_wqueue_ready - Is the scheduler ready for submission
1200  *
1201  * @sched: scheduler instance
1202  *
1203  * Returns true if submission is ready
1204  */
1205 bool drm_sched_wqueue_ready(struct drm_gpu_scheduler *sched)
1206 {
1207 	return sched->ready;
1208 }
1209 EXPORT_SYMBOL(drm_sched_wqueue_ready);
1210 
1211 /**
1212  * drm_sched_wqueue_stop - stop scheduler submission
1213  * @sched: scheduler instance
1214  *
1215  * Stops the scheduler from pulling new jobs from entities. It also stops
1216  * freeing jobs automatically through drm_sched_backend_ops.free_job().
1217  */
1218 void drm_sched_wqueue_stop(struct drm_gpu_scheduler *sched)
1219 {
1220 	WRITE_ONCE(sched->pause_submit, true);
1221 	cancel_work_sync(&sched->work_run_job);
1222 	cancel_work_sync(&sched->work_free_job);
1223 }
1224 EXPORT_SYMBOL(drm_sched_wqueue_stop);
1225 
1226 /**
1227  * drm_sched_wqueue_start - start scheduler submission
1228  * @sched: scheduler instance
1229  *
1230  * Restarts the scheduler after drm_sched_wqueue_stop() has stopped it.
1231  *
1232  * This function is not necessary for 'conventional' startup. The scheduler is
1233  * fully operational after drm_sched_init() succeeded.
1234  */
1235 void drm_sched_wqueue_start(struct drm_gpu_scheduler *sched)
1236 {
1237 	WRITE_ONCE(sched->pause_submit, false);
1238 	queue_work(sched->submit_wq, &sched->work_run_job);
1239 	queue_work(sched->submit_wq, &sched->work_free_job);
1240 }
1241 EXPORT_SYMBOL(drm_sched_wqueue_start);
1242 
1243 /**
1244  * drm_sched_is_stopped() - Checks whether drm_sched is stopped
1245  * @sched: DRM scheduler
1246  *
1247  * Return: true if sched is stopped, false otherwise
1248  */
1249 bool drm_sched_is_stopped(struct drm_gpu_scheduler *sched)
1250 {
1251 	return READ_ONCE(sched->pause_submit);
1252 }
1253 EXPORT_SYMBOL(drm_sched_is_stopped);
1254 
1255 /**
1256  * drm_sched_job_is_signaled() - DRM scheduler job is signaled
1257  * @job: DRM scheduler job
1258  *
1259  * Determine if DRM scheduler job is signaled. DRM scheduler should be stopped
1260  * to obtain a stable snapshot of state. Both parent fence (hardware fence) and
1261  * finished fence (software fence) are checked to determine signaling state.
1262  *
1263  * Return: true if job is signaled, false otherwise
1264  */
1265 bool drm_sched_job_is_signaled(struct drm_sched_job *job)
1266 {
1267 	struct drm_sched_fence *s_fence = job->s_fence;
1268 
1269 	WARN_ON(!drm_sched_is_stopped(job->sched));
1270 	return (s_fence->parent && dma_fence_is_signaled(s_fence->parent)) ||
1271 		dma_fence_is_signaled(&s_fence->finished);
1272 }
1273 EXPORT_SYMBOL(drm_sched_job_is_signaled);
1274