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