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 #ifndef _DRM_GPU_SCHEDULER_H_
25 #define _DRM_GPU_SCHEDULER_H_
26 
27 #include <drm/spsc_queue.h>
28 #include <linux/dma-fence.h>
29 #include <linux/completion.h>
30 #include <linux/xarray.h>
31 #include <linux/workqueue.h>
32 
33 #define MAX_WAIT_SCHED_ENTITY_Q_EMPTY msecs_to_jiffies(1000)
34 
35 /**
36  * DRM_SCHED_FENCE_DONT_PIPELINE - Prefent dependency pipelining
37  *
38  * Setting this flag on a scheduler fence prevents pipelining of jobs depending
39  * on this fence. In other words we always insert a full CPU round trip before
40  * dependen jobs are pushed to the hw queue.
41  */
42 #define DRM_SCHED_FENCE_DONT_PIPELINE	DMA_FENCE_FLAG_USER_BITS
43 
44 struct drm_gem_object;
45 
46 struct drm_gpu_scheduler;
47 struct drm_sched_rq;
48 
49 /* These are often used as an (initial) index
50  * to an array, and as such should start at 0.
51  */
52 enum drm_sched_priority {
53 	DRM_SCHED_PRIORITY_MIN,
54 	DRM_SCHED_PRIORITY_NORMAL,
55 	DRM_SCHED_PRIORITY_HIGH,
56 	DRM_SCHED_PRIORITY_KERNEL,
57 
58 	DRM_SCHED_PRIORITY_COUNT,
59 	DRM_SCHED_PRIORITY_UNSET = -2
60 };
61 
62 /**
63  * struct drm_sched_entity - A wrapper around a job queue (typically
64  * attached to the DRM file_priv).
65  *
66  * Entities will emit jobs in order to their corresponding hardware
67  * ring, and the scheduler will alternate between entities based on
68  * scheduling policy.
69  */
70 struct drm_sched_entity {
71 	/**
72 	 * @list:
73 	 *
74 	 * Used to append this struct to the list of entities in the runqueue
75 	 * @rq under &drm_sched_rq.entities.
76 	 *
77 	 * Protected by &drm_sched_rq.lock of @rq.
78 	 */
79 	struct list_head		list;
80 
81 	/**
82 	 * @rq:
83 	 *
84 	 * Runqueue on which this entity is currently scheduled.
85 	 *
86 	 * FIXME: Locking is very unclear for this. Writers are protected by
87 	 * @rq_lock, but readers are generally lockless and seem to just race
88 	 * with not even a READ_ONCE.
89 	 */
90 	struct drm_sched_rq		*rq;
91 
92 	/**
93 	 * @sched_list:
94 	 *
95 	 * A list of schedulers (struct drm_gpu_scheduler).  Jobs from this entity can
96 	 * be scheduled on any scheduler on this list.
97 	 *
98 	 * This can be modified by calling drm_sched_entity_modify_sched().
99 	 * Locking is entirely up to the driver, see the above function for more
100 	 * details.
101 	 *
102 	 * This will be set to NULL if &num_sched_list equals 1 and @rq has been
103 	 * set already.
104 	 *
105 	 * FIXME: This means priority changes through
106 	 * drm_sched_entity_set_priority() will be lost henceforth in this case.
107 	 */
108 	struct drm_gpu_scheduler        **sched_list;
109 
110 	/**
111 	 * @num_sched_list:
112 	 *
113 	 * Number of drm_gpu_schedulers in the @sched_list.
114 	 */
115 	unsigned int                    num_sched_list;
116 
117 	/**
118 	 * @priority:
119 	 *
120 	 * Priority of the entity. This can be modified by calling
121 	 * drm_sched_entity_set_priority(). Protected by &rq_lock.
122 	 */
123 	enum drm_sched_priority         priority;
124 
125 	/**
126 	 * @rq_lock:
127 	 *
128 	 * Lock to modify the runqueue to which this entity belongs.
129 	 */
130 	spinlock_t			rq_lock;
131 
132 	/**
133 	 * @job_queue: the list of jobs of this entity.
134 	 */
135 	struct spsc_queue		job_queue;
136 
137 	/**
138 	 * @fence_seq:
139 	 *
140 	 * A linearly increasing seqno incremented with each new
141 	 * &drm_sched_fence which is part of the entity.
142 	 *
143 	 * FIXME: Callers of drm_sched_job_arm() need to ensure correct locking,
144 	 * this doesn't need to be atomic.
145 	 */
146 	atomic_t			fence_seq;
147 
148 	/**
149 	 * @fence_context:
150 	 *
151 	 * A unique context for all the fences which belong to this entity.  The
152 	 * &drm_sched_fence.scheduled uses the fence_context but
153 	 * &drm_sched_fence.finished uses fence_context + 1.
154 	 */
155 	uint64_t			fence_context;
156 
157 	/**
158 	 * @dependency:
159 	 *
160 	 * The dependency fence of the job which is on the top of the job queue.
161 	 */
162 	struct dma_fence		*dependency;
163 
164 	/**
165 	 * @cb:
166 	 *
167 	 * Callback for the dependency fence above.
168 	 */
169 	struct dma_fence_cb		cb;
170 
171 	/**
172 	 * @guilty:
173 	 *
174 	 * Points to entities' guilty.
175 	 */
176 	atomic_t			*guilty;
177 
178 	/**
179 	 * @last_scheduled:
180 	 *
181 	 * Points to the finished fence of the last scheduled job. Only written
182 	 * by the scheduler thread, can be accessed locklessly from
183 	 * drm_sched_job_arm() iff the queue is empty.
184 	 */
185 	struct dma_fence                *last_scheduled;
186 
187 	/**
188 	 * @last_user: last group leader pushing a job into the entity.
189 	 */
190 	struct task_struct		*last_user;
191 
192 	/**
193 	 * @stopped:
194 	 *
195 	 * Marks the enity as removed from rq and destined for
196 	 * termination. This is set by calling drm_sched_entity_flush() and by
197 	 * drm_sched_fini().
198 	 */
199 	bool 				stopped;
200 
201 	/**
202 	 * @entity_idle:
203 	 *
204 	 * Signals when entity is not in use, used to sequence entity cleanup in
205 	 * drm_sched_entity_fini().
206 	 */
207 	struct completion		entity_idle;
208 };
209 
210 /**
211  * struct drm_sched_rq - queue of entities to be scheduled.
212  *
213  * @lock: to modify the entities list.
214  * @sched: the scheduler to which this rq belongs to.
215  * @entities: list of the entities to be scheduled.
216  * @current_entity: the entity which is to be scheduled.
217  *
218  * Run queue is a set of entities scheduling command submissions for
219  * one specific ring. It implements the scheduling policy that selects
220  * the next entity to emit commands from.
221  */
222 struct drm_sched_rq {
223 	spinlock_t			lock;
224 	struct drm_gpu_scheduler	*sched;
225 	struct list_head		entities;
226 	struct drm_sched_entity		*current_entity;
227 };
228 
229 /**
230  * struct drm_sched_fence - fences corresponding to the scheduling of a job.
231  */
232 struct drm_sched_fence {
233         /**
234          * @scheduled: this fence is what will be signaled by the scheduler
235          * when the job is scheduled.
236          */
237 	struct dma_fence		scheduled;
238 
239         /**
240          * @finished: this fence is what will be signaled by the scheduler
241          * when the job is completed.
242          *
243          * When setting up an out fence for the job, you should use
244          * this, since it's available immediately upon
245          * drm_sched_job_init(), and the fence returned by the driver
246          * from run_job() won't be created until the dependencies have
247          * resolved.
248          */
249 	struct dma_fence		finished;
250 
251         /**
252          * @parent: the fence returned by &drm_sched_backend_ops.run_job
253          * when scheduling the job on hardware. We signal the
254          * &drm_sched_fence.finished fence once parent is signalled.
255          */
256 	struct dma_fence		*parent;
257         /**
258          * @sched: the scheduler instance to which the job having this struct
259          * belongs to.
260          */
261 	struct drm_gpu_scheduler	*sched;
262         /**
263          * @lock: the lock used by the scheduled and the finished fences.
264          */
265 	spinlock_t			lock;
266         /**
267          * @owner: job owner for debugging
268          */
269 	void				*owner;
270 };
271 
272 struct drm_sched_fence *to_drm_sched_fence(struct dma_fence *f);
273 
274 /**
275  * struct drm_sched_job - A job to be run by an entity.
276  *
277  * @queue_node: used to append this struct to the queue of jobs in an entity.
278  * @list: a job participates in a "pending" and "done" lists.
279  * @sched: the scheduler instance on which this job is scheduled.
280  * @s_fence: contains the fences for the scheduling of job.
281  * @finish_cb: the callback for the finished fence.
282  * @work: Helper to reschdeule job kill to different context.
283  * @id: a unique id assigned to each job scheduled on the scheduler.
284  * @karma: increment on every hang caused by this job. If this exceeds the hang
285  *         limit of the scheduler then the job is marked guilty and will not
286  *         be scheduled further.
287  * @s_priority: the priority of the job.
288  * @entity: the entity to which this job belongs.
289  * @cb: the callback for the parent fence in s_fence.
290  *
291  * A job is created by the driver using drm_sched_job_init(), and
292  * should call drm_sched_entity_push_job() once it wants the scheduler
293  * to schedule the job.
294  */
295 struct drm_sched_job {
296 	struct spsc_node		queue_node;
297 	struct list_head		list;
298 	struct drm_gpu_scheduler	*sched;
299 	struct drm_sched_fence		*s_fence;
300 
301 	/*
302 	 * work is used only after finish_cb has been used and will not be
303 	 * accessed anymore.
304 	 */
305 	union {
306 		struct dma_fence_cb		finish_cb;
307 		struct work_struct 		work;
308 	};
309 
310 	uint64_t			id;
311 	atomic_t			karma;
312 	enum drm_sched_priority		s_priority;
313 	struct drm_sched_entity         *entity;
314 	struct dma_fence_cb		cb;
315 	/**
316 	 * @dependencies:
317 	 *
318 	 * Contains the dependencies as struct dma_fence for this job, see
319 	 * drm_sched_job_add_dependency() and
320 	 * drm_sched_job_add_implicit_dependencies().
321 	 */
322 	struct xarray			dependencies;
323 
324 	/** @last_dependency: tracks @dependencies as they signal */
325 	unsigned long			last_dependency;
326 };
327 
drm_sched_invalidate_job(struct drm_sched_job * s_job,int threshold)328 static inline bool drm_sched_invalidate_job(struct drm_sched_job *s_job,
329 					    int threshold)
330 {
331 	return s_job && atomic_inc_return(&s_job->karma) > threshold;
332 }
333 
334 enum drm_gpu_sched_stat {
335 	DRM_GPU_SCHED_STAT_NONE, /* Reserve 0 */
336 	DRM_GPU_SCHED_STAT_NOMINAL,
337 	DRM_GPU_SCHED_STAT_ENODEV,
338 };
339 
340 /**
341  * struct drm_sched_backend_ops - Define the backend operations
342  *	called by the scheduler
343  *
344  * These functions should be implemented in the driver side.
345  */
346 struct drm_sched_backend_ops {
347 	/**
348 	 * @dependency:
349 	 *
350 	 * Called when the scheduler is considering scheduling this job next, to
351 	 * get another struct dma_fence for this job to block on.  Once it
352 	 * returns NULL, run_job() may be called.
353 	 *
354 	 * If a driver exclusively uses drm_sched_job_add_dependency() and
355 	 * drm_sched_job_add_implicit_dependencies() this can be ommitted and
356 	 * left as NULL.
357 	 */
358 	struct dma_fence *(*dependency)(struct drm_sched_job *sched_job,
359 					struct drm_sched_entity *s_entity);
360 
361 	/**
362          * @run_job: Called to execute the job once all of the dependencies
363          * have been resolved.  This may be called multiple times, if
364 	 * timedout_job() has happened and drm_sched_job_recovery()
365 	 * decides to try it again.
366 	 */
367 	struct dma_fence *(*run_job)(struct drm_sched_job *sched_job);
368 
369 	/**
370 	 * @timedout_job: Called when a job has taken too long to execute,
371 	 * to trigger GPU recovery.
372 	 *
373 	 * This method is called in a workqueue context.
374 	 *
375 	 * Drivers typically issue a reset to recover from GPU hangs, and this
376 	 * procedure usually follows the following workflow:
377 	 *
378 	 * 1. Stop the scheduler using drm_sched_stop(). This will park the
379 	 *    scheduler thread and cancel the timeout work, guaranteeing that
380 	 *    nothing is queued while we reset the hardware queue
381 	 * 2. Try to gracefully stop non-faulty jobs (optional)
382 	 * 3. Issue a GPU reset (driver-specific)
383 	 * 4. Re-submit jobs using drm_sched_resubmit_jobs()
384 	 * 5. Restart the scheduler using drm_sched_start(). At that point, new
385 	 *    jobs can be queued, and the scheduler thread is unblocked
386 	 *
387 	 * Note that some GPUs have distinct hardware queues but need to reset
388 	 * the GPU globally, which requires extra synchronization between the
389 	 * timeout handler of the different &drm_gpu_scheduler. One way to
390 	 * achieve this synchronization is to create an ordered workqueue
391 	 * (using alloc_ordered_workqueue()) at the driver level, and pass this
392 	 * queue to drm_sched_init(), to guarantee that timeout handlers are
393 	 * executed sequentially. The above workflow needs to be slightly
394 	 * adjusted in that case:
395 	 *
396 	 * 1. Stop all schedulers impacted by the reset using drm_sched_stop()
397 	 * 2. Try to gracefully stop non-faulty jobs on all queues impacted by
398 	 *    the reset (optional)
399 	 * 3. Issue a GPU reset on all faulty queues (driver-specific)
400 	 * 4. Re-submit jobs on all schedulers impacted by the reset using
401 	 *    drm_sched_resubmit_jobs()
402 	 * 5. Restart all schedulers that were stopped in step #1 using
403 	 *    drm_sched_start()
404 	 *
405 	 * Return DRM_GPU_SCHED_STAT_NOMINAL, when all is normal,
406 	 * and the underlying driver has started or completed recovery.
407 	 *
408 	 * Return DRM_GPU_SCHED_STAT_ENODEV, if the device is no longer
409 	 * available, i.e. has been unplugged.
410 	 */
411 	enum drm_gpu_sched_stat (*timedout_job)(struct drm_sched_job *sched_job);
412 
413 	/**
414          * @free_job: Called once the job's finished fence has been signaled
415          * and it's time to clean it up.
416 	 */
417 	void (*free_job)(struct drm_sched_job *sched_job);
418 };
419 
420 /**
421  * struct drm_gpu_scheduler - scheduler instance-specific data
422  *
423  * @ops: backend operations provided by the driver.
424  * @hw_submission_limit: the max size of the hardware queue.
425  * @timeout: the time after which a job is removed from the scheduler.
426  * @name: name of the ring for which this scheduler is being used.
427  * @sched_rq: priority wise array of run queues.
428  * @wake_up_worker: the wait queue on which the scheduler sleeps until a job
429  *                  is ready to be scheduled.
430  * @job_scheduled: once @drm_sched_entity_do_release is called the scheduler
431  *                 waits on this wait queue until all the scheduled jobs are
432  *                 finished.
433  * @hw_rq_count: the number of jobs currently in the hardware queue.
434  * @job_id_count: used to assign unique id to the each job.
435  * @timeout_wq: workqueue used to queue @work_tdr
436  * @work_tdr: schedules a delayed call to @drm_sched_job_timedout after the
437  *            timeout interval is over.
438  * @thread: the kthread on which the scheduler which run.
439  * @pending_list: the list of jobs which are currently in the job queue.
440  * @job_list_lock: lock to protect the pending_list.
441  * @hang_limit: once the hangs by a job crosses this limit then it is marked
442  *              guilty and it will no longer be considered for scheduling.
443  * @score: score to help loadbalancer pick a idle sched
444  * @_score: score used when the driver doesn't provide one
445  * @ready: marks if the underlying HW is ready to work
446  * @free_guilty: A hit to time out handler to free the guilty job.
447  * @dev: system &struct device
448  *
449  * One scheduler is implemented for each hardware ring.
450  */
451 struct drm_gpu_scheduler {
452 	const struct drm_sched_backend_ops	*ops;
453 	uint32_t			hw_submission_limit;
454 	long				timeout;
455 	const char			*name;
456 	struct drm_sched_rq		sched_rq[DRM_SCHED_PRIORITY_COUNT];
457 	wait_queue_head_t		wake_up_worker;
458 	wait_queue_head_t		job_scheduled;
459 	atomic_t			hw_rq_count;
460 	atomic64_t			job_id_count;
461 	struct workqueue_struct		*timeout_wq;
462 	struct delayed_work		work_tdr;
463 	struct task_struct		*thread;
464 	struct list_head		pending_list;
465 	spinlock_t			job_list_lock;
466 	int				hang_limit;
467 	atomic_t                        *score;
468 	atomic_t                        _score;
469 	bool				ready;
470 	bool				free_guilty;
471 	struct device			*dev;
472 };
473 
474 int drm_sched_init(struct drm_gpu_scheduler *sched,
475 		   const struct drm_sched_backend_ops *ops,
476 		   uint32_t hw_submission, unsigned hang_limit,
477 		   long timeout, struct workqueue_struct *timeout_wq,
478 		   atomic_t *score, const char *name, struct device *dev);
479 
480 void drm_sched_fini(struct drm_gpu_scheduler *sched);
481 int drm_sched_job_init(struct drm_sched_job *job,
482 		       struct drm_sched_entity *entity,
483 		       void *owner);
484 void drm_sched_job_arm(struct drm_sched_job *job);
485 int drm_sched_job_add_dependency(struct drm_sched_job *job,
486 				 struct dma_fence *fence);
487 int drm_sched_job_add_implicit_dependencies(struct drm_sched_job *job,
488 					    struct drm_gem_object *obj,
489 					    bool write);
490 
491 
492 void drm_sched_entity_modify_sched(struct drm_sched_entity *entity,
493 				    struct drm_gpu_scheduler **sched_list,
494                                    unsigned int num_sched_list);
495 
496 void drm_sched_job_cleanup(struct drm_sched_job *job);
497 void drm_sched_wakeup(struct drm_gpu_scheduler *sched);
498 void drm_sched_stop(struct drm_gpu_scheduler *sched, struct drm_sched_job *bad);
499 void drm_sched_start(struct drm_gpu_scheduler *sched, bool full_recovery);
500 void drm_sched_resubmit_jobs(struct drm_gpu_scheduler *sched);
501 void drm_sched_resubmit_jobs_ext(struct drm_gpu_scheduler *sched, int max);
502 void drm_sched_increase_karma(struct drm_sched_job *bad);
503 void drm_sched_reset_karma(struct drm_sched_job *bad);
504 void drm_sched_increase_karma_ext(struct drm_sched_job *bad, int type);
505 bool drm_sched_dependency_optimized(struct dma_fence* fence,
506 				    struct drm_sched_entity *entity);
507 void drm_sched_fault(struct drm_gpu_scheduler *sched);
508 void drm_sched_job_kickout(struct drm_sched_job *s_job);
509 
510 void drm_sched_rq_add_entity(struct drm_sched_rq *rq,
511 			     struct drm_sched_entity *entity);
512 void drm_sched_rq_remove_entity(struct drm_sched_rq *rq,
513 				struct drm_sched_entity *entity);
514 
515 int drm_sched_entity_init(struct drm_sched_entity *entity,
516 			  enum drm_sched_priority priority,
517 			  struct drm_gpu_scheduler **sched_list,
518 			  unsigned int num_sched_list,
519 			  atomic_t *guilty);
520 long drm_sched_entity_flush(struct drm_sched_entity *entity, long timeout);
521 void drm_sched_entity_fini(struct drm_sched_entity *entity);
522 void drm_sched_entity_destroy(struct drm_sched_entity *entity);
523 void drm_sched_entity_select_rq(struct drm_sched_entity *entity);
524 struct drm_sched_job *drm_sched_entity_pop_job(struct drm_sched_entity *entity);
525 void drm_sched_entity_push_job(struct drm_sched_job *sched_job);
526 void drm_sched_entity_set_priority(struct drm_sched_entity *entity,
527 				   enum drm_sched_priority priority);
528 bool drm_sched_entity_is_ready(struct drm_sched_entity *entity);
529 
530 struct drm_sched_fence *drm_sched_fence_alloc(
531 	struct drm_sched_entity *s_entity, void *owner);
532 void drm_sched_fence_init(struct drm_sched_fence *fence,
533 			  struct drm_sched_entity *entity);
534 void drm_sched_fence_free(struct drm_sched_fence *fence);
535 
536 void drm_sched_fence_scheduled(struct drm_sched_fence *fence);
537 void drm_sched_fence_finished(struct drm_sched_fence *fence);
538 
539 unsigned long drm_sched_suspend_timeout(struct drm_gpu_scheduler *sched);
540 void drm_sched_resume_timeout(struct drm_gpu_scheduler *sched,
541 		                unsigned long remaining);
542 struct drm_gpu_scheduler *
543 drm_sched_pick_best(struct drm_gpu_scheduler **sched_list,
544 		     unsigned int num_sched_list);
545 
546 #endif
547