xref: /linux/drivers/gpu/drm/scheduler/sched_main.c (revision 5c9deba5578db5a3ea05be8a3e4a59ecb08ee76f)
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 (unlikely(!credits)) {
592 		pr_err("*ERROR* %s: credits cannot be 0!\n", __func__);
593 		return -EINVAL;
594 	}
595 
596 	/*
597 	 * We don't know for sure how the user has allocated. Thus, zero the
598 	 * struct so that unallowed (i.e., too early) usage of pointers that
599 	 * this function does not set is guaranteed to lead to a NULL pointer
600 	 * exception instead of UB.
601 	 */
602 	memset(job, 0, sizeof(*job));
603 
604 	job->entity = entity;
605 	job->credits = credits;
606 	job->s_fence = drm_sched_fence_alloc(entity, owner, drm_client_id);
607 	if (!job->s_fence)
608 		return -ENOMEM;
609 
610 	INIT_LIST_HEAD(&job->list);
611 
612 	xa_init_flags(&job->dependencies, XA_FLAGS_ALLOC);
613 
614 	return 0;
615 }
616 EXPORT_SYMBOL(drm_sched_job_init);
617 
618 /**
619  * drm_sched_job_arm - arm a scheduler job for execution
620  * @job: scheduler job to arm
621  *
622  * This arms a scheduler job for execution. Specifically it initializes the
623  * &drm_sched_job.s_fence of @job, so that it can be attached to struct dma_resv
624  * or other places that need to track the completion of this job. It also
625  * initializes sequence numbers, which are fundamental for fence ordering.
626  *
627  * Refer to drm_sched_entity_push_job() documentation for locking
628  * considerations.
629  *
630  * Once this function was called, you *must* submit @job with
631  * drm_sched_entity_push_job().
632  *
633  * This can only be called if drm_sched_job_init() succeeded.
634  */
635 void drm_sched_job_arm(struct drm_sched_job *job)
636 {
637 	struct drm_gpu_scheduler *sched;
638 	struct drm_sched_entity *entity = job->entity;
639 
640 	BUG_ON(!entity);
641 	drm_sched_entity_select_rq(entity);
642 	sched = container_of(entity->rq, typeof(*sched), rq);
643 
644 	job->sched = sched;
645 	job->s_priority = entity->priority;
646 	job->entity_stats = drm_sched_entity_stats_get(entity->stats);
647 
648 	drm_sched_fence_init(job->s_fence, job->entity);
649 }
650 EXPORT_SYMBOL(drm_sched_job_arm);
651 
652 /**
653  * drm_sched_job_add_dependency - adds the fence as a job dependency
654  * @job: scheduler job to add the dependencies to
655  * @fence: the dma_fence to add to the list of dependencies.
656  *
657  * Note that @fence is consumed in both the success and error cases.
658  *
659  * Returns:
660  * 0 on success, or an error on failing to expand the array.
661  */
662 int drm_sched_job_add_dependency(struct drm_sched_job *job,
663 				 struct dma_fence *fence)
664 {
665 	struct dma_fence *entry;
666 	unsigned long index;
667 	u32 id = 0;
668 	int ret;
669 
670 	if (!fence)
671 		return 0;
672 
673 	/* Deduplicate if we already depend on a fence from the same context.
674 	 * This lets the size of the array of deps scale with the number of
675 	 * engines involved, rather than the number of BOs.
676 	 */
677 	xa_for_each(&job->dependencies, index, entry) {
678 		if (entry->context != fence->context)
679 			continue;
680 
681 		if (dma_fence_is_later(fence, entry)) {
682 			dma_fence_put(entry);
683 			xa_store(&job->dependencies, index, fence, GFP_KERNEL);
684 		} else {
685 			dma_fence_put(fence);
686 		}
687 		return 0;
688 	}
689 
690 	ret = xa_alloc(&job->dependencies, &id, fence, xa_limit_32b, GFP_KERNEL);
691 	if (ret != 0)
692 		dma_fence_put(fence);
693 
694 	return ret;
695 }
696 EXPORT_SYMBOL(drm_sched_job_add_dependency);
697 
698 /**
699  * drm_sched_job_add_syncobj_dependency - adds a syncobj's fence as a job dependency
700  * @job: scheduler job to add the dependencies to
701  * @file: drm file private pointer
702  * @handle: syncobj handle to lookup
703  * @point: timeline point
704  *
705  * This adds the fence matching the given syncobj to @job.
706  *
707  * Returns:
708  * 0 on success, or an error on failing to expand the array.
709  */
710 int drm_sched_job_add_syncobj_dependency(struct drm_sched_job *job,
711 					 struct drm_file *file,
712 					 u32 handle,
713 					 u32 point)
714 {
715 	struct dma_fence *fence;
716 	int ret;
717 
718 	ret = drm_syncobj_find_fence(file, handle, point, 0, &fence);
719 	if (ret)
720 		return ret;
721 
722 	return drm_sched_job_add_dependency(job, fence);
723 }
724 EXPORT_SYMBOL(drm_sched_job_add_syncobj_dependency);
725 
726 /**
727  * drm_sched_job_add_resv_dependencies - add all fences from the resv to the job
728  * @job: scheduler job to add the dependencies to
729  * @resv: the dma_resv object to get the fences from
730  * @usage: the dma_resv_usage to use to filter the fences
731  *
732  * This adds all fences matching the given usage from @resv to @job.
733  * Must be called with the @resv lock held.
734  *
735  * Returns:
736  * 0 on success, or an error on failing to expand the array.
737  */
738 int drm_sched_job_add_resv_dependencies(struct drm_sched_job *job,
739 					struct dma_resv *resv,
740 					enum dma_resv_usage usage)
741 {
742 	struct dma_resv_iter cursor;
743 	struct dma_fence *fence;
744 	int ret;
745 
746 	dma_resv_assert_held(resv);
747 
748 	dma_resv_for_each_fence(&cursor, resv, usage, fence) {
749 		/*
750 		 * As drm_sched_job_add_dependency always consumes the fence
751 		 * reference (even when it fails), and dma_resv_for_each_fence
752 		 * is not obtaining one, we need to grab one before calling.
753 		 */
754 		ret = drm_sched_job_add_dependency(job, dma_fence_get(fence));
755 		if (ret)
756 			return ret;
757 	}
758 	return 0;
759 }
760 EXPORT_SYMBOL(drm_sched_job_add_resv_dependencies);
761 
762 /**
763  * drm_sched_job_add_implicit_dependencies - adds implicit dependencies as job
764  *   dependencies
765  * @job: scheduler job to add the dependencies to
766  * @obj: the gem object to add new dependencies from.
767  * @write: whether the job might write the object (so we need to depend on
768  * shared fences in the reservation object).
769  *
770  * This should be called after drm_gem_lock_reservations() on your array of
771  * GEM objects used in the job but before updating the reservations with your
772  * own fences.
773  *
774  * Returns:
775  * 0 on success, or an error on failing to expand the array.
776  */
777 int drm_sched_job_add_implicit_dependencies(struct drm_sched_job *job,
778 					    struct drm_gem_object *obj,
779 					    bool write)
780 {
781 	return drm_sched_job_add_resv_dependencies(job, obj->resv,
782 						   dma_resv_usage_rw(write));
783 }
784 EXPORT_SYMBOL(drm_sched_job_add_implicit_dependencies);
785 
786 /**
787  * drm_sched_job_has_dependency - check whether fence is the job's dependency
788  * @job: scheduler job to check
789  * @fence: fence to look for
790  *
791  * Returns:
792  * True if @fence is found within the job's dependencies, or otherwise false.
793  */
794 bool drm_sched_job_has_dependency(struct drm_sched_job *job,
795 				  struct dma_fence *fence)
796 {
797 	struct dma_fence *f;
798 	unsigned long index;
799 
800 	xa_for_each(&job->dependencies, index, f) {
801 		if (f == fence)
802 			return true;
803 	}
804 
805 	return false;
806 }
807 EXPORT_SYMBOL(drm_sched_job_has_dependency);
808 
809 /**
810  * drm_sched_job_cleanup - clean up scheduler job resources
811  * @job: scheduler job to clean up
812  *
813  * Cleans up the resources allocated with drm_sched_job_init().
814  *
815  * Drivers should call this from their error unwind code if @job is aborted
816  * before drm_sched_job_arm() is called.
817  *
818  * drm_sched_job_arm() is a point of no return since it initializes the fences
819  * and their sequence number etc. Once that function has been called, you *must*
820  * submit it with drm_sched_entity_push_job() and cannot simply abort it by
821  * calling drm_sched_job_cleanup().
822  *
823  * This function should be called in the &drm_sched_backend_ops.free_job callback.
824  */
825 void drm_sched_job_cleanup(struct drm_sched_job *job)
826 {
827 	struct dma_fence *fence;
828 	unsigned long index;
829 
830 	if (kref_read(&job->s_fence->finished.refcount)) {
831 		/* The job has been processed by the scheduler, i.e.,
832 		 * drm_sched_job_arm() and drm_sched_entity_push_job() have
833 		 * been called.
834 		 */
835 		dma_fence_put(&job->s_fence->finished);
836 		drm_sched_entity_stats_put(job->entity_stats);
837 	} else {
838 		/* The job was aborted before it has been committed to be run;
839 		 * notably, drm_sched_job_arm() has not been called.
840 		 */
841 		drm_sched_fence_free(job->s_fence);
842 	}
843 
844 	job->s_fence = NULL;
845 
846 	xa_for_each(&job->dependencies, index, fence) {
847 		dma_fence_put(fence);
848 	}
849 	xa_destroy(&job->dependencies);
850 
851 }
852 EXPORT_SYMBOL(drm_sched_job_cleanup);
853 
854 /**
855  * drm_sched_wakeup - Wake up the scheduler if it is ready to queue
856  * @sched: scheduler instance
857  *
858  * Wake up the scheduler if we can queue jobs.
859  */
860 void drm_sched_wakeup(struct drm_gpu_scheduler *sched)
861 {
862 	drm_sched_run_job_queue(sched);
863 }
864 
865 /**
866  * drm_sched_get_finished_job - fetch the next finished job to be destroyed
867  *
868  * @sched: scheduler instance
869  *
870  * Informs the caller through @have_more whether there are more finished jobs
871  * besides the returned one.
872  *
873  * Returns the next finished job from the pending list (if there is one)
874  * ready for it to be destroyed.
875  */
876 static struct drm_sched_job *
877 drm_sched_get_finished_job(struct drm_gpu_scheduler *sched)
878 {
879 	struct drm_sched_job *job, *next;
880 
881 	spin_lock(&sched->job_list_lock);
882 
883 	job = list_first_entry_or_null(&sched->pending_list,
884 				       struct drm_sched_job, list);
885 	if (job && dma_fence_is_signaled(&job->s_fence->finished)) {
886 		/* remove job from pending_list */
887 		list_del_init(&job->list);
888 
889 		/* cancel this job's TO timer */
890 		cancel_delayed_work(&sched->work_tdr);
891 
892 		next = list_first_entry_or_null(&sched->pending_list,
893 						typeof(*next), list);
894 		if (next) {
895 			/* make the scheduled timestamp more accurate */
896 			if (test_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT,
897 				     &next->s_fence->scheduled.flags))
898 				next->s_fence->scheduled.timestamp =
899 					dma_fence_timestamp(&job->s_fence->finished);
900 
901 			/* start TO timer for next job */
902 			drm_sched_start_timeout(sched);
903 		}
904 	} else {
905 		job = NULL;
906 	}
907 
908 	spin_unlock(&sched->job_list_lock);
909 
910 	return job;
911 }
912 
913 /**
914  * drm_sched_pick_best - Get a drm sched from a sched_list with the least load
915  * @sched_list: list of drm_gpu_schedulers
916  * @num_sched_list: number of drm_gpu_schedulers in the sched_list
917  *
918  * Returns pointer of the sched with the least load or NULL if none of the
919  * drm_gpu_schedulers are ready
920  */
921 struct drm_gpu_scheduler *
922 drm_sched_pick_best(struct drm_gpu_scheduler **sched_list,
923 		     unsigned int num_sched_list)
924 {
925 	struct drm_gpu_scheduler *sched, *picked_sched = NULL;
926 	int i;
927 	unsigned int min_score = UINT_MAX, num_score;
928 
929 	for (i = 0; i < num_sched_list; ++i) {
930 		sched = sched_list[i];
931 
932 		if (!sched->ready) {
933 			DRM_WARN("scheduler %s is not ready, skipping",
934 				 sched->name);
935 			continue;
936 		}
937 
938 		num_score = atomic_read(sched->score);
939 		if (num_score < min_score) {
940 			min_score = num_score;
941 			picked_sched = sched;
942 		}
943 	}
944 
945 	return picked_sched;
946 }
947 EXPORT_SYMBOL(drm_sched_pick_best);
948 
949 /**
950  * drm_sched_free_job_work - worker to call free_job
951  *
952  * @w: free job work
953  */
954 static void drm_sched_free_job_work(struct work_struct *w)
955 {
956 	struct drm_gpu_scheduler *sched =
957 		container_of(w, struct drm_gpu_scheduler, work_free_job);
958 	struct drm_sched_job *job;
959 
960 	while ((job = drm_sched_get_finished_job(sched))) {
961 		ktime_t duration = drm_sched_entity_stats_job_add_gpu_time(job);
962 
963 		/* Serialized by the worker. */
964 		ewma_drm_sched_avgtime_add(&sched->avg_job_us,
965 					   ktime_to_us(duration));
966 
967 		sched->ops->free_job(job);
968 	}
969 
970 	drm_sched_run_job_queue(sched);
971 }
972 
973 /**
974  * drm_sched_run_job_work - worker to call run_job
975  *
976  * @w: run job work
977  */
978 static void drm_sched_run_job_work(struct work_struct *w)
979 {
980 	struct drm_gpu_scheduler *sched =
981 		container_of(w, struct drm_gpu_scheduler, work_run_job);
982 	struct drm_sched_entity *entity;
983 	struct dma_fence *fence;
984 	struct drm_sched_fence *s_fence;
985 	struct drm_sched_job *sched_job;
986 	int r;
987 
988 	/* Find entity with a ready job */
989 	entity = drm_sched_select_entity(sched);
990 	if (IS_ERR_OR_NULL(entity)) {
991 		/*
992 		 * Either no more work to do, or the next ready job needs more
993 		 * credits than the scheduler has currently available.
994 		 */
995 		return;
996 	}
997 
998 	sched_job = drm_sched_entity_pop_job(entity);
999 	if (!sched_job) {
1000 		complete_all(&entity->entity_idle);
1001 		drm_sched_run_job_queue(sched);
1002 		return;
1003 	}
1004 
1005 	s_fence = sched_job->s_fence;
1006 
1007 	atomic_add(sched_job->credits, &sched->credit_count);
1008 	drm_sched_job_begin(sched_job);
1009 
1010 	trace_drm_sched_job_run(sched_job, entity);
1011 	/*
1012 	 * The run_job() callback must by definition return a fence whose
1013 	 * refcount has been incremented for the scheduler already.
1014 	 */
1015 	fence = sched->ops->run_job(sched_job);
1016 	complete_all(&entity->entity_idle);
1017 	drm_sched_fence_scheduled(s_fence, fence);
1018 
1019 	if (!IS_ERR_OR_NULL(fence)) {
1020 		r = dma_fence_add_callback(fence, &sched_job->cb,
1021 					   drm_sched_job_done_cb);
1022 		if (r == -ENOENT)
1023 			drm_sched_job_done(sched_job, fence->error);
1024 		else if (r)
1025 			DRM_DEV_ERROR(sched->dev, "fence add callback failed (%d)\n", r);
1026 
1027 		dma_fence_put(fence);
1028 	} else {
1029 		drm_sched_job_done(sched_job, IS_ERR(fence) ?
1030 				   PTR_ERR(fence) : 0);
1031 	}
1032 
1033 	wake_up(&sched->job_scheduled);
1034 	drm_sched_run_job_queue(sched);
1035 }
1036 
1037 static struct workqueue_struct *drm_sched_alloc_wq(const char *name)
1038 {
1039 #if (IS_ENABLED(CONFIG_LOCKDEP))
1040 	static struct lockdep_map map = {
1041 		.name = "drm_sched_lockdep_map"
1042 	};
1043 
1044 	/*
1045 	 * Avoid leaking a lockdep map on each drm sched creation and
1046 	 * destruction by using a single lockdep map for all drm sched
1047 	 * allocated submit_wq.
1048 	 */
1049 
1050 	return alloc_ordered_workqueue_lockdep_map(name, WQ_MEM_RECLAIM, &map);
1051 #else
1052 	return alloc_ordered_workqueue(name, WQ_MEM_RECLAIM);
1053 #endif
1054 }
1055 
1056 /**
1057  * drm_sched_init - Init a gpu scheduler instance
1058  *
1059  * @sched: scheduler instance
1060  * @args: scheduler initialization arguments
1061  *
1062  * Return 0 on success, otherwise error code.
1063  */
1064 int drm_sched_init(struct drm_gpu_scheduler *sched, const struct drm_sched_init_args *args)
1065 {
1066 	sched->ops = args->ops;
1067 	sched->credit_limit = args->credit_limit;
1068 	sched->name = args->name;
1069 	sched->timeout = args->timeout;
1070 	sched->hang_limit = args->hang_limit;
1071 	sched->timeout_wq = args->timeout_wq ? args->timeout_wq : system_percpu_wq;
1072 	sched->score = args->score ? args->score : &sched->_score;
1073 	sched->dev = args->dev;
1074 
1075 	if (args->submit_wq) {
1076 		sched->submit_wq = args->submit_wq;
1077 		sched->own_submit_wq = false;
1078 	} else {
1079 		sched->submit_wq = drm_sched_alloc_wq(args->name);
1080 		if (!sched->submit_wq)
1081 			return -ENOMEM;
1082 
1083 		sched->own_submit_wq = true;
1084 	}
1085 
1086 	drm_sched_rq_init(&sched->rq);
1087 
1088 	init_waitqueue_head(&sched->job_scheduled);
1089 	INIT_LIST_HEAD(&sched->pending_list);
1090 	spin_lock_init(&sched->job_list_lock);
1091 	atomic_set(&sched->credit_count, 0);
1092 	INIT_DELAYED_WORK(&sched->work_tdr, drm_sched_job_timedout);
1093 	INIT_WORK(&sched->work_run_job, drm_sched_run_job_work);
1094 	INIT_WORK(&sched->work_free_job, drm_sched_free_job_work);
1095 	atomic_set(&sched->_score, 0);
1096 	atomic64_set(&sched->job_id_count, 0);
1097 	sched->pause_submit = false;
1098 	ewma_drm_sched_avgtime_init(&sched->avg_job_us);
1099 
1100 	sched->ready = true;
1101 	return 0;
1102 }
1103 EXPORT_SYMBOL(drm_sched_init);
1104 
1105 static void drm_sched_cancel_remaining_jobs(struct drm_gpu_scheduler *sched)
1106 {
1107 	struct drm_sched_job *job, *tmp;
1108 
1109 	/* All other accessors are stopped. No locking necessary. */
1110 	list_for_each_entry_safe_reverse(job, tmp, &sched->pending_list, list) {
1111 		sched->ops->cancel_job(job);
1112 		list_del(&job->list);
1113 		sched->ops->free_job(job);
1114 	}
1115 }
1116 
1117 /**
1118  * drm_sched_fini - Destroy a gpu scheduler
1119  *
1120  * @sched: scheduler instance
1121  *
1122  * Tears down and cleans up the scheduler.
1123  *
1124  * This stops submission of new jobs to the hardware through &struct
1125  * drm_sched_backend_ops.run_job. If &struct drm_sched_backend_ops.cancel_job
1126  * is implemented, all jobs will be canceled through it and afterwards cleaned
1127  * up through &struct drm_sched_backend_ops.free_job. If cancel_job is not
1128  * implemented, memory could leak.
1129  */
1130 void drm_sched_fini(struct drm_gpu_scheduler *sched)
1131 {
1132 	drm_sched_wqueue_stop(sched);
1133 
1134 	/* Wakeup everyone stuck in drm_sched_entity_flush for this scheduler */
1135 	wake_up_all(&sched->job_scheduled);
1136 
1137 	/* Confirm no work left behind accessing device structures */
1138 	cancel_delayed_work_sync(&sched->work_tdr);
1139 
1140 	/* Avoid memory leaks if supported by the driver. */
1141 	if (sched->ops->cancel_job)
1142 		drm_sched_cancel_remaining_jobs(sched);
1143 
1144 	if (sched->own_submit_wq)
1145 		destroy_workqueue(sched->submit_wq);
1146 	sched->ready = false;
1147 
1148 	if (!list_empty(&sched->pending_list))
1149 		dev_warn(sched->dev, "Tearing down scheduler while jobs are pending!\n");
1150 }
1151 EXPORT_SYMBOL(drm_sched_fini);
1152 
1153 /**
1154  * drm_sched_increase_karma - Update sched_entity guilty flag
1155  *
1156  * @bad: The job guilty of time out
1157  *
1158  * Increment on every hang caused by the 'bad' job. If this exceeds the hang
1159  * limit of the scheduler then the respective sched entity is marked guilty and
1160  * jobs from it will not be scheduled further
1161  */
1162 void drm_sched_increase_karma(struct drm_sched_job *bad)
1163 {
1164 	struct drm_gpu_scheduler *sched = bad->sched;
1165 	struct drm_sched_entity *entity, *tmp;
1166 	struct drm_sched_rq *rq = &sched->rq;
1167 
1168 	/* don't change @bad's karma if it's from KERNEL RQ,
1169 	 * because sometimes GPU hang would cause kernel jobs (like VM updating jobs)
1170 	 * corrupt but keep in mind that kernel jobs always considered good.
1171 	 */
1172 	if (bad->s_priority == DRM_SCHED_PRIORITY_KERNEL)
1173 		return;
1174 
1175 	atomic_inc(&bad->karma);
1176 
1177 	spin_lock(&rq->lock);
1178 	list_for_each_entry_safe(entity, tmp, &rq->entities, list) {
1179 		if (bad->s_fence->scheduled.context == entity->fence_context) {
1180 			if (entity->guilty)
1181 				atomic_set(entity->guilty, 1);
1182 			break;
1183 		}
1184 	}
1185 	spin_unlock(&rq->lock);
1186 }
1187 EXPORT_SYMBOL(drm_sched_increase_karma);
1188 
1189 /**
1190  * drm_sched_wqueue_ready - Is the scheduler ready for submission
1191  *
1192  * @sched: scheduler instance
1193  *
1194  * Returns true if submission is ready
1195  */
1196 bool drm_sched_wqueue_ready(struct drm_gpu_scheduler *sched)
1197 {
1198 	return sched->ready;
1199 }
1200 EXPORT_SYMBOL(drm_sched_wqueue_ready);
1201 
1202 /**
1203  * drm_sched_wqueue_stop - stop scheduler submission
1204  * @sched: scheduler instance
1205  *
1206  * Stops the scheduler from pulling new jobs from entities. It also stops
1207  * freeing jobs automatically through drm_sched_backend_ops.free_job().
1208  */
1209 void drm_sched_wqueue_stop(struct drm_gpu_scheduler *sched)
1210 {
1211 	WRITE_ONCE(sched->pause_submit, true);
1212 	cancel_work_sync(&sched->work_run_job);
1213 	cancel_work_sync(&sched->work_free_job);
1214 }
1215 EXPORT_SYMBOL(drm_sched_wqueue_stop);
1216 
1217 /**
1218  * drm_sched_wqueue_start - start scheduler submission
1219  * @sched: scheduler instance
1220  *
1221  * Restarts the scheduler after drm_sched_wqueue_stop() has stopped it.
1222  *
1223  * This function is not necessary for 'conventional' startup. The scheduler is
1224  * fully operational after drm_sched_init() succeeded.
1225  */
1226 void drm_sched_wqueue_start(struct drm_gpu_scheduler *sched)
1227 {
1228 	WRITE_ONCE(sched->pause_submit, false);
1229 	queue_work(sched->submit_wq, &sched->work_run_job);
1230 	queue_work(sched->submit_wq, &sched->work_free_job);
1231 }
1232 EXPORT_SYMBOL(drm_sched_wqueue_start);
1233 
1234 /**
1235  * drm_sched_is_stopped() - Checks whether drm_sched is stopped
1236  * @sched: DRM scheduler
1237  *
1238  * Return: true if sched is stopped, false otherwise
1239  */
1240 bool drm_sched_is_stopped(struct drm_gpu_scheduler *sched)
1241 {
1242 	return READ_ONCE(sched->pause_submit);
1243 }
1244 EXPORT_SYMBOL(drm_sched_is_stopped);
1245 
1246 /**
1247  * drm_sched_job_is_signaled() - DRM scheduler job is signaled
1248  * @job: DRM scheduler job
1249  *
1250  * Determine if DRM scheduler job is signaled. DRM scheduler should be stopped
1251  * to obtain a stable snapshot of state. Both parent fence (hardware fence) and
1252  * finished fence (software fence) are checked to determine signaling state.
1253  *
1254  * Return: true if job is signaled, false otherwise
1255  */
1256 bool drm_sched_job_is_signaled(struct drm_sched_job *job)
1257 {
1258 	struct drm_sched_fence *s_fence = job->s_fence;
1259 
1260 	WARN_ON(!drm_sched_is_stopped(job->sched));
1261 	return (s_fence->parent && dma_fence_is_signaled(s_fence->parent)) ||
1262 		dma_fence_is_signaled(&s_fence->finished);
1263 }
1264 EXPORT_SYMBOL(drm_sched_job_is_signaled);
1265