drm/scheduler: set entity to NULL in drm_sched_entity_pop_job()
[platform/kernel/linux-rpi.git] / drivers / gpu / drm / scheduler / sched_main.c
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 a entity are always scheduled in the order that 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 #include <linux/kthread.h>
52 #include <linux/wait.h>
53 #include <linux/sched.h>
54 #include <linux/completion.h>
55 #include <linux/dma-resv.h>
56 #include <uapi/linux/sched/types.h>
57
58 #include <drm/drm_print.h>
59 #include <drm/drm_gem.h>
60 #include <drm/drm_syncobj.h>
61 #include <drm/gpu_scheduler.h>
62 #include <drm/spsc_queue.h>
63
64 #define CREATE_TRACE_POINTS
65 #include "gpu_scheduler_trace.h"
66
67 #define to_drm_sched_job(sched_job)             \
68                 container_of((sched_job), struct drm_sched_job, queue_node)
69
70 int drm_sched_policy = DRM_SCHED_POLICY_FIFO;
71
72 /**
73  * DOC: sched_policy (int)
74  * Used to override default entities scheduling policy in a run queue.
75  */
76 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).");
77 module_param_named(sched_policy, drm_sched_policy, int, 0444);
78
79 static __always_inline bool drm_sched_entity_compare_before(struct rb_node *a,
80                                                             const struct rb_node *b)
81 {
82         struct drm_sched_entity *ent_a =  rb_entry((a), struct drm_sched_entity, rb_tree_node);
83         struct drm_sched_entity *ent_b =  rb_entry((b), struct drm_sched_entity, rb_tree_node);
84
85         return ktime_before(ent_a->oldest_job_waiting, ent_b->oldest_job_waiting);
86 }
87
88 static inline void drm_sched_rq_remove_fifo_locked(struct drm_sched_entity *entity)
89 {
90         struct drm_sched_rq *rq = entity->rq;
91
92         if (!RB_EMPTY_NODE(&entity->rb_tree_node)) {
93                 rb_erase_cached(&entity->rb_tree_node, &rq->rb_tree_root);
94                 RB_CLEAR_NODE(&entity->rb_tree_node);
95         }
96 }
97
98 void drm_sched_rq_update_fifo(struct drm_sched_entity *entity, ktime_t ts)
99 {
100         /*
101          * Both locks need to be grabbed, one to protect from entity->rq change
102          * for entity from within concurrent drm_sched_entity_select_rq and the
103          * other to update the rb tree structure.
104          */
105         spin_lock(&entity->rq_lock);
106         spin_lock(&entity->rq->lock);
107
108         drm_sched_rq_remove_fifo_locked(entity);
109
110         entity->oldest_job_waiting = ts;
111
112         rb_add_cached(&entity->rb_tree_node, &entity->rq->rb_tree_root,
113                       drm_sched_entity_compare_before);
114
115         spin_unlock(&entity->rq->lock);
116         spin_unlock(&entity->rq_lock);
117 }
118
119 /**
120  * drm_sched_rq_init - initialize a given run queue struct
121  *
122  * @sched: scheduler instance to associate with this run queue
123  * @rq: scheduler run queue
124  *
125  * Initializes a scheduler runqueue.
126  */
127 static void drm_sched_rq_init(struct drm_gpu_scheduler *sched,
128                               struct drm_sched_rq *rq)
129 {
130         spin_lock_init(&rq->lock);
131         INIT_LIST_HEAD(&rq->entities);
132         rq->rb_tree_root = RB_ROOT_CACHED;
133         rq->current_entity = NULL;
134         rq->sched = sched;
135 }
136
137 /**
138  * drm_sched_rq_add_entity - add an entity
139  *
140  * @rq: scheduler run queue
141  * @entity: scheduler entity
142  *
143  * Adds a scheduler entity to the run queue.
144  */
145 void drm_sched_rq_add_entity(struct drm_sched_rq *rq,
146                              struct drm_sched_entity *entity)
147 {
148         if (!list_empty(&entity->list))
149                 return;
150
151         spin_lock(&rq->lock);
152
153         atomic_inc(rq->sched->score);
154         list_add_tail(&entity->list, &rq->entities);
155
156         spin_unlock(&rq->lock);
157 }
158
159 /**
160  * drm_sched_rq_remove_entity - remove an entity
161  *
162  * @rq: scheduler run queue
163  * @entity: scheduler entity
164  *
165  * Removes a scheduler entity from the run queue.
166  */
167 void drm_sched_rq_remove_entity(struct drm_sched_rq *rq,
168                                 struct drm_sched_entity *entity)
169 {
170         if (list_empty(&entity->list))
171                 return;
172
173         spin_lock(&rq->lock);
174
175         atomic_dec(rq->sched->score);
176         list_del_init(&entity->list);
177
178         if (rq->current_entity == entity)
179                 rq->current_entity = NULL;
180
181         if (drm_sched_policy == DRM_SCHED_POLICY_FIFO)
182                 drm_sched_rq_remove_fifo_locked(entity);
183
184         spin_unlock(&rq->lock);
185 }
186
187 /**
188  * drm_sched_rq_select_entity_rr - Select an entity which could provide a job to run
189  *
190  * @rq: scheduler run queue to check.
191  *
192  * Try to find a ready entity, returns NULL if none found.
193  */
194 static struct drm_sched_entity *
195 drm_sched_rq_select_entity_rr(struct drm_sched_rq *rq)
196 {
197         struct drm_sched_entity *entity;
198
199         spin_lock(&rq->lock);
200
201         entity = rq->current_entity;
202         if (entity) {
203                 list_for_each_entry_continue(entity, &rq->entities, list) {
204                         if (drm_sched_entity_is_ready(entity)) {
205                                 rq->current_entity = entity;
206                                 reinit_completion(&entity->entity_idle);
207                                 spin_unlock(&rq->lock);
208                                 return entity;
209                         }
210                 }
211         }
212
213         list_for_each_entry(entity, &rq->entities, list) {
214
215                 if (drm_sched_entity_is_ready(entity)) {
216                         rq->current_entity = entity;
217                         reinit_completion(&entity->entity_idle);
218                         spin_unlock(&rq->lock);
219                         return entity;
220                 }
221
222                 if (entity == rq->current_entity)
223                         break;
224         }
225
226         spin_unlock(&rq->lock);
227
228         return NULL;
229 }
230
231 /**
232  * drm_sched_rq_select_entity_fifo - Select an entity which provides a job to run
233  *
234  * @rq: scheduler run queue to check.
235  *
236  * Find oldest waiting ready entity, returns NULL if none found.
237  */
238 static struct drm_sched_entity *
239 drm_sched_rq_select_entity_fifo(struct drm_sched_rq *rq)
240 {
241         struct rb_node *rb;
242
243         spin_lock(&rq->lock);
244         for (rb = rb_first_cached(&rq->rb_tree_root); rb; rb = rb_next(rb)) {
245                 struct drm_sched_entity *entity;
246
247                 entity = rb_entry(rb, struct drm_sched_entity, rb_tree_node);
248                 if (drm_sched_entity_is_ready(entity)) {
249                         rq->current_entity = entity;
250                         reinit_completion(&entity->entity_idle);
251                         break;
252                 }
253         }
254         spin_unlock(&rq->lock);
255
256         return rb ? rb_entry(rb, struct drm_sched_entity, rb_tree_node) : NULL;
257 }
258
259 /**
260  * drm_sched_job_done - complete a job
261  * @s_job: pointer to the job which is done
262  *
263  * Finish the job's fence and wake up the worker thread.
264  */
265 static void drm_sched_job_done(struct drm_sched_job *s_job)
266 {
267         struct drm_sched_fence *s_fence = s_job->s_fence;
268         struct drm_gpu_scheduler *sched = s_fence->sched;
269
270         atomic_dec(&sched->hw_rq_count);
271         atomic_dec(sched->score);
272
273         trace_drm_sched_process_job(s_fence);
274
275         dma_fence_get(&s_fence->finished);
276         drm_sched_fence_finished(s_fence);
277         dma_fence_put(&s_fence->finished);
278         wake_up_interruptible(&sched->wake_up_worker);
279 }
280
281 /**
282  * drm_sched_job_done_cb - the callback for a done job
283  * @f: fence
284  * @cb: fence callbacks
285  */
286 static void drm_sched_job_done_cb(struct dma_fence *f, struct dma_fence_cb *cb)
287 {
288         struct drm_sched_job *s_job = container_of(cb, struct drm_sched_job, cb);
289
290         drm_sched_job_done(s_job);
291 }
292
293 /**
294  * drm_sched_start_timeout - start timeout for reset worker
295  *
296  * @sched: scheduler instance to start the worker for
297  *
298  * Start the timeout for the given scheduler.
299  */
300 static void drm_sched_start_timeout(struct drm_gpu_scheduler *sched)
301 {
302         if (sched->timeout != MAX_SCHEDULE_TIMEOUT &&
303             !list_empty(&sched->pending_list))
304                 queue_delayed_work(sched->timeout_wq, &sched->work_tdr, sched->timeout);
305 }
306
307 /**
308  * drm_sched_fault - immediately start timeout handler
309  *
310  * @sched: scheduler where the timeout handling should be started.
311  *
312  * Start timeout handling immediately when the driver detects a hardware fault.
313  */
314 void drm_sched_fault(struct drm_gpu_scheduler *sched)
315 {
316         mod_delayed_work(sched->timeout_wq, &sched->work_tdr, 0);
317 }
318 EXPORT_SYMBOL(drm_sched_fault);
319
320 /**
321  * drm_sched_suspend_timeout - Suspend scheduler job timeout
322  *
323  * @sched: scheduler instance for which to suspend the timeout
324  *
325  * Suspend the delayed work timeout for the scheduler. This is done by
326  * modifying the delayed work timeout to an arbitrary large value,
327  * MAX_SCHEDULE_TIMEOUT in this case.
328  *
329  * Returns the timeout remaining
330  *
331  */
332 unsigned long drm_sched_suspend_timeout(struct drm_gpu_scheduler *sched)
333 {
334         unsigned long sched_timeout, now = jiffies;
335
336         sched_timeout = sched->work_tdr.timer.expires;
337
338         /*
339          * Modify the timeout to an arbitrarily large value. This also prevents
340          * the timeout to be restarted when new submissions arrive
341          */
342         if (mod_delayed_work(sched->timeout_wq, &sched->work_tdr, MAX_SCHEDULE_TIMEOUT)
343                         && time_after(sched_timeout, now))
344                 return sched_timeout - now;
345         else
346                 return sched->timeout;
347 }
348 EXPORT_SYMBOL(drm_sched_suspend_timeout);
349
350 /**
351  * drm_sched_resume_timeout - Resume scheduler job timeout
352  *
353  * @sched: scheduler instance for which to resume the timeout
354  * @remaining: remaining timeout
355  *
356  * Resume the delayed work timeout for the scheduler.
357  */
358 void drm_sched_resume_timeout(struct drm_gpu_scheduler *sched,
359                 unsigned long remaining)
360 {
361         spin_lock(&sched->job_list_lock);
362
363         if (list_empty(&sched->pending_list))
364                 cancel_delayed_work(&sched->work_tdr);
365         else
366                 mod_delayed_work(sched->timeout_wq, &sched->work_tdr, remaining);
367
368         spin_unlock(&sched->job_list_lock);
369 }
370 EXPORT_SYMBOL(drm_sched_resume_timeout);
371
372 static void drm_sched_job_begin(struct drm_sched_job *s_job)
373 {
374         struct drm_gpu_scheduler *sched = s_job->sched;
375
376         spin_lock(&sched->job_list_lock);
377         list_add_tail(&s_job->list, &sched->pending_list);
378         drm_sched_start_timeout(sched);
379         spin_unlock(&sched->job_list_lock);
380 }
381
382 static void drm_sched_job_timedout(struct work_struct *work)
383 {
384         struct drm_gpu_scheduler *sched;
385         struct drm_sched_job *job;
386         enum drm_gpu_sched_stat status = DRM_GPU_SCHED_STAT_NOMINAL;
387
388         sched = container_of(work, struct drm_gpu_scheduler, work_tdr.work);
389
390         /* Protects against concurrent deletion in drm_sched_get_cleanup_job */
391         spin_lock(&sched->job_list_lock);
392         job = list_first_entry_or_null(&sched->pending_list,
393                                        struct drm_sched_job, list);
394
395         if (job) {
396                 /*
397                  * Remove the bad job so it cannot be freed by concurrent
398                  * drm_sched_cleanup_jobs. It will be reinserted back after sched->thread
399                  * is parked at which point it's safe.
400                  */
401                 list_del_init(&job->list);
402                 spin_unlock(&sched->job_list_lock);
403
404                 status = job->sched->ops->timedout_job(job);
405
406                 /*
407                  * Guilty job did complete and hence needs to be manually removed
408                  * See drm_sched_stop doc.
409                  */
410                 if (sched->free_guilty) {
411                         job->sched->ops->free_job(job);
412                         sched->free_guilty = false;
413                 }
414         } else {
415                 spin_unlock(&sched->job_list_lock);
416         }
417
418         if (status != DRM_GPU_SCHED_STAT_ENODEV) {
419                 spin_lock(&sched->job_list_lock);
420                 drm_sched_start_timeout(sched);
421                 spin_unlock(&sched->job_list_lock);
422         }
423 }
424
425 /**
426  * drm_sched_stop - stop the scheduler
427  *
428  * @sched: scheduler instance
429  * @bad: job which caused the time out
430  *
431  * Stop the scheduler and also removes and frees all completed jobs.
432  * Note: bad job will not be freed as it might be used later and so it's
433  * callers responsibility to release it manually if it's not part of the
434  * pending list any more.
435  *
436  */
437 void drm_sched_stop(struct drm_gpu_scheduler *sched, struct drm_sched_job *bad)
438 {
439         struct drm_sched_job *s_job, *tmp;
440
441         kthread_park(sched->thread);
442
443         /*
444          * Reinsert back the bad job here - now it's safe as
445          * drm_sched_get_cleanup_job cannot race against us and release the
446          * bad job at this point - we parked (waited for) any in progress
447          * (earlier) cleanups and drm_sched_get_cleanup_job will not be called
448          * now until the scheduler thread is unparked.
449          */
450         if (bad && bad->sched == sched)
451                 /*
452                  * Add at the head of the queue to reflect it was the earliest
453                  * job extracted.
454                  */
455                 list_add(&bad->list, &sched->pending_list);
456
457         /*
458          * Iterate the job list from later to  earlier one and either deactive
459          * their HW callbacks or remove them from pending list if they already
460          * signaled.
461          * This iteration is thread safe as sched thread is stopped.
462          */
463         list_for_each_entry_safe_reverse(s_job, tmp, &sched->pending_list,
464                                          list) {
465                 if (s_job->s_fence->parent &&
466                     dma_fence_remove_callback(s_job->s_fence->parent,
467                                               &s_job->cb)) {
468                         dma_fence_put(s_job->s_fence->parent);
469                         s_job->s_fence->parent = NULL;
470                         atomic_dec(&sched->hw_rq_count);
471                 } else {
472                         /*
473                          * remove job from pending_list.
474                          * Locking here is for concurrent resume timeout
475                          */
476                         spin_lock(&sched->job_list_lock);
477                         list_del_init(&s_job->list);
478                         spin_unlock(&sched->job_list_lock);
479
480                         /*
481                          * Wait for job's HW fence callback to finish using s_job
482                          * before releasing it.
483                          *
484                          * Job is still alive so fence refcount at least 1
485                          */
486                         dma_fence_wait(&s_job->s_fence->finished, false);
487
488                         /*
489                          * We must keep bad job alive for later use during
490                          * recovery by some of the drivers but leave a hint
491                          * that the guilty job must be released.
492                          */
493                         if (bad != s_job)
494                                 sched->ops->free_job(s_job);
495                         else
496                                 sched->free_guilty = true;
497                 }
498         }
499
500         /*
501          * Stop pending timer in flight as we rearm it in  drm_sched_start. This
502          * avoids the pending timeout work in progress to fire right away after
503          * this TDR finished and before the newly restarted jobs had a
504          * chance to complete.
505          */
506         cancel_delayed_work(&sched->work_tdr);
507 }
508
509 EXPORT_SYMBOL(drm_sched_stop);
510
511 /**
512  * drm_sched_start - recover jobs after a reset
513  *
514  * @sched: scheduler instance
515  * @full_recovery: proceed with complete sched restart
516  *
517  */
518 void drm_sched_start(struct drm_gpu_scheduler *sched, bool full_recovery)
519 {
520         struct drm_sched_job *s_job, *tmp;
521         int r;
522
523         /*
524          * Locking the list is not required here as the sched thread is parked
525          * so no new jobs are being inserted or removed. Also concurrent
526          * GPU recovers can't run in parallel.
527          */
528         list_for_each_entry_safe(s_job, tmp, &sched->pending_list, list) {
529                 struct dma_fence *fence = s_job->s_fence->parent;
530
531                 atomic_inc(&sched->hw_rq_count);
532
533                 if (!full_recovery)
534                         continue;
535
536                 if (fence) {
537                         r = dma_fence_add_callback(fence, &s_job->cb,
538                                                    drm_sched_job_done_cb);
539                         if (r == -ENOENT)
540                                 drm_sched_job_done(s_job);
541                         else if (r)
542                                 DRM_DEV_ERROR(sched->dev, "fence add callback failed (%d)\n",
543                                           r);
544                 } else
545                         drm_sched_job_done(s_job);
546         }
547
548         if (full_recovery) {
549                 spin_lock(&sched->job_list_lock);
550                 drm_sched_start_timeout(sched);
551                 spin_unlock(&sched->job_list_lock);
552         }
553
554         kthread_unpark(sched->thread);
555 }
556 EXPORT_SYMBOL(drm_sched_start);
557
558 /**
559  * drm_sched_resubmit_jobs - Deprecated, don't use in new code!
560  *
561  * @sched: scheduler instance
562  *
563  * Re-submitting jobs was a concept AMD came up as cheap way to implement
564  * recovery after a job timeout.
565  *
566  * This turned out to be not working very well. First of all there are many
567  * problem with the dma_fence implementation and requirements. Either the
568  * implementation is risking deadlocks with core memory management or violating
569  * documented implementation details of the dma_fence object.
570  *
571  * Drivers can still save and restore their state for recovery operations, but
572  * we shouldn't make this a general scheduler feature around the dma_fence
573  * interface.
574  */
575 void drm_sched_resubmit_jobs(struct drm_gpu_scheduler *sched)
576 {
577         struct drm_sched_job *s_job, *tmp;
578         uint64_t guilty_context;
579         bool found_guilty = false;
580         struct dma_fence *fence;
581
582         list_for_each_entry_safe(s_job, tmp, &sched->pending_list, list) {
583                 struct drm_sched_fence *s_fence = s_job->s_fence;
584
585                 if (!found_guilty && atomic_read(&s_job->karma) > sched->hang_limit) {
586                         found_guilty = true;
587                         guilty_context = s_job->s_fence->scheduled.context;
588                 }
589
590                 if (found_guilty && s_job->s_fence->scheduled.context == guilty_context)
591                         dma_fence_set_error(&s_fence->finished, -ECANCELED);
592
593                 fence = sched->ops->run_job(s_job);
594
595                 if (IS_ERR_OR_NULL(fence)) {
596                         if (IS_ERR(fence))
597                                 dma_fence_set_error(&s_fence->finished, PTR_ERR(fence));
598
599                         s_job->s_fence->parent = NULL;
600                 } else {
601
602                         s_job->s_fence->parent = dma_fence_get(fence);
603
604                         /* Drop for orignal kref_init */
605                         dma_fence_put(fence);
606                 }
607         }
608 }
609 EXPORT_SYMBOL(drm_sched_resubmit_jobs);
610
611 /**
612  * drm_sched_job_init - init a scheduler job
613  * @job: scheduler job to init
614  * @entity: scheduler entity to use
615  * @owner: job owner for debugging
616  *
617  * Refer to drm_sched_entity_push_job() documentation
618  * for locking considerations.
619  *
620  * Drivers must make sure drm_sched_job_cleanup() if this function returns
621  * successfully, even when @job is aborted before drm_sched_job_arm() is called.
622  *
623  * WARNING: amdgpu abuses &drm_sched.ready to signal when the hardware
624  * has died, which can mean that there's no valid runqueue for a @entity.
625  * This function returns -ENOENT in this case (which probably should be -EIO as
626  * a more meanigful return value).
627  *
628  * Returns 0 for success, negative error code otherwise.
629  */
630 int drm_sched_job_init(struct drm_sched_job *job,
631                        struct drm_sched_entity *entity,
632                        void *owner)
633 {
634         if (!entity->rq)
635                 return -ENOENT;
636
637         job->entity = entity;
638         job->s_fence = drm_sched_fence_alloc(entity, owner);
639         if (!job->s_fence)
640                 return -ENOMEM;
641
642         INIT_LIST_HEAD(&job->list);
643
644         xa_init_flags(&job->dependencies, XA_FLAGS_ALLOC);
645
646         return 0;
647 }
648 EXPORT_SYMBOL(drm_sched_job_init);
649
650 /**
651  * drm_sched_job_arm - arm a scheduler job for execution
652  * @job: scheduler job to arm
653  *
654  * This arms a scheduler job for execution. Specifically it initializes the
655  * &drm_sched_job.s_fence of @job, so that it can be attached to struct dma_resv
656  * or other places that need to track the completion of this job.
657  *
658  * Refer to drm_sched_entity_push_job() documentation for locking
659  * considerations.
660  *
661  * This can only be called if drm_sched_job_init() succeeded.
662  */
663 void drm_sched_job_arm(struct drm_sched_job *job)
664 {
665         struct drm_gpu_scheduler *sched;
666         struct drm_sched_entity *entity = job->entity;
667
668         BUG_ON(!entity);
669         drm_sched_entity_select_rq(entity);
670         sched = entity->rq->sched;
671
672         job->sched = sched;
673         job->s_priority = entity->rq - sched->sched_rq;
674         job->id = atomic64_inc_return(&sched->job_id_count);
675
676         drm_sched_fence_init(job->s_fence, job->entity);
677 }
678 EXPORT_SYMBOL(drm_sched_job_arm);
679
680 /**
681  * drm_sched_job_add_dependency - adds the fence as a job dependency
682  * @job: scheduler job to add the dependencies to
683  * @fence: the dma_fence to add to the list of dependencies.
684  *
685  * Note that @fence is consumed in both the success and error cases.
686  *
687  * Returns:
688  * 0 on success, or an error on failing to expand the array.
689  */
690 int drm_sched_job_add_dependency(struct drm_sched_job *job,
691                                  struct dma_fence *fence)
692 {
693         struct dma_fence *entry;
694         unsigned long index;
695         u32 id = 0;
696         int ret;
697
698         if (!fence)
699                 return 0;
700
701         /* Deduplicate if we already depend on a fence from the same context.
702          * This lets the size of the array of deps scale with the number of
703          * engines involved, rather than the number of BOs.
704          */
705         xa_for_each(&job->dependencies, index, entry) {
706                 if (entry->context != fence->context)
707                         continue;
708
709                 if (dma_fence_is_later(fence, entry)) {
710                         dma_fence_put(entry);
711                         xa_store(&job->dependencies, index, fence, GFP_KERNEL);
712                 } else {
713                         dma_fence_put(fence);
714                 }
715                 return 0;
716         }
717
718         ret = xa_alloc(&job->dependencies, &id, fence, xa_limit_32b, GFP_KERNEL);
719         if (ret != 0)
720                 dma_fence_put(fence);
721
722         return ret;
723 }
724 EXPORT_SYMBOL(drm_sched_job_add_dependency);
725
726 /**
727  * drm_sched_job_add_syncobj_dependency - adds a syncobj's fence as a job dependency
728  * @job: scheduler job to add the dependencies to
729  * @file: drm file private pointer
730  * @handle: syncobj handle to lookup
731  * @point: timeline point
732  *
733  * This adds the fence matching the given syncobj to @job.
734  *
735  * Returns:
736  * 0 on success, or an error on failing to expand the array.
737  */
738 int drm_sched_job_add_syncobj_dependency(struct drm_sched_job *job,
739                                          struct drm_file *file,
740                                          u32 handle,
741                                          u32 point)
742 {
743         struct dma_fence *fence;
744         int ret;
745
746         ret = drm_syncobj_find_fence(file, handle, point, 0, &fence);
747         if (ret)
748                 return ret;
749
750         return drm_sched_job_add_dependency(job, fence);
751 }
752 EXPORT_SYMBOL(drm_sched_job_add_syncobj_dependency);
753
754 /**
755  * drm_sched_job_add_resv_dependencies - add all fences from the resv to the job
756  * @job: scheduler job to add the dependencies to
757  * @resv: the dma_resv object to get the fences from
758  * @usage: the dma_resv_usage to use to filter the fences
759  *
760  * This adds all fences matching the given usage from @resv to @job.
761  * Must be called with the @resv lock held.
762  *
763  * Returns:
764  * 0 on success, or an error on failing to expand the array.
765  */
766 int drm_sched_job_add_resv_dependencies(struct drm_sched_job *job,
767                                         struct dma_resv *resv,
768                                         enum dma_resv_usage usage)
769 {
770         struct dma_resv_iter cursor;
771         struct dma_fence *fence;
772         int ret;
773
774         dma_resv_assert_held(resv);
775
776         dma_resv_for_each_fence(&cursor, resv, usage, fence) {
777                 /* Make sure to grab an additional ref on the added fence */
778                 dma_fence_get(fence);
779                 ret = drm_sched_job_add_dependency(job, fence);
780                 if (ret) {
781                         dma_fence_put(fence);
782                         return ret;
783                 }
784         }
785         return 0;
786 }
787 EXPORT_SYMBOL(drm_sched_job_add_resv_dependencies);
788
789 /**
790  * drm_sched_job_add_implicit_dependencies - adds implicit dependencies as job
791  *   dependencies
792  * @job: scheduler job to add the dependencies to
793  * @obj: the gem object to add new dependencies from.
794  * @write: whether the job might write the object (so we need to depend on
795  * shared fences in the reservation object).
796  *
797  * This should be called after drm_gem_lock_reservations() on your array of
798  * GEM objects used in the job but before updating the reservations with your
799  * own fences.
800  *
801  * Returns:
802  * 0 on success, or an error on failing to expand the array.
803  */
804 int drm_sched_job_add_implicit_dependencies(struct drm_sched_job *job,
805                                             struct drm_gem_object *obj,
806                                             bool write)
807 {
808         return drm_sched_job_add_resv_dependencies(job, obj->resv,
809                                                    dma_resv_usage_rw(write));
810 }
811 EXPORT_SYMBOL(drm_sched_job_add_implicit_dependencies);
812
813 /**
814  * drm_sched_job_cleanup - clean up scheduler job resources
815  * @job: scheduler job to clean up
816  *
817  * Cleans up the resources allocated with drm_sched_job_init().
818  *
819  * Drivers should call this from their error unwind code if @job is aborted
820  * before drm_sched_job_arm() is called.
821  *
822  * After that point of no return @job is committed to be executed by the
823  * scheduler, and this function should be called from the
824  * &drm_sched_backend_ops.free_job callback.
825  */
826 void drm_sched_job_cleanup(struct drm_sched_job *job)
827 {
828         struct dma_fence *fence;
829         unsigned long index;
830
831         if (kref_read(&job->s_fence->finished.refcount)) {
832                 /* drm_sched_job_arm() has been called */
833                 dma_fence_put(&job->s_fence->finished);
834         } else {
835                 /* aborted job before committing to run it */
836                 drm_sched_fence_free(job->s_fence);
837         }
838
839         job->s_fence = NULL;
840
841         xa_for_each(&job->dependencies, index, fence) {
842                 dma_fence_put(fence);
843         }
844         xa_destroy(&job->dependencies);
845
846 }
847 EXPORT_SYMBOL(drm_sched_job_cleanup);
848
849 /**
850  * drm_sched_ready - is the scheduler ready
851  *
852  * @sched: scheduler instance
853  *
854  * Return true if we can push more jobs to the hw, otherwise false.
855  */
856 static bool drm_sched_ready(struct drm_gpu_scheduler *sched)
857 {
858         return atomic_read(&sched->hw_rq_count) <
859                 sched->hw_submission_limit;
860 }
861
862 /**
863  * drm_sched_wakeup - Wake up the scheduler when it is ready
864  *
865  * @sched: scheduler instance
866  *
867  */
868 void drm_sched_wakeup(struct drm_gpu_scheduler *sched)
869 {
870         if (drm_sched_ready(sched))
871                 wake_up_interruptible(&sched->wake_up_worker);
872 }
873
874 /**
875  * drm_sched_select_entity - Select next entity to process
876  *
877  * @sched: scheduler instance
878  *
879  * Returns the entity to process or NULL if none are found.
880  */
881 static struct drm_sched_entity *
882 drm_sched_select_entity(struct drm_gpu_scheduler *sched)
883 {
884         struct drm_sched_entity *entity;
885         int i;
886
887         if (!drm_sched_ready(sched))
888                 return NULL;
889
890         /* Kernel run queue has higher priority than normal run queue*/
891         for (i = DRM_SCHED_PRIORITY_COUNT - 1; i >= DRM_SCHED_PRIORITY_MIN; i--) {
892                 entity = drm_sched_policy == DRM_SCHED_POLICY_FIFO ?
893                         drm_sched_rq_select_entity_fifo(&sched->sched_rq[i]) :
894                         drm_sched_rq_select_entity_rr(&sched->sched_rq[i]);
895                 if (entity)
896                         break;
897         }
898
899         return entity;
900 }
901
902 /**
903  * drm_sched_get_cleanup_job - fetch the next finished job to be destroyed
904  *
905  * @sched: scheduler instance
906  *
907  * Returns the next finished job from the pending list (if there is one)
908  * ready for it to be destroyed.
909  */
910 static struct drm_sched_job *
911 drm_sched_get_cleanup_job(struct drm_gpu_scheduler *sched)
912 {
913         struct drm_sched_job *job, *next;
914
915         spin_lock(&sched->job_list_lock);
916
917         job = list_first_entry_or_null(&sched->pending_list,
918                                        struct drm_sched_job, list);
919
920         if (job && dma_fence_is_signaled(&job->s_fence->finished)) {
921                 /* remove job from pending_list */
922                 list_del_init(&job->list);
923
924                 /* cancel this job's TO timer */
925                 cancel_delayed_work(&sched->work_tdr);
926                 /* make the scheduled timestamp more accurate */
927                 next = list_first_entry_or_null(&sched->pending_list,
928                                                 typeof(*next), list);
929
930                 if (next) {
931                         next->s_fence->scheduled.timestamp =
932                                 job->s_fence->finished.timestamp;
933                         /* start TO timer for next job */
934                         drm_sched_start_timeout(sched);
935                 }
936         } else {
937                 job = NULL;
938         }
939
940         spin_unlock(&sched->job_list_lock);
941
942         if (job) {
943                 job->entity->elapsed_ns += ktime_to_ns(
944                         ktime_sub(job->s_fence->finished.timestamp,
945                                   job->s_fence->scheduled.timestamp));
946         }
947
948         return job;
949 }
950
951 /**
952  * drm_sched_pick_best - Get a drm sched from a sched_list with the least load
953  * @sched_list: list of drm_gpu_schedulers
954  * @num_sched_list: number of drm_gpu_schedulers in the sched_list
955  *
956  * Returns pointer of the sched with the least load or NULL if none of the
957  * drm_gpu_schedulers are ready
958  */
959 struct drm_gpu_scheduler *
960 drm_sched_pick_best(struct drm_gpu_scheduler **sched_list,
961                      unsigned int num_sched_list)
962 {
963         struct drm_gpu_scheduler *sched, *picked_sched = NULL;
964         int i;
965         unsigned int min_score = UINT_MAX, num_score;
966
967         for (i = 0; i < num_sched_list; ++i) {
968                 sched = sched_list[i];
969
970                 if (!sched->ready) {
971                         DRM_WARN("scheduler %s is not ready, skipping",
972                                  sched->name);
973                         continue;
974                 }
975
976                 num_score = atomic_read(sched->score);
977                 if (num_score < min_score) {
978                         min_score = num_score;
979                         picked_sched = sched;
980                 }
981         }
982
983         return picked_sched;
984 }
985 EXPORT_SYMBOL(drm_sched_pick_best);
986
987 /**
988  * drm_sched_blocked - check if the scheduler is blocked
989  *
990  * @sched: scheduler instance
991  *
992  * Returns true if blocked, otherwise false.
993  */
994 static bool drm_sched_blocked(struct drm_gpu_scheduler *sched)
995 {
996         if (kthread_should_park()) {
997                 kthread_parkme();
998                 return true;
999         }
1000
1001         return false;
1002 }
1003
1004 /**
1005  * drm_sched_main - main scheduler thread
1006  *
1007  * @param: scheduler instance
1008  *
1009  * Returns 0.
1010  */
1011 static int drm_sched_main(void *param)
1012 {
1013         struct drm_gpu_scheduler *sched = (struct drm_gpu_scheduler *)param;
1014         int r;
1015
1016         sched_set_fifo_low(current);
1017
1018         while (!kthread_should_stop()) {
1019                 struct drm_sched_entity *entity = NULL;
1020                 struct drm_sched_fence *s_fence;
1021                 struct drm_sched_job *sched_job;
1022                 struct dma_fence *fence;
1023                 struct drm_sched_job *cleanup_job = NULL;
1024
1025                 wait_event_interruptible(sched->wake_up_worker,
1026                                          (cleanup_job = drm_sched_get_cleanup_job(sched)) ||
1027                                          (!drm_sched_blocked(sched) &&
1028                                           (entity = drm_sched_select_entity(sched))) ||
1029                                          kthread_should_stop());
1030
1031                 if (cleanup_job)
1032                         sched->ops->free_job(cleanup_job);
1033
1034                 if (!entity)
1035                         continue;
1036
1037                 sched_job = drm_sched_entity_pop_job(entity);
1038
1039                 if (!sched_job) {
1040                         complete_all(&entity->entity_idle);
1041                         continue;
1042                 }
1043
1044                 s_fence = sched_job->s_fence;
1045
1046                 atomic_inc(&sched->hw_rq_count);
1047                 drm_sched_job_begin(sched_job);
1048
1049                 trace_drm_run_job(sched_job, entity);
1050                 fence = sched->ops->run_job(sched_job);
1051                 complete_all(&entity->entity_idle);
1052                 drm_sched_fence_scheduled(s_fence);
1053
1054                 if (!IS_ERR_OR_NULL(fence)) {
1055                         drm_sched_fence_set_parent(s_fence, fence);
1056                         /* Drop for original kref_init of the fence */
1057                         dma_fence_put(fence);
1058
1059                         r = dma_fence_add_callback(fence, &sched_job->cb,
1060                                                    drm_sched_job_done_cb);
1061                         if (r == -ENOENT)
1062                                 drm_sched_job_done(sched_job);
1063                         else if (r)
1064                                 DRM_DEV_ERROR(sched->dev, "fence add callback failed (%d)\n",
1065                                           r);
1066                 } else {
1067                         if (IS_ERR(fence))
1068                                 dma_fence_set_error(&s_fence->finished, PTR_ERR(fence));
1069
1070                         drm_sched_job_done(sched_job);
1071                 }
1072
1073                 wake_up(&sched->job_scheduled);
1074         }
1075         return 0;
1076 }
1077
1078 /**
1079  * drm_sched_init - Init a gpu scheduler instance
1080  *
1081  * @sched: scheduler instance
1082  * @ops: backend operations for this scheduler
1083  * @hw_submission: number of hw submissions that can be in flight
1084  * @hang_limit: number of times to allow a job to hang before dropping it
1085  * @timeout: timeout value in jiffies for the scheduler
1086  * @timeout_wq: workqueue to use for timeout work. If NULL, the system_wq is
1087  *              used
1088  * @score: optional score atomic shared with other schedulers
1089  * @name: name used for debugging
1090  * @dev: target &struct device
1091  *
1092  * Return 0 on success, otherwise error code.
1093  */
1094 int drm_sched_init(struct drm_gpu_scheduler *sched,
1095                    const struct drm_sched_backend_ops *ops,
1096                    unsigned hw_submission, unsigned hang_limit,
1097                    long timeout, struct workqueue_struct *timeout_wq,
1098                    atomic_t *score, const char *name, struct device *dev)
1099 {
1100         int i, ret;
1101         sched->ops = ops;
1102         sched->hw_submission_limit = hw_submission;
1103         sched->name = name;
1104         sched->timeout = timeout;
1105         sched->timeout_wq = timeout_wq ? : system_wq;
1106         sched->hang_limit = hang_limit;
1107         sched->score = score ? score : &sched->_score;
1108         sched->dev = dev;
1109         for (i = DRM_SCHED_PRIORITY_MIN; i < DRM_SCHED_PRIORITY_COUNT; i++)
1110                 drm_sched_rq_init(sched, &sched->sched_rq[i]);
1111
1112         init_waitqueue_head(&sched->wake_up_worker);
1113         init_waitqueue_head(&sched->job_scheduled);
1114         INIT_LIST_HEAD(&sched->pending_list);
1115         spin_lock_init(&sched->job_list_lock);
1116         atomic_set(&sched->hw_rq_count, 0);
1117         INIT_DELAYED_WORK(&sched->work_tdr, drm_sched_job_timedout);
1118         atomic_set(&sched->_score, 0);
1119         atomic64_set(&sched->job_id_count, 0);
1120
1121         /* Each scheduler will run on a seperate kernel thread */
1122         sched->thread = kthread_run(drm_sched_main, sched, sched->name);
1123         if (IS_ERR(sched->thread)) {
1124                 ret = PTR_ERR(sched->thread);
1125                 sched->thread = NULL;
1126                 DRM_DEV_ERROR(sched->dev, "Failed to create scheduler for %s.\n", name);
1127                 return ret;
1128         }
1129
1130         sched->ready = true;
1131         return 0;
1132 }
1133 EXPORT_SYMBOL(drm_sched_init);
1134
1135 /**
1136  * drm_sched_fini - Destroy a gpu scheduler
1137  *
1138  * @sched: scheduler instance
1139  *
1140  * Tears down and cleans up the scheduler.
1141  */
1142 void drm_sched_fini(struct drm_gpu_scheduler *sched)
1143 {
1144         struct drm_sched_entity *s_entity;
1145         int i;
1146
1147         if (sched->thread)
1148                 kthread_stop(sched->thread);
1149
1150         for (i = DRM_SCHED_PRIORITY_COUNT - 1; i >= DRM_SCHED_PRIORITY_MIN; i--) {
1151                 struct drm_sched_rq *rq = &sched->sched_rq[i];
1152
1153                 if (!rq)
1154                         continue;
1155
1156                 spin_lock(&rq->lock);
1157                 list_for_each_entry(s_entity, &rq->entities, list)
1158                         /*
1159                          * Prevents reinsertion and marks job_queue as idle,
1160                          * it will removed from rq in drm_sched_entity_fini
1161                          * eventually
1162                          */
1163                         s_entity->stopped = true;
1164                 spin_unlock(&rq->lock);
1165
1166         }
1167
1168         /* Wakeup everyone stuck in drm_sched_entity_flush for this scheduler */
1169         wake_up_all(&sched->job_scheduled);
1170
1171         /* Confirm no work left behind accessing device structures */
1172         cancel_delayed_work_sync(&sched->work_tdr);
1173
1174         sched->ready = false;
1175 }
1176 EXPORT_SYMBOL(drm_sched_fini);
1177
1178 /**
1179  * drm_sched_increase_karma - Update sched_entity guilty flag
1180  *
1181  * @bad: The job guilty of time out
1182  *
1183  * Increment on every hang caused by the 'bad' job. If this exceeds the hang
1184  * limit of the scheduler then the respective sched entity is marked guilty and
1185  * jobs from it will not be scheduled further
1186  */
1187 void drm_sched_increase_karma(struct drm_sched_job *bad)
1188 {
1189         int i;
1190         struct drm_sched_entity *tmp;
1191         struct drm_sched_entity *entity;
1192         struct drm_gpu_scheduler *sched = bad->sched;
1193
1194         /* don't change @bad's karma if it's from KERNEL RQ,
1195          * because sometimes GPU hang would cause kernel jobs (like VM updating jobs)
1196          * corrupt but keep in mind that kernel jobs always considered good.
1197          */
1198         if (bad->s_priority != DRM_SCHED_PRIORITY_KERNEL) {
1199                 atomic_inc(&bad->karma);
1200
1201                 for (i = DRM_SCHED_PRIORITY_MIN; i < DRM_SCHED_PRIORITY_KERNEL;
1202                      i++) {
1203                         struct drm_sched_rq *rq = &sched->sched_rq[i];
1204
1205                         spin_lock(&rq->lock);
1206                         list_for_each_entry_safe(entity, tmp, &rq->entities, list) {
1207                                 if (bad->s_fence->scheduled.context ==
1208                                     entity->fence_context) {
1209                                         if (entity->guilty)
1210                                                 atomic_set(entity->guilty, 1);
1211                                         break;
1212                                 }
1213                         }
1214                         spin_unlock(&rq->lock);
1215                         if (&entity->list != &rq->entities)
1216                                 break;
1217                 }
1218         }
1219 }
1220 EXPORT_SYMBOL(drm_sched_increase_karma);