xref: /linux/drivers/gpu/drm/panthor/panthor_sched.c (revision f4e0ff7e45c30f4665cfbbe2f0538e9c5789bebc)
1 // SPDX-License-Identifier: GPL-2.0 or MIT
2 /* Copyright 2023 Collabora ltd. */
3 
4 #include <drm/drm_drv.h>
5 #include <drm/drm_exec.h>
6 #include <drm/drm_gem_shmem_helper.h>
7 #include <drm/drm_managed.h>
8 #include <drm/gpu_scheduler.h>
9 #include <drm/panthor_drm.h>
10 
11 #include <linux/build_bug.h>
12 #include <linux/cleanup.h>
13 #include <linux/clk.h>
14 #include <linux/delay.h>
15 #include <linux/dma-mapping.h>
16 #include <linux/dma-resv.h>
17 #include <linux/firmware.h>
18 #include <linux/interrupt.h>
19 #include <linux/io.h>
20 #include <linux/iopoll.h>
21 #include <linux/iosys-map.h>
22 #include <linux/module.h>
23 #include <linux/platform_device.h>
24 #include <linux/pm_runtime.h>
25 
26 #include "panthor_devfreq.h"
27 #include "panthor_device.h"
28 #include "panthor_fw.h"
29 #include "panthor_gem.h"
30 #include "panthor_gpu.h"
31 #include "panthor_heap.h"
32 #include "panthor_mmu.h"
33 #include "panthor_regs.h"
34 #include "panthor_sched.h"
35 
36 /**
37  * DOC: Scheduler
38  *
39  * Mali CSF hardware adopts a firmware-assisted scheduling model, where
40  * the firmware takes care of scheduling aspects, to some extent.
41  *
42  * The scheduling happens at the scheduling group level, each group
43  * contains 1 to N queues (N is FW/hardware dependent, and exposed
44  * through the firmware interface). Each queue is assigned a command
45  * stream ring buffer, which serves as a way to get jobs submitted to
46  * the GPU, among other things.
47  *
48  * The firmware can schedule a maximum of M groups (M is FW/hardware
49  * dependent, and exposed through the firmware interface). Passed
50  * this maximum number of groups, the kernel must take care of
51  * rotating the groups passed to the firmware so every group gets
52  * a chance to have his queues scheduled for execution.
53  *
54  * The current implementation only supports with kernel-mode queues.
55  * In other terms, userspace doesn't have access to the ring-buffer.
56  * Instead, userspace passes indirect command stream buffers that are
57  * called from the queue ring-buffer by the kernel using a pre-defined
58  * sequence of command stream instructions to ensure the userspace driver
59  * always gets consistent results (cache maintenance,
60  * synchronization, ...).
61  *
62  * We rely on the drm_gpu_scheduler framework to deal with job
63  * dependencies and submission. As any other driver dealing with a
64  * FW-scheduler, we use the 1:1 entity:scheduler mode, such that each
65  * entity has its own job scheduler. When a job is ready to be executed
66  * (all its dependencies are met), it is pushed to the appropriate
67  * queue ring-buffer, and the group is scheduled for execution if it
68  * wasn't already active.
69  *
70  * Kernel-side group scheduling is timeslice-based. When we have less
71  * groups than there are slots, the periodic tick is disabled and we
72  * just let the FW schedule the active groups. When there are more
73  * groups than slots, we let each group a chance to execute stuff for
74  * a given amount of time, and then re-evaluate and pick new groups
75  * to schedule. The group selection algorithm is based on
76  * priority+round-robin.
77  *
78  * Even though user-mode queues is out of the scope right now, the
79  * current design takes them into account by avoiding any guess on the
80  * group/queue state that would be based on information we wouldn't have
81  * if userspace was in charge of the ring-buffer. That's also one of the
82  * reason we don't do 'cooperative' scheduling (encoding FW group slot
83  * reservation as dma_fence that would be returned from the
84  * drm_gpu_scheduler::prepare_job() hook, and treating group rotation as
85  * a queue of waiters, ordered by job submission order). This approach
86  * would work for kernel-mode queues, but would make user-mode queues a
87  * lot more complicated to retrofit.
88  */
89 
90 #define JOB_TIMEOUT_MS				5000
91 
92 #define MAX_CSG_PRIO				0xf
93 
94 #define NUM_INSTRS_PER_CACHE_LINE		(64 / sizeof(u64))
95 #define MAX_INSTRS_PER_JOB			24
96 
97 struct panthor_group;
98 
99 /**
100  * struct panthor_csg_slot - Command stream group slot
101  *
102  * This represents a FW slot for a scheduling group.
103  */
104 struct panthor_csg_slot {
105 	/** @group: Scheduling group bound to this slot. */
106 	struct panthor_group *group;
107 
108 	/** @priority: Group priority. */
109 	u8 priority;
110 
111 	/**
112 	 * @idle: True if the group bound to this slot is idle.
113 	 *
114 	 * A group is idle when it has nothing waiting for execution on
115 	 * all its queues, or when queues are blocked waiting for something
116 	 * to happen (synchronization object).
117 	 */
118 	bool idle;
119 };
120 
121 /**
122  * enum panthor_csg_priority - Group priority
123  */
124 enum panthor_csg_priority {
125 	/** @PANTHOR_CSG_PRIORITY_LOW: Low priority group. */
126 	PANTHOR_CSG_PRIORITY_LOW = 0,
127 
128 	/** @PANTHOR_CSG_PRIORITY_MEDIUM: Medium priority group. */
129 	PANTHOR_CSG_PRIORITY_MEDIUM,
130 
131 	/** @PANTHOR_CSG_PRIORITY_HIGH: High priority group. */
132 	PANTHOR_CSG_PRIORITY_HIGH,
133 
134 	/**
135 	 * @PANTHOR_CSG_PRIORITY_RT: Real-time priority group.
136 	 *
137 	 * Real-time priority allows one to preempt scheduling of other
138 	 * non-real-time groups. When such a group becomes executable,
139 	 * it will evict the group with the lowest non-rt priority if
140 	 * there's no free group slot available.
141 	 */
142 	PANTHOR_CSG_PRIORITY_RT,
143 
144 	/** @PANTHOR_CSG_PRIORITY_COUNT: Number of priority levels. */
145 	PANTHOR_CSG_PRIORITY_COUNT,
146 };
147 
148 /**
149  * struct panthor_scheduler - Object used to manage the scheduler
150  */
151 struct panthor_scheduler {
152 	/** @ptdev: Device. */
153 	struct panthor_device *ptdev;
154 
155 	/**
156 	 * @wq: Workqueue used by our internal scheduler logic and
157 	 * drm_gpu_scheduler.
158 	 *
159 	 * Used for the scheduler tick, group update or other kind of FW
160 	 * event processing that can't be handled in the threaded interrupt
161 	 * path. Also passed to the drm_gpu_scheduler instances embedded
162 	 * in panthor_queue.
163 	 */
164 	struct workqueue_struct *wq;
165 
166 	/**
167 	 * @heap_alloc_wq: Workqueue used to schedule tiler_oom works.
168 	 *
169 	 * We have a queue dedicated to heap chunk allocation works to avoid
170 	 * blocking the rest of the scheduler if the allocation tries to
171 	 * reclaim memory.
172 	 */
173 	struct workqueue_struct *heap_alloc_wq;
174 
175 	/** @tick_work: Work executed on a scheduling tick. */
176 	struct delayed_work tick_work;
177 
178 	/**
179 	 * @sync_upd_work: Work used to process synchronization object updates.
180 	 *
181 	 * We use this work to unblock queues/groups that were waiting on a
182 	 * synchronization object.
183 	 */
184 	struct work_struct sync_upd_work;
185 
186 	/**
187 	 * @fw_events_work: Work used to process FW events outside the interrupt path.
188 	 *
189 	 * Even if the interrupt is threaded, we need any event processing
190 	 * that require taking the panthor_scheduler::lock to be processed
191 	 * outside the interrupt path so we don't block the tick logic when
192 	 * it calls panthor_fw_{csg,wait}_wait_acks(). Since most of the
193 	 * event processing requires taking this lock, we just delegate all
194 	 * FW event processing to the scheduler workqueue.
195 	 */
196 	struct work_struct fw_events_work;
197 
198 	/**
199 	 * @fw_events: Bitmask encoding pending FW events.
200 	 */
201 	atomic_t fw_events;
202 
203 	/**
204 	 * @resched_target: When the next tick should occur.
205 	 *
206 	 * Expressed in jiffies.
207 	 */
208 	u64 resched_target;
209 
210 	/**
211 	 * @last_tick: When the last tick occurred.
212 	 *
213 	 * Expressed in jiffies.
214 	 */
215 	u64 last_tick;
216 
217 	/** @tick_period: Tick period in jiffies. */
218 	u64 tick_period;
219 
220 	/**
221 	 * @lock: Lock protecting access to all the scheduler fields.
222 	 *
223 	 * Should be taken in the tick work, the irq handler, and anywhere the @groups
224 	 * fields are touched.
225 	 */
226 	struct mutex lock;
227 
228 	/** @groups: Various lists used to classify groups. */
229 	struct {
230 		/**
231 		 * @runnable: Runnable group lists.
232 		 *
233 		 * When a group has queues that want to execute something,
234 		 * its panthor_group::run_node should be inserted here.
235 		 *
236 		 * One list per-priority.
237 		 */
238 		struct list_head runnable[PANTHOR_CSG_PRIORITY_COUNT];
239 
240 		/**
241 		 * @idle: Idle group lists.
242 		 *
243 		 * When all queues of a group are idle (either because they
244 		 * have nothing to execute, or because they are blocked), the
245 		 * panthor_group::run_node field should be inserted here.
246 		 *
247 		 * One list per-priority.
248 		 */
249 		struct list_head idle[PANTHOR_CSG_PRIORITY_COUNT];
250 
251 		/**
252 		 * @waiting: List of groups whose queues are blocked on a
253 		 * synchronization object.
254 		 *
255 		 * Insert panthor_group::wait_node here when a group is waiting
256 		 * for synchronization objects to be signaled.
257 		 *
258 		 * This list is evaluated in the @sync_upd_work work.
259 		 */
260 		struct list_head waiting;
261 	} groups;
262 
263 	/**
264 	 * @csg_slots: FW command stream group slots.
265 	 */
266 	struct panthor_csg_slot csg_slots[MAX_CSGS];
267 
268 	/** @csg_slot_count: Number of command stream group slots exposed by the FW. */
269 	u32 csg_slot_count;
270 
271 	/** @cs_slot_count: Number of command stream slot per group slot exposed by the FW. */
272 	u32 cs_slot_count;
273 
274 	/** @as_slot_count: Number of address space slots supported by the MMU. */
275 	u32 as_slot_count;
276 
277 	/** @used_csg_slot_count: Number of command stream group slot currently used. */
278 	u32 used_csg_slot_count;
279 
280 	/** @sb_slot_count: Number of scoreboard slots. */
281 	u32 sb_slot_count;
282 
283 	/**
284 	 * @might_have_idle_groups: True if an active group might have become idle.
285 	 *
286 	 * This will force a tick, so other runnable groups can be scheduled if one
287 	 * or more active groups became idle.
288 	 */
289 	bool might_have_idle_groups;
290 
291 	/** @pm: Power management related fields. */
292 	struct {
293 		/** @has_ref: True if the scheduler owns a runtime PM reference. */
294 		bool has_ref;
295 	} pm;
296 
297 	/** @reset: Reset related fields. */
298 	struct {
299 		/** @lock: Lock protecting the other reset fields. */
300 		struct mutex lock;
301 
302 		/**
303 		 * @in_progress: True if a reset is in progress.
304 		 *
305 		 * Set to true in panthor_sched_pre_reset() and back to false in
306 		 * panthor_sched_post_reset().
307 		 */
308 		atomic_t in_progress;
309 
310 		/**
311 		 * @stopped_groups: List containing all groups that were stopped
312 		 * before a reset.
313 		 *
314 		 * Insert panthor_group::run_node in the pre_reset path.
315 		 */
316 		struct list_head stopped_groups;
317 	} reset;
318 };
319 
320 /**
321  * struct panthor_syncobj_32b - 32-bit FW synchronization object
322  */
323 struct panthor_syncobj_32b {
324 	/** @seqno: Sequence number. */
325 	u32 seqno;
326 
327 	/**
328 	 * @status: Status.
329 	 *
330 	 * Not zero on failure.
331 	 */
332 	u32 status;
333 };
334 
335 /**
336  * struct panthor_syncobj_64b - 64-bit FW synchronization object
337  */
338 struct panthor_syncobj_64b {
339 	/** @seqno: Sequence number. */
340 	u64 seqno;
341 
342 	/**
343 	 * @status: Status.
344 	 *
345 	 * Not zero on failure.
346 	 */
347 	u32 status;
348 
349 	/** @pad: MBZ. */
350 	u32 pad;
351 };
352 
353 /**
354  * struct panthor_queue - Execution queue
355  */
356 struct panthor_queue {
357 	/** @scheduler: DRM scheduler used for this queue. */
358 	struct drm_gpu_scheduler scheduler;
359 
360 	/** @entity: DRM scheduling entity used for this queue. */
361 	struct drm_sched_entity entity;
362 
363 	/**
364 	 * @remaining_time: Time remaining before the job timeout expires.
365 	 *
366 	 * The job timeout is suspended when the queue is not scheduled by the
367 	 * FW. Every time we suspend the timer, we need to save the remaining
368 	 * time so we can restore it later on.
369 	 */
370 	unsigned long remaining_time;
371 
372 	/** @timeout_suspended: True if the job timeout was suspended. */
373 	bool timeout_suspended;
374 
375 	/**
376 	 * @doorbell_id: Doorbell assigned to this queue.
377 	 *
378 	 * Right now, all groups share the same doorbell, and the doorbell ID
379 	 * is assigned to group_slot + 1 when the group is assigned a slot. But
380 	 * we might decide to provide fine grained doorbell assignment at some
381 	 * point, so don't have to wake up all queues in a group every time one
382 	 * of them is updated.
383 	 */
384 	u8 doorbell_id;
385 
386 	/**
387 	 * @priority: Priority of the queue inside the group.
388 	 *
389 	 * Must be less than 16 (Only 4 bits available).
390 	 */
391 	u8 priority;
392 #define CSF_MAX_QUEUE_PRIO	GENMASK(3, 0)
393 
394 	/** @ringbuf: Command stream ring-buffer. */
395 	struct panthor_kernel_bo *ringbuf;
396 
397 	/** @iface: Firmware interface. */
398 	struct {
399 		/** @mem: FW memory allocated for this interface. */
400 		struct panthor_kernel_bo *mem;
401 
402 		/** @input: Input interface. */
403 		struct panthor_fw_ringbuf_input_iface *input;
404 
405 		/** @output: Output interface. */
406 		const struct panthor_fw_ringbuf_output_iface *output;
407 
408 		/** @input_fw_va: FW virtual address of the input interface buffer. */
409 		u32 input_fw_va;
410 
411 		/** @output_fw_va: FW virtual address of the output interface buffer. */
412 		u32 output_fw_va;
413 	} iface;
414 
415 	/**
416 	 * @syncwait: Stores information about the synchronization object this
417 	 * queue is waiting on.
418 	 */
419 	struct {
420 		/** @gpu_va: GPU address of the synchronization object. */
421 		u64 gpu_va;
422 
423 		/** @ref: Reference value to compare against. */
424 		u64 ref;
425 
426 		/** @gt: True if this is a greater-than test. */
427 		bool gt;
428 
429 		/** @sync64: True if this is a 64-bit sync object. */
430 		bool sync64;
431 
432 		/** @bo: Buffer object holding the synchronization object. */
433 		struct drm_gem_object *obj;
434 
435 		/** @offset: Offset of the synchronization object inside @bo. */
436 		u64 offset;
437 
438 		/**
439 		 * @kmap: Kernel mapping of the buffer object holding the
440 		 * synchronization object.
441 		 */
442 		void *kmap;
443 	} syncwait;
444 
445 	/** @fence_ctx: Fence context fields. */
446 	struct {
447 		/** @lock: Used to protect access to all fences allocated by this context. */
448 		spinlock_t lock;
449 
450 		/**
451 		 * @id: Fence context ID.
452 		 *
453 		 * Allocated with dma_fence_context_alloc().
454 		 */
455 		u64 id;
456 
457 		/** @seqno: Sequence number of the last initialized fence. */
458 		atomic64_t seqno;
459 
460 		/**
461 		 * @last_fence: Fence of the last submitted job.
462 		 *
463 		 * We return this fence when we get an empty command stream.
464 		 * This way, we are guaranteed that all earlier jobs have completed
465 		 * when drm_sched_job::s_fence::finished without having to feed
466 		 * the CS ring buffer with a dummy job that only signals the fence.
467 		 */
468 		struct dma_fence *last_fence;
469 
470 		/**
471 		 * @in_flight_jobs: List containing all in-flight jobs.
472 		 *
473 		 * Used to keep track and signal panthor_job::done_fence when the
474 		 * synchronization object attached to the queue is signaled.
475 		 */
476 		struct list_head in_flight_jobs;
477 	} fence_ctx;
478 
479 	/** @profiling: Job profiling data slots and access information. */
480 	struct {
481 		/** @slots: Kernel BO holding the slots. */
482 		struct panthor_kernel_bo *slots;
483 
484 		/** @slot_count: Number of jobs ringbuffer can hold at once. */
485 		u32 slot_count;
486 
487 		/** @seqno: Index of the next available profiling information slot. */
488 		u32 seqno;
489 	} profiling;
490 };
491 
492 /**
493  * enum panthor_group_state - Scheduling group state.
494  */
495 enum panthor_group_state {
496 	/** @PANTHOR_CS_GROUP_CREATED: Group was created, but not scheduled yet. */
497 	PANTHOR_CS_GROUP_CREATED,
498 
499 	/** @PANTHOR_CS_GROUP_ACTIVE: Group is currently scheduled. */
500 	PANTHOR_CS_GROUP_ACTIVE,
501 
502 	/**
503 	 * @PANTHOR_CS_GROUP_SUSPENDED: Group was scheduled at least once, but is
504 	 * inactive/suspended right now.
505 	 */
506 	PANTHOR_CS_GROUP_SUSPENDED,
507 
508 	/**
509 	 * @PANTHOR_CS_GROUP_TERMINATED: Group was terminated.
510 	 *
511 	 * Can no longer be scheduled. The only allowed action is a destruction.
512 	 */
513 	PANTHOR_CS_GROUP_TERMINATED,
514 
515 	/**
516 	 * @PANTHOR_CS_GROUP_UNKNOWN_STATE: Group is an unknown state.
517 	 *
518 	 * The FW returned an inconsistent state. The group is flagged unusable
519 	 * and can no longer be scheduled. The only allowed action is a
520 	 * destruction.
521 	 *
522 	 * When that happens, we also schedule a FW reset, to start from a fresh
523 	 * state.
524 	 */
525 	PANTHOR_CS_GROUP_UNKNOWN_STATE,
526 };
527 
528 /**
529  * struct panthor_group - Scheduling group object
530  */
531 struct panthor_group {
532 	/** @refcount: Reference count */
533 	struct kref refcount;
534 
535 	/** @ptdev: Device. */
536 	struct panthor_device *ptdev;
537 
538 	/** @vm: VM bound to the group. */
539 	struct panthor_vm *vm;
540 
541 	/** @compute_core_mask: Mask of shader cores that can be used for compute jobs. */
542 	u64 compute_core_mask;
543 
544 	/** @fragment_core_mask: Mask of shader cores that can be used for fragment jobs. */
545 	u64 fragment_core_mask;
546 
547 	/** @tiler_core_mask: Mask of tiler cores that can be used for tiler jobs. */
548 	u64 tiler_core_mask;
549 
550 	/** @max_compute_cores: Maximum number of shader cores used for compute jobs. */
551 	u8 max_compute_cores;
552 
553 	/** @max_fragment_cores: Maximum number of shader cores used for fragment jobs. */
554 	u8 max_fragment_cores;
555 
556 	/** @max_tiler_cores: Maximum number of tiler cores used for tiler jobs. */
557 	u8 max_tiler_cores;
558 
559 	/** @priority: Group priority (check panthor_csg_priority). */
560 	u8 priority;
561 
562 	/** @blocked_queues: Bitmask reflecting the blocked queues. */
563 	u32 blocked_queues;
564 
565 	/** @idle_queues: Bitmask reflecting the idle queues. */
566 	u32 idle_queues;
567 
568 	/** @fatal_lock: Lock used to protect access to fatal fields. */
569 	spinlock_t fatal_lock;
570 
571 	/** @fatal_queues: Bitmask reflecting the queues that hit a fatal exception. */
572 	u32 fatal_queues;
573 
574 	/** @tiler_oom: Mask of queues that have a tiler OOM event to process. */
575 	atomic_t tiler_oom;
576 
577 	/** @queue_count: Number of queues in this group. */
578 	u32 queue_count;
579 
580 	/** @queues: Queues owned by this group. */
581 	struct panthor_queue *queues[MAX_CS_PER_CSG];
582 
583 	/**
584 	 * @csg_id: ID of the FW group slot.
585 	 *
586 	 * -1 when the group is not scheduled/active.
587 	 */
588 	int csg_id;
589 
590 	/**
591 	 * @destroyed: True when the group has been destroyed.
592 	 *
593 	 * If a group is destroyed it becomes useless: no further jobs can be submitted
594 	 * to its queues. We simply wait for all references to be dropped so we can
595 	 * release the group object.
596 	 */
597 	bool destroyed;
598 
599 	/**
600 	 * @timedout: True when a timeout occurred on any of the queues owned by
601 	 * this group.
602 	 *
603 	 * Timeouts can be reported by drm_sched or by the FW. If a reset is required,
604 	 * and the group can't be suspended, this also leads to a timeout. In any case,
605 	 * any timeout situation is unrecoverable, and the group becomes useless. We
606 	 * simply wait for all references to be dropped so we can release the group
607 	 * object.
608 	 */
609 	bool timedout;
610 
611 	/**
612 	 * @innocent: True when the group becomes unusable because the group suspension
613 	 * failed during a reset.
614 	 *
615 	 * Sometimes the FW was put in a bad state by other groups, causing the group
616 	 * suspension happening in the reset path to fail. In that case, we consider the
617 	 * group innocent.
618 	 */
619 	bool innocent;
620 
621 	/**
622 	 * @syncobjs: Pool of per-queue synchronization objects.
623 	 *
624 	 * One sync object per queue. The position of the sync object is
625 	 * determined by the queue index.
626 	 */
627 	struct panthor_kernel_bo *syncobjs;
628 
629 	/** @fdinfo: Per-file info exposed through /proc/<process>/fdinfo */
630 	struct {
631 		/** @data: Total sampled values for jobs in queues from this group. */
632 		struct panthor_gpu_usage data;
633 
634 		/**
635 		 * @fdinfo.lock: Spinlock to govern concurrent access from drm file's fdinfo
636 		 * callback and job post-completion processing function
637 		 */
638 		spinlock_t lock;
639 
640 		/** @fdinfo.kbo_sizes: Aggregate size of private kernel BO's held by the group. */
641 		size_t kbo_sizes;
642 	} fdinfo;
643 
644 	/** @state: Group state. */
645 	enum panthor_group_state state;
646 
647 	/**
648 	 * @suspend_buf: Suspend buffer.
649 	 *
650 	 * Stores the state of the group and its queues when a group is suspended.
651 	 * Used at resume time to restore the group in its previous state.
652 	 *
653 	 * The size of the suspend buffer is exposed through the FW interface.
654 	 */
655 	struct panthor_kernel_bo *suspend_buf;
656 
657 	/**
658 	 * @protm_suspend_buf: Protection mode suspend buffer.
659 	 *
660 	 * Stores the state of the group and its queues when a group that's in
661 	 * protection mode is suspended.
662 	 *
663 	 * Used at resume time to restore the group in its previous state.
664 	 *
665 	 * The size of the protection mode suspend buffer is exposed through the
666 	 * FW interface.
667 	 */
668 	struct panthor_kernel_bo *protm_suspend_buf;
669 
670 	/** @sync_upd_work: Work used to check/signal job fences. */
671 	struct work_struct sync_upd_work;
672 
673 	/** @tiler_oom_work: Work used to process tiler OOM events happening on this group. */
674 	struct work_struct tiler_oom_work;
675 
676 	/** @term_work: Work used to finish the group termination procedure. */
677 	struct work_struct term_work;
678 
679 	/**
680 	 * @release_work: Work used to release group resources.
681 	 *
682 	 * We need to postpone the group release to avoid a deadlock when
683 	 * the last ref is released in the tick work.
684 	 */
685 	struct work_struct release_work;
686 
687 	/**
688 	 * @run_node: Node used to insert the group in the
689 	 * panthor_group::groups::{runnable,idle} and
690 	 * panthor_group::reset.stopped_groups lists.
691 	 */
692 	struct list_head run_node;
693 
694 	/**
695 	 * @wait_node: Node used to insert the group in the
696 	 * panthor_group::groups::waiting list.
697 	 */
698 	struct list_head wait_node;
699 };
700 
701 struct panthor_job_profiling_data {
702 	struct {
703 		u64 before;
704 		u64 after;
705 	} cycles;
706 
707 	struct {
708 		u64 before;
709 		u64 after;
710 	} time;
711 };
712 
713 /**
714  * group_queue_work() - Queue a group work
715  * @group: Group to queue the work for.
716  * @wname: Work name.
717  *
718  * Grabs a ref and queue a work item to the scheduler workqueue. If
719  * the work was already queued, we release the reference we grabbed.
720  *
721  * Work callbacks must release the reference we grabbed here.
722  */
723 #define group_queue_work(group, wname) \
724 	do { \
725 		group_get(group); \
726 		if (!queue_work((group)->ptdev->scheduler->wq, &(group)->wname ## _work)) \
727 			group_put(group); \
728 	} while (0)
729 
730 /**
731  * sched_queue_work() - Queue a scheduler work.
732  * @sched: Scheduler object.
733  * @wname: Work name.
734  *
735  * Conditionally queues a scheduler work if no reset is pending/in-progress.
736  */
737 #define sched_queue_work(sched, wname) \
738 	do { \
739 		if (!atomic_read(&(sched)->reset.in_progress) && \
740 		    !panthor_device_reset_is_pending((sched)->ptdev)) \
741 			queue_work((sched)->wq, &(sched)->wname ## _work); \
742 	} while (0)
743 
744 /**
745  * sched_queue_delayed_work() - Queue a scheduler delayed work.
746  * @sched: Scheduler object.
747  * @wname: Work name.
748  * @delay: Work delay in jiffies.
749  *
750  * Conditionally queues a scheduler delayed work if no reset is
751  * pending/in-progress.
752  */
753 #define sched_queue_delayed_work(sched, wname, delay) \
754 	do { \
755 		if (!atomic_read(&sched->reset.in_progress) && \
756 		    !panthor_device_reset_is_pending((sched)->ptdev)) \
757 			mod_delayed_work((sched)->wq, &(sched)->wname ## _work, delay); \
758 	} while (0)
759 
760 /*
761  * We currently set the maximum of groups per file to an arbitrary low value.
762  * But this can be updated if we need more.
763  */
764 #define MAX_GROUPS_PER_POOL 128
765 
766 /**
767  * struct panthor_group_pool - Group pool
768  *
769  * Each file get assigned a group pool.
770  */
771 struct panthor_group_pool {
772 	/** @xa: Xarray used to manage group handles. */
773 	struct xarray xa;
774 };
775 
776 /**
777  * struct panthor_job - Used to manage GPU job
778  */
779 struct panthor_job {
780 	/** @base: Inherit from drm_sched_job. */
781 	struct drm_sched_job base;
782 
783 	/** @refcount: Reference count. */
784 	struct kref refcount;
785 
786 	/** @group: Group of the queue this job will be pushed to. */
787 	struct panthor_group *group;
788 
789 	/** @queue_idx: Index of the queue inside @group. */
790 	u32 queue_idx;
791 
792 	/** @call_info: Information about the userspace command stream call. */
793 	struct {
794 		/** @start: GPU address of the userspace command stream. */
795 		u64 start;
796 
797 		/** @size: Size of the userspace command stream. */
798 		u32 size;
799 
800 		/**
801 		 * @latest_flush: Flush ID at the time the userspace command
802 		 * stream was built.
803 		 *
804 		 * Needed for the flush reduction mechanism.
805 		 */
806 		u32 latest_flush;
807 	} call_info;
808 
809 	/** @ringbuf: Position of this job is in the ring buffer. */
810 	struct {
811 		/** @start: Start offset. */
812 		u64 start;
813 
814 		/** @end: End offset. */
815 		u64 end;
816 	} ringbuf;
817 
818 	/**
819 	 * @node: Used to insert the job in the panthor_queue::fence_ctx::in_flight_jobs
820 	 * list.
821 	 */
822 	struct list_head node;
823 
824 	/** @done_fence: Fence signaled when the job is finished or cancelled. */
825 	struct dma_fence *done_fence;
826 
827 	/** @profiling: Job profiling information. */
828 	struct {
829 		/** @mask: Current device job profiling enablement bitmask. */
830 		u32 mask;
831 
832 		/** @slot: Job index in the profiling slots BO. */
833 		u32 slot;
834 	} profiling;
835 };
836 
837 static void
838 panthor_queue_put_syncwait_obj(struct panthor_queue *queue)
839 {
840 	if (queue->syncwait.kmap) {
841 		struct iosys_map map = IOSYS_MAP_INIT_VADDR(queue->syncwait.kmap);
842 
843 		drm_gem_vunmap(queue->syncwait.obj, &map);
844 		queue->syncwait.kmap = NULL;
845 	}
846 
847 	drm_gem_object_put(queue->syncwait.obj);
848 	queue->syncwait.obj = NULL;
849 }
850 
851 static void *
852 panthor_queue_get_syncwait_obj(struct panthor_group *group, struct panthor_queue *queue)
853 {
854 	struct panthor_device *ptdev = group->ptdev;
855 	struct panthor_gem_object *bo;
856 	struct iosys_map map;
857 	int ret;
858 
859 	if (queue->syncwait.kmap)
860 		return queue->syncwait.kmap + queue->syncwait.offset;
861 
862 	bo = panthor_vm_get_bo_for_va(group->vm,
863 				      queue->syncwait.gpu_va,
864 				      &queue->syncwait.offset);
865 	if (drm_WARN_ON(&ptdev->base, IS_ERR_OR_NULL(bo)))
866 		goto err_put_syncwait_obj;
867 
868 	queue->syncwait.obj = &bo->base.base;
869 	ret = drm_gem_vmap(queue->syncwait.obj, &map);
870 	if (drm_WARN_ON(&ptdev->base, ret))
871 		goto err_put_syncwait_obj;
872 
873 	queue->syncwait.kmap = map.vaddr;
874 	if (drm_WARN_ON(&ptdev->base, !queue->syncwait.kmap))
875 		goto err_put_syncwait_obj;
876 
877 	return queue->syncwait.kmap + queue->syncwait.offset;
878 
879 err_put_syncwait_obj:
880 	panthor_queue_put_syncwait_obj(queue);
881 	return NULL;
882 }
883 
884 static void group_free_queue(struct panthor_group *group, struct panthor_queue *queue)
885 {
886 	if (IS_ERR_OR_NULL(queue))
887 		return;
888 
889 	drm_sched_entity_destroy(&queue->entity);
890 
891 	if (queue->scheduler.ops)
892 		drm_sched_fini(&queue->scheduler);
893 
894 	panthor_queue_put_syncwait_obj(queue);
895 
896 	panthor_kernel_bo_destroy(queue->ringbuf);
897 	panthor_kernel_bo_destroy(queue->iface.mem);
898 	panthor_kernel_bo_destroy(queue->profiling.slots);
899 
900 	/* Release the last_fence we were holding, if any. */
901 	dma_fence_put(queue->fence_ctx.last_fence);
902 
903 	kfree(queue);
904 }
905 
906 static void group_release_work(struct work_struct *work)
907 {
908 	struct panthor_group *group = container_of(work,
909 						   struct panthor_group,
910 						   release_work);
911 	u32 i;
912 
913 	for (i = 0; i < group->queue_count; i++)
914 		group_free_queue(group, group->queues[i]);
915 
916 	panthor_kernel_bo_destroy(group->suspend_buf);
917 	panthor_kernel_bo_destroy(group->protm_suspend_buf);
918 	panthor_kernel_bo_destroy(group->syncobjs);
919 
920 	panthor_vm_put(group->vm);
921 	kfree(group);
922 }
923 
924 static void group_release(struct kref *kref)
925 {
926 	struct panthor_group *group = container_of(kref,
927 						   struct panthor_group,
928 						   refcount);
929 	struct panthor_device *ptdev = group->ptdev;
930 
931 	drm_WARN_ON(&ptdev->base, group->csg_id >= 0);
932 	drm_WARN_ON(&ptdev->base, !list_empty(&group->run_node));
933 	drm_WARN_ON(&ptdev->base, !list_empty(&group->wait_node));
934 
935 	queue_work(panthor_cleanup_wq, &group->release_work);
936 }
937 
938 static void group_put(struct panthor_group *group)
939 {
940 	if (group)
941 		kref_put(&group->refcount, group_release);
942 }
943 
944 static struct panthor_group *
945 group_get(struct panthor_group *group)
946 {
947 	if (group)
948 		kref_get(&group->refcount);
949 
950 	return group;
951 }
952 
953 /**
954  * group_bind_locked() - Bind a group to a group slot
955  * @group: Group.
956  * @csg_id: Slot.
957  *
958  * Return: 0 on success, a negative error code otherwise.
959  */
960 static int
961 group_bind_locked(struct panthor_group *group, u32 csg_id)
962 {
963 	struct panthor_device *ptdev = group->ptdev;
964 	struct panthor_csg_slot *csg_slot;
965 	int ret;
966 
967 	lockdep_assert_held(&ptdev->scheduler->lock);
968 
969 	if (drm_WARN_ON(&ptdev->base, group->csg_id != -1 || csg_id >= MAX_CSGS ||
970 			ptdev->scheduler->csg_slots[csg_id].group))
971 		return -EINVAL;
972 
973 	ret = panthor_vm_active(group->vm);
974 	if (ret)
975 		return ret;
976 
977 	csg_slot = &ptdev->scheduler->csg_slots[csg_id];
978 	group_get(group);
979 	group->csg_id = csg_id;
980 
981 	/* Dummy doorbell allocation: doorbell is assigned to the group and
982 	 * all queues use the same doorbell.
983 	 *
984 	 * TODO: Implement LRU-based doorbell assignment, so the most often
985 	 * updated queues get their own doorbell, thus avoiding useless checks
986 	 * on queues belonging to the same group that are rarely updated.
987 	 */
988 	for (u32 i = 0; i < group->queue_count; i++)
989 		group->queues[i]->doorbell_id = csg_id + 1;
990 
991 	csg_slot->group = group;
992 
993 	return 0;
994 }
995 
996 /**
997  * group_unbind_locked() - Unbind a group from a slot.
998  * @group: Group to unbind.
999  *
1000  * Return: 0 on success, a negative error code otherwise.
1001  */
1002 static int
1003 group_unbind_locked(struct panthor_group *group)
1004 {
1005 	struct panthor_device *ptdev = group->ptdev;
1006 	struct panthor_csg_slot *slot;
1007 
1008 	lockdep_assert_held(&ptdev->scheduler->lock);
1009 
1010 	if (drm_WARN_ON(&ptdev->base, group->csg_id < 0 || group->csg_id >= MAX_CSGS))
1011 		return -EINVAL;
1012 
1013 	if (drm_WARN_ON(&ptdev->base, group->state == PANTHOR_CS_GROUP_ACTIVE))
1014 		return -EINVAL;
1015 
1016 	slot = &ptdev->scheduler->csg_slots[group->csg_id];
1017 	panthor_vm_idle(group->vm);
1018 	group->csg_id = -1;
1019 
1020 	/* Tiler OOM events will be re-issued next time the group is scheduled. */
1021 	atomic_set(&group->tiler_oom, 0);
1022 	cancel_work(&group->tiler_oom_work);
1023 
1024 	for (u32 i = 0; i < group->queue_count; i++)
1025 		group->queues[i]->doorbell_id = -1;
1026 
1027 	slot->group = NULL;
1028 
1029 	group_put(group);
1030 	return 0;
1031 }
1032 
1033 /**
1034  * cs_slot_prog_locked() - Program a queue slot
1035  * @ptdev: Device.
1036  * @csg_id: Group slot ID.
1037  * @cs_id: Queue slot ID.
1038  *
1039  * Program a queue slot with the queue information so things can start being
1040  * executed on this queue.
1041  *
1042  * The group slot must have a group bound to it already (group_bind_locked()).
1043  */
1044 static void
1045 cs_slot_prog_locked(struct panthor_device *ptdev, u32 csg_id, u32 cs_id)
1046 {
1047 	struct panthor_queue *queue = ptdev->scheduler->csg_slots[csg_id].group->queues[cs_id];
1048 	struct panthor_fw_cs_iface *cs_iface = panthor_fw_get_cs_iface(ptdev, csg_id, cs_id);
1049 
1050 	lockdep_assert_held(&ptdev->scheduler->lock);
1051 
1052 	queue->iface.input->extract = queue->iface.output->extract;
1053 	drm_WARN_ON(&ptdev->base, queue->iface.input->insert < queue->iface.input->extract);
1054 
1055 	cs_iface->input->ringbuf_base = panthor_kernel_bo_gpuva(queue->ringbuf);
1056 	cs_iface->input->ringbuf_size = panthor_kernel_bo_size(queue->ringbuf);
1057 	cs_iface->input->ringbuf_input = queue->iface.input_fw_va;
1058 	cs_iface->input->ringbuf_output = queue->iface.output_fw_va;
1059 	cs_iface->input->config = CS_CONFIG_PRIORITY(queue->priority) |
1060 				  CS_CONFIG_DOORBELL(queue->doorbell_id);
1061 	cs_iface->input->ack_irq_mask = ~0;
1062 	panthor_fw_update_reqs(cs_iface, req,
1063 			       CS_IDLE_SYNC_WAIT |
1064 			       CS_IDLE_EMPTY |
1065 			       CS_STATE_START |
1066 			       CS_EXTRACT_EVENT,
1067 			       CS_IDLE_SYNC_WAIT |
1068 			       CS_IDLE_EMPTY |
1069 			       CS_STATE_MASK |
1070 			       CS_EXTRACT_EVENT);
1071 	if (queue->iface.input->insert != queue->iface.input->extract && queue->timeout_suspended) {
1072 		drm_sched_resume_timeout(&queue->scheduler, queue->remaining_time);
1073 		queue->timeout_suspended = false;
1074 	}
1075 }
1076 
1077 /**
1078  * cs_slot_reset_locked() - Reset a queue slot
1079  * @ptdev: Device.
1080  * @csg_id: Group slot.
1081  * @cs_id: Queue slot.
1082  *
1083  * Change the queue slot state to STOP and suspend the queue timeout if
1084  * the queue is not blocked.
1085  *
1086  * The group slot must have a group bound to it (group_bind_locked()).
1087  */
1088 static int
1089 cs_slot_reset_locked(struct panthor_device *ptdev, u32 csg_id, u32 cs_id)
1090 {
1091 	struct panthor_fw_cs_iface *cs_iface = panthor_fw_get_cs_iface(ptdev, csg_id, cs_id);
1092 	struct panthor_group *group = ptdev->scheduler->csg_slots[csg_id].group;
1093 	struct panthor_queue *queue = group->queues[cs_id];
1094 
1095 	lockdep_assert_held(&ptdev->scheduler->lock);
1096 
1097 	panthor_fw_update_reqs(cs_iface, req,
1098 			       CS_STATE_STOP,
1099 			       CS_STATE_MASK);
1100 
1101 	/* If the queue is blocked, we want to keep the timeout running, so
1102 	 * we can detect unbounded waits and kill the group when that happens.
1103 	 */
1104 	if (!(group->blocked_queues & BIT(cs_id)) && !queue->timeout_suspended) {
1105 		queue->remaining_time = drm_sched_suspend_timeout(&queue->scheduler);
1106 		queue->timeout_suspended = true;
1107 		WARN_ON(queue->remaining_time > msecs_to_jiffies(JOB_TIMEOUT_MS));
1108 	}
1109 
1110 	return 0;
1111 }
1112 
1113 /**
1114  * csg_slot_sync_priority_locked() - Synchronize the group slot priority
1115  * @ptdev: Device.
1116  * @csg_id: Group slot ID.
1117  *
1118  * Group slot priority update happens asynchronously. When we receive a
1119  * %CSG_ENDPOINT_CONFIG, we know the update is effective, and can
1120  * reflect it to our panthor_csg_slot object.
1121  */
1122 static void
1123 csg_slot_sync_priority_locked(struct panthor_device *ptdev, u32 csg_id)
1124 {
1125 	struct panthor_csg_slot *csg_slot = &ptdev->scheduler->csg_slots[csg_id];
1126 	struct panthor_fw_csg_iface *csg_iface;
1127 
1128 	lockdep_assert_held(&ptdev->scheduler->lock);
1129 
1130 	csg_iface = panthor_fw_get_csg_iface(ptdev, csg_id);
1131 	csg_slot->priority = (csg_iface->input->endpoint_req & CSG_EP_REQ_PRIORITY_MASK) >> 28;
1132 }
1133 
1134 /**
1135  * cs_slot_sync_queue_state_locked() - Synchronize the queue slot priority
1136  * @ptdev: Device.
1137  * @csg_id: Group slot.
1138  * @cs_id: Queue slot.
1139  *
1140  * Queue state is updated on group suspend or STATUS_UPDATE event.
1141  */
1142 static void
1143 cs_slot_sync_queue_state_locked(struct panthor_device *ptdev, u32 csg_id, u32 cs_id)
1144 {
1145 	struct panthor_group *group = ptdev->scheduler->csg_slots[csg_id].group;
1146 	struct panthor_queue *queue = group->queues[cs_id];
1147 	struct panthor_fw_cs_iface *cs_iface =
1148 		panthor_fw_get_cs_iface(group->ptdev, csg_id, cs_id);
1149 
1150 	u32 status_wait_cond;
1151 
1152 	switch (cs_iface->output->status_blocked_reason) {
1153 	case CS_STATUS_BLOCKED_REASON_UNBLOCKED:
1154 		if (queue->iface.input->insert == queue->iface.output->extract &&
1155 		    cs_iface->output->status_scoreboards == 0)
1156 			group->idle_queues |= BIT(cs_id);
1157 		break;
1158 
1159 	case CS_STATUS_BLOCKED_REASON_SYNC_WAIT:
1160 		if (list_empty(&group->wait_node)) {
1161 			list_move_tail(&group->wait_node,
1162 				       &group->ptdev->scheduler->groups.waiting);
1163 		}
1164 
1165 		/* The queue is only blocked if there's no deferred operation
1166 		 * pending, which can be checked through the scoreboard status.
1167 		 */
1168 		if (!cs_iface->output->status_scoreboards)
1169 			group->blocked_queues |= BIT(cs_id);
1170 
1171 		queue->syncwait.gpu_va = cs_iface->output->status_wait_sync_ptr;
1172 		queue->syncwait.ref = cs_iface->output->status_wait_sync_value;
1173 		status_wait_cond = cs_iface->output->status_wait & CS_STATUS_WAIT_SYNC_COND_MASK;
1174 		queue->syncwait.gt = status_wait_cond == CS_STATUS_WAIT_SYNC_COND_GT;
1175 		if (cs_iface->output->status_wait & CS_STATUS_WAIT_SYNC_64B) {
1176 			u64 sync_val_hi = cs_iface->output->status_wait_sync_value_hi;
1177 
1178 			queue->syncwait.sync64 = true;
1179 			queue->syncwait.ref |= sync_val_hi << 32;
1180 		} else {
1181 			queue->syncwait.sync64 = false;
1182 		}
1183 		break;
1184 
1185 	default:
1186 		/* Other reasons are not blocking. Consider the queue as runnable
1187 		 * in those cases.
1188 		 */
1189 		break;
1190 	}
1191 }
1192 
1193 static void
1194 csg_slot_sync_queues_state_locked(struct panthor_device *ptdev, u32 csg_id)
1195 {
1196 	struct panthor_csg_slot *csg_slot = &ptdev->scheduler->csg_slots[csg_id];
1197 	struct panthor_group *group = csg_slot->group;
1198 	u32 i;
1199 
1200 	lockdep_assert_held(&ptdev->scheduler->lock);
1201 
1202 	group->idle_queues = 0;
1203 	group->blocked_queues = 0;
1204 
1205 	for (i = 0; i < group->queue_count; i++) {
1206 		if (group->queues[i])
1207 			cs_slot_sync_queue_state_locked(ptdev, csg_id, i);
1208 	}
1209 }
1210 
1211 static void
1212 csg_slot_sync_state_locked(struct panthor_device *ptdev, u32 csg_id)
1213 {
1214 	struct panthor_csg_slot *csg_slot = &ptdev->scheduler->csg_slots[csg_id];
1215 	struct panthor_fw_csg_iface *csg_iface;
1216 	struct panthor_group *group;
1217 	enum panthor_group_state new_state, old_state;
1218 	u32 csg_state;
1219 
1220 	lockdep_assert_held(&ptdev->scheduler->lock);
1221 
1222 	csg_iface = panthor_fw_get_csg_iface(ptdev, csg_id);
1223 	group = csg_slot->group;
1224 
1225 	if (!group)
1226 		return;
1227 
1228 	old_state = group->state;
1229 	csg_state = csg_iface->output->ack & CSG_STATE_MASK;
1230 	switch (csg_state) {
1231 	case CSG_STATE_START:
1232 	case CSG_STATE_RESUME:
1233 		new_state = PANTHOR_CS_GROUP_ACTIVE;
1234 		break;
1235 	case CSG_STATE_TERMINATE:
1236 		new_state = PANTHOR_CS_GROUP_TERMINATED;
1237 		break;
1238 	case CSG_STATE_SUSPEND:
1239 		new_state = PANTHOR_CS_GROUP_SUSPENDED;
1240 		break;
1241 	default:
1242 		/* The unknown state might be caused by a FW state corruption,
1243 		 * which means the group metadata can't be trusted anymore, and
1244 		 * the SUSPEND operation might propagate the corruption to the
1245 		 * suspend buffers. Flag the group state as unknown to make
1246 		 * sure it's unusable after that point.
1247 		 */
1248 		drm_err(&ptdev->base, "Invalid state on CSG %d (state=%d)",
1249 			csg_id, csg_state);
1250 		new_state = PANTHOR_CS_GROUP_UNKNOWN_STATE;
1251 		break;
1252 	}
1253 
1254 	if (old_state == new_state)
1255 		return;
1256 
1257 	/* The unknown state might be caused by a FW issue, reset the FW to
1258 	 * take a fresh start.
1259 	 */
1260 	if (new_state == PANTHOR_CS_GROUP_UNKNOWN_STATE)
1261 		panthor_device_schedule_reset(ptdev);
1262 
1263 	if (new_state == PANTHOR_CS_GROUP_SUSPENDED)
1264 		csg_slot_sync_queues_state_locked(ptdev, csg_id);
1265 
1266 	if (old_state == PANTHOR_CS_GROUP_ACTIVE) {
1267 		u32 i;
1268 
1269 		/* Reset the queue slots so we start from a clean
1270 		 * state when starting/resuming a new group on this
1271 		 * CSG slot. No wait needed here, and no ringbell
1272 		 * either, since the CS slot will only be re-used
1273 		 * on the next CSG start operation.
1274 		 */
1275 		for (i = 0; i < group->queue_count; i++) {
1276 			if (group->queues[i])
1277 				cs_slot_reset_locked(ptdev, csg_id, i);
1278 		}
1279 	}
1280 
1281 	group->state = new_state;
1282 }
1283 
1284 static int
1285 csg_slot_prog_locked(struct panthor_device *ptdev, u32 csg_id, u32 priority)
1286 {
1287 	struct panthor_fw_csg_iface *csg_iface;
1288 	struct panthor_csg_slot *csg_slot;
1289 	struct panthor_group *group;
1290 	u32 queue_mask = 0, i;
1291 
1292 	lockdep_assert_held(&ptdev->scheduler->lock);
1293 
1294 	if (priority > MAX_CSG_PRIO)
1295 		return -EINVAL;
1296 
1297 	if (drm_WARN_ON(&ptdev->base, csg_id >= MAX_CSGS))
1298 		return -EINVAL;
1299 
1300 	csg_slot = &ptdev->scheduler->csg_slots[csg_id];
1301 	group = csg_slot->group;
1302 	if (!group || group->state == PANTHOR_CS_GROUP_ACTIVE)
1303 		return 0;
1304 
1305 	csg_iface = panthor_fw_get_csg_iface(group->ptdev, csg_id);
1306 
1307 	for (i = 0; i < group->queue_count; i++) {
1308 		if (group->queues[i]) {
1309 			cs_slot_prog_locked(ptdev, csg_id, i);
1310 			queue_mask |= BIT(i);
1311 		}
1312 	}
1313 
1314 	csg_iface->input->allow_compute = group->compute_core_mask;
1315 	csg_iface->input->allow_fragment = group->fragment_core_mask;
1316 	csg_iface->input->allow_other = group->tiler_core_mask;
1317 	csg_iface->input->endpoint_req = CSG_EP_REQ_COMPUTE(group->max_compute_cores) |
1318 					 CSG_EP_REQ_FRAGMENT(group->max_fragment_cores) |
1319 					 CSG_EP_REQ_TILER(group->max_tiler_cores) |
1320 					 CSG_EP_REQ_PRIORITY(priority);
1321 	csg_iface->input->config = panthor_vm_as(group->vm);
1322 
1323 	if (group->suspend_buf)
1324 		csg_iface->input->suspend_buf = panthor_kernel_bo_gpuva(group->suspend_buf);
1325 	else
1326 		csg_iface->input->suspend_buf = 0;
1327 
1328 	if (group->protm_suspend_buf) {
1329 		csg_iface->input->protm_suspend_buf =
1330 			panthor_kernel_bo_gpuva(group->protm_suspend_buf);
1331 	} else {
1332 		csg_iface->input->protm_suspend_buf = 0;
1333 	}
1334 
1335 	csg_iface->input->ack_irq_mask = ~0;
1336 	panthor_fw_toggle_reqs(csg_iface, doorbell_req, doorbell_ack, queue_mask);
1337 	return 0;
1338 }
1339 
1340 static void
1341 cs_slot_process_fatal_event_locked(struct panthor_device *ptdev,
1342 				   u32 csg_id, u32 cs_id)
1343 {
1344 	struct panthor_scheduler *sched = ptdev->scheduler;
1345 	struct panthor_csg_slot *csg_slot = &sched->csg_slots[csg_id];
1346 	struct panthor_group *group = csg_slot->group;
1347 	struct panthor_fw_cs_iface *cs_iface;
1348 	u32 fatal;
1349 	u64 info;
1350 
1351 	lockdep_assert_held(&sched->lock);
1352 
1353 	cs_iface = panthor_fw_get_cs_iface(ptdev, csg_id, cs_id);
1354 	fatal = cs_iface->output->fatal;
1355 	info = cs_iface->output->fatal_info;
1356 
1357 	if (group)
1358 		group->fatal_queues |= BIT(cs_id);
1359 
1360 	if (CS_EXCEPTION_TYPE(fatal) == DRM_PANTHOR_EXCEPTION_CS_UNRECOVERABLE) {
1361 		/* If this exception is unrecoverable, queue a reset, and make
1362 		 * sure we stop scheduling groups until the reset has happened.
1363 		 */
1364 		panthor_device_schedule_reset(ptdev);
1365 		cancel_delayed_work(&sched->tick_work);
1366 	} else {
1367 		sched_queue_delayed_work(sched, tick, 0);
1368 	}
1369 
1370 	drm_warn(&ptdev->base,
1371 		 "CSG slot %d CS slot: %d\n"
1372 		 "CS_FATAL.EXCEPTION_TYPE: 0x%x (%s)\n"
1373 		 "CS_FATAL.EXCEPTION_DATA: 0x%x\n"
1374 		 "CS_FATAL_INFO.EXCEPTION_DATA: 0x%llx\n",
1375 		 csg_id, cs_id,
1376 		 (unsigned int)CS_EXCEPTION_TYPE(fatal),
1377 		 panthor_exception_name(ptdev, CS_EXCEPTION_TYPE(fatal)),
1378 		 (unsigned int)CS_EXCEPTION_DATA(fatal),
1379 		 info);
1380 }
1381 
1382 static void
1383 cs_slot_process_fault_event_locked(struct panthor_device *ptdev,
1384 				   u32 csg_id, u32 cs_id)
1385 {
1386 	struct panthor_scheduler *sched = ptdev->scheduler;
1387 	struct panthor_csg_slot *csg_slot = &sched->csg_slots[csg_id];
1388 	struct panthor_group *group = csg_slot->group;
1389 	struct panthor_queue *queue = group && cs_id < group->queue_count ?
1390 				      group->queues[cs_id] : NULL;
1391 	struct panthor_fw_cs_iface *cs_iface;
1392 	u32 fault;
1393 	u64 info;
1394 
1395 	lockdep_assert_held(&sched->lock);
1396 
1397 	cs_iface = panthor_fw_get_cs_iface(ptdev, csg_id, cs_id);
1398 	fault = cs_iface->output->fault;
1399 	info = cs_iface->output->fault_info;
1400 
1401 	if (queue && CS_EXCEPTION_TYPE(fault) == DRM_PANTHOR_EXCEPTION_CS_INHERIT_FAULT) {
1402 		u64 cs_extract = queue->iface.output->extract;
1403 		struct panthor_job *job;
1404 
1405 		spin_lock(&queue->fence_ctx.lock);
1406 		list_for_each_entry(job, &queue->fence_ctx.in_flight_jobs, node) {
1407 			if (cs_extract >= job->ringbuf.end)
1408 				continue;
1409 
1410 			if (cs_extract < job->ringbuf.start)
1411 				break;
1412 
1413 			dma_fence_set_error(job->done_fence, -EINVAL);
1414 		}
1415 		spin_unlock(&queue->fence_ctx.lock);
1416 	}
1417 
1418 	drm_warn(&ptdev->base,
1419 		 "CSG slot %d CS slot: %d\n"
1420 		 "CS_FAULT.EXCEPTION_TYPE: 0x%x (%s)\n"
1421 		 "CS_FAULT.EXCEPTION_DATA: 0x%x\n"
1422 		 "CS_FAULT_INFO.EXCEPTION_DATA: 0x%llx\n",
1423 		 csg_id, cs_id,
1424 		 (unsigned int)CS_EXCEPTION_TYPE(fault),
1425 		 panthor_exception_name(ptdev, CS_EXCEPTION_TYPE(fault)),
1426 		 (unsigned int)CS_EXCEPTION_DATA(fault),
1427 		 info);
1428 }
1429 
1430 static int group_process_tiler_oom(struct panthor_group *group, u32 cs_id)
1431 {
1432 	struct panthor_device *ptdev = group->ptdev;
1433 	struct panthor_scheduler *sched = ptdev->scheduler;
1434 	u32 renderpasses_in_flight, pending_frag_count;
1435 	struct panthor_heap_pool *heaps = NULL;
1436 	u64 heap_address, new_chunk_va = 0;
1437 	u32 vt_start, vt_end, frag_end;
1438 	int ret, csg_id;
1439 
1440 	mutex_lock(&sched->lock);
1441 	csg_id = group->csg_id;
1442 	if (csg_id >= 0) {
1443 		struct panthor_fw_cs_iface *cs_iface;
1444 
1445 		cs_iface = panthor_fw_get_cs_iface(ptdev, csg_id, cs_id);
1446 		heaps = panthor_vm_get_heap_pool(group->vm, false);
1447 		heap_address = cs_iface->output->heap_address;
1448 		vt_start = cs_iface->output->heap_vt_start;
1449 		vt_end = cs_iface->output->heap_vt_end;
1450 		frag_end = cs_iface->output->heap_frag_end;
1451 		renderpasses_in_flight = vt_start - frag_end;
1452 		pending_frag_count = vt_end - frag_end;
1453 	}
1454 	mutex_unlock(&sched->lock);
1455 
1456 	/* The group got scheduled out, we stop here. We will get a new tiler OOM event
1457 	 * when it's scheduled again.
1458 	 */
1459 	if (unlikely(csg_id < 0))
1460 		return 0;
1461 
1462 	if (IS_ERR(heaps) || frag_end > vt_end || vt_end >= vt_start) {
1463 		ret = -EINVAL;
1464 	} else {
1465 		/* We do the allocation without holding the scheduler lock to avoid
1466 		 * blocking the scheduling.
1467 		 */
1468 		ret = panthor_heap_grow(heaps, heap_address,
1469 					renderpasses_in_flight,
1470 					pending_frag_count, &new_chunk_va);
1471 	}
1472 
1473 	/* If the heap context doesn't have memory for us, we want to let the
1474 	 * FW try to reclaim memory by waiting for fragment jobs to land or by
1475 	 * executing the tiler OOM exception handler, which is supposed to
1476 	 * implement incremental rendering.
1477 	 */
1478 	if (ret && ret != -ENOMEM) {
1479 		drm_warn(&ptdev->base, "Failed to extend the tiler heap\n");
1480 		group->fatal_queues |= BIT(cs_id);
1481 		sched_queue_delayed_work(sched, tick, 0);
1482 		goto out_put_heap_pool;
1483 	}
1484 
1485 	mutex_lock(&sched->lock);
1486 	csg_id = group->csg_id;
1487 	if (csg_id >= 0) {
1488 		struct panthor_fw_csg_iface *csg_iface;
1489 		struct panthor_fw_cs_iface *cs_iface;
1490 
1491 		csg_iface = panthor_fw_get_csg_iface(ptdev, csg_id);
1492 		cs_iface = panthor_fw_get_cs_iface(ptdev, csg_id, cs_id);
1493 
1494 		cs_iface->input->heap_start = new_chunk_va;
1495 		cs_iface->input->heap_end = new_chunk_va;
1496 		panthor_fw_update_reqs(cs_iface, req, cs_iface->output->ack, CS_TILER_OOM);
1497 		panthor_fw_toggle_reqs(csg_iface, doorbell_req, doorbell_ack, BIT(cs_id));
1498 		panthor_fw_ring_csg_doorbells(ptdev, BIT(csg_id));
1499 	}
1500 	mutex_unlock(&sched->lock);
1501 
1502 	/* We allocated a chunck, but couldn't link it to the heap
1503 	 * context because the group was scheduled out while we were
1504 	 * allocating memory. We need to return this chunk to the heap.
1505 	 */
1506 	if (unlikely(csg_id < 0 && new_chunk_va))
1507 		panthor_heap_return_chunk(heaps, heap_address, new_chunk_va);
1508 
1509 	ret = 0;
1510 
1511 out_put_heap_pool:
1512 	panthor_heap_pool_put(heaps);
1513 	return ret;
1514 }
1515 
1516 static void group_tiler_oom_work(struct work_struct *work)
1517 {
1518 	struct panthor_group *group =
1519 		container_of(work, struct panthor_group, tiler_oom_work);
1520 	u32 tiler_oom = atomic_xchg(&group->tiler_oom, 0);
1521 
1522 	while (tiler_oom) {
1523 		u32 cs_id = ffs(tiler_oom) - 1;
1524 
1525 		group_process_tiler_oom(group, cs_id);
1526 		tiler_oom &= ~BIT(cs_id);
1527 	}
1528 
1529 	group_put(group);
1530 }
1531 
1532 static void
1533 cs_slot_process_tiler_oom_event_locked(struct panthor_device *ptdev,
1534 				       u32 csg_id, u32 cs_id)
1535 {
1536 	struct panthor_scheduler *sched = ptdev->scheduler;
1537 	struct panthor_csg_slot *csg_slot = &sched->csg_slots[csg_id];
1538 	struct panthor_group *group = csg_slot->group;
1539 
1540 	lockdep_assert_held(&sched->lock);
1541 
1542 	if (drm_WARN_ON(&ptdev->base, !group))
1543 		return;
1544 
1545 	atomic_or(BIT(cs_id), &group->tiler_oom);
1546 
1547 	/* We don't use group_queue_work() here because we want to queue the
1548 	 * work item to the heap_alloc_wq.
1549 	 */
1550 	group_get(group);
1551 	if (!queue_work(sched->heap_alloc_wq, &group->tiler_oom_work))
1552 		group_put(group);
1553 }
1554 
1555 static bool cs_slot_process_irq_locked(struct panthor_device *ptdev,
1556 				       u32 csg_id, u32 cs_id)
1557 {
1558 	struct panthor_fw_cs_iface *cs_iface;
1559 	u32 req, ack, events;
1560 
1561 	lockdep_assert_held(&ptdev->scheduler->lock);
1562 
1563 	cs_iface = panthor_fw_get_cs_iface(ptdev, csg_id, cs_id);
1564 	req = cs_iface->input->req;
1565 	ack = cs_iface->output->ack;
1566 	events = (req ^ ack) & CS_EVT_MASK;
1567 
1568 	if (events & CS_FATAL)
1569 		cs_slot_process_fatal_event_locked(ptdev, csg_id, cs_id);
1570 
1571 	if (events & CS_FAULT)
1572 		cs_slot_process_fault_event_locked(ptdev, csg_id, cs_id);
1573 
1574 	if (events & CS_TILER_OOM)
1575 		cs_slot_process_tiler_oom_event_locked(ptdev, csg_id, cs_id);
1576 
1577 	/* We don't acknowledge the TILER_OOM event since its handling is
1578 	 * deferred to a separate work.
1579 	 */
1580 	panthor_fw_update_reqs(cs_iface, req, ack, CS_FATAL | CS_FAULT);
1581 
1582 	return (events & (CS_FAULT | CS_TILER_OOM)) != 0;
1583 }
1584 
1585 static void csg_slot_sync_idle_state_locked(struct panthor_device *ptdev, u32 csg_id)
1586 {
1587 	struct panthor_csg_slot *csg_slot = &ptdev->scheduler->csg_slots[csg_id];
1588 	struct panthor_fw_csg_iface *csg_iface;
1589 
1590 	lockdep_assert_held(&ptdev->scheduler->lock);
1591 
1592 	csg_iface = panthor_fw_get_csg_iface(ptdev, csg_id);
1593 	csg_slot->idle = csg_iface->output->status_state & CSG_STATUS_STATE_IS_IDLE;
1594 }
1595 
1596 static void csg_slot_process_idle_event_locked(struct panthor_device *ptdev, u32 csg_id)
1597 {
1598 	struct panthor_scheduler *sched = ptdev->scheduler;
1599 
1600 	lockdep_assert_held(&sched->lock);
1601 
1602 	sched->might_have_idle_groups = true;
1603 
1604 	/* Schedule a tick so we can evict idle groups and schedule non-idle
1605 	 * ones. This will also update runtime PM and devfreq busy/idle states,
1606 	 * so the device can lower its frequency or get suspended.
1607 	 */
1608 	sched_queue_delayed_work(sched, tick, 0);
1609 }
1610 
1611 static void csg_slot_sync_update_locked(struct panthor_device *ptdev,
1612 					u32 csg_id)
1613 {
1614 	struct panthor_csg_slot *csg_slot = &ptdev->scheduler->csg_slots[csg_id];
1615 	struct panthor_group *group = csg_slot->group;
1616 
1617 	lockdep_assert_held(&ptdev->scheduler->lock);
1618 
1619 	if (group)
1620 		group_queue_work(group, sync_upd);
1621 
1622 	sched_queue_work(ptdev->scheduler, sync_upd);
1623 }
1624 
1625 static void
1626 csg_slot_process_progress_timer_event_locked(struct panthor_device *ptdev, u32 csg_id)
1627 {
1628 	struct panthor_scheduler *sched = ptdev->scheduler;
1629 	struct panthor_csg_slot *csg_slot = &sched->csg_slots[csg_id];
1630 	struct panthor_group *group = csg_slot->group;
1631 
1632 	lockdep_assert_held(&sched->lock);
1633 
1634 	drm_warn(&ptdev->base, "CSG slot %d progress timeout\n", csg_id);
1635 
1636 	group = csg_slot->group;
1637 	if (!drm_WARN_ON(&ptdev->base, !group))
1638 		group->timedout = true;
1639 
1640 	sched_queue_delayed_work(sched, tick, 0);
1641 }
1642 
1643 static void sched_process_csg_irq_locked(struct panthor_device *ptdev, u32 csg_id)
1644 {
1645 	u32 req, ack, cs_irq_req, cs_irq_ack, cs_irqs, csg_events;
1646 	struct panthor_fw_csg_iface *csg_iface;
1647 	u32 ring_cs_db_mask = 0;
1648 
1649 	lockdep_assert_held(&ptdev->scheduler->lock);
1650 
1651 	if (drm_WARN_ON(&ptdev->base, csg_id >= ptdev->scheduler->csg_slot_count))
1652 		return;
1653 
1654 	csg_iface = panthor_fw_get_csg_iface(ptdev, csg_id);
1655 	req = READ_ONCE(csg_iface->input->req);
1656 	ack = READ_ONCE(csg_iface->output->ack);
1657 	cs_irq_req = READ_ONCE(csg_iface->output->cs_irq_req);
1658 	cs_irq_ack = READ_ONCE(csg_iface->input->cs_irq_ack);
1659 	csg_events = (req ^ ack) & CSG_EVT_MASK;
1660 
1661 	/* There may not be any pending CSG/CS interrupts to process */
1662 	if (req == ack && cs_irq_req == cs_irq_ack)
1663 		return;
1664 
1665 	/* Immediately set IRQ_ACK bits to be same as the IRQ_REQ bits before
1666 	 * examining the CS_ACK & CS_REQ bits. This would ensure that Host
1667 	 * doesn't miss an interrupt for the CS in the race scenario where
1668 	 * whilst Host is servicing an interrupt for the CS, firmware sends
1669 	 * another interrupt for that CS.
1670 	 */
1671 	csg_iface->input->cs_irq_ack = cs_irq_req;
1672 
1673 	panthor_fw_update_reqs(csg_iface, req, ack,
1674 			       CSG_SYNC_UPDATE |
1675 			       CSG_IDLE |
1676 			       CSG_PROGRESS_TIMER_EVENT);
1677 
1678 	if (csg_events & CSG_IDLE)
1679 		csg_slot_process_idle_event_locked(ptdev, csg_id);
1680 
1681 	if (csg_events & CSG_PROGRESS_TIMER_EVENT)
1682 		csg_slot_process_progress_timer_event_locked(ptdev, csg_id);
1683 
1684 	cs_irqs = cs_irq_req ^ cs_irq_ack;
1685 	while (cs_irqs) {
1686 		u32 cs_id = ffs(cs_irqs) - 1;
1687 
1688 		if (cs_slot_process_irq_locked(ptdev, csg_id, cs_id))
1689 			ring_cs_db_mask |= BIT(cs_id);
1690 
1691 		cs_irqs &= ~BIT(cs_id);
1692 	}
1693 
1694 	if (csg_events & CSG_SYNC_UPDATE)
1695 		csg_slot_sync_update_locked(ptdev, csg_id);
1696 
1697 	if (ring_cs_db_mask)
1698 		panthor_fw_toggle_reqs(csg_iface, doorbell_req, doorbell_ack, ring_cs_db_mask);
1699 
1700 	panthor_fw_ring_csg_doorbells(ptdev, BIT(csg_id));
1701 }
1702 
1703 static void sched_process_idle_event_locked(struct panthor_device *ptdev)
1704 {
1705 	struct panthor_fw_global_iface *glb_iface = panthor_fw_get_glb_iface(ptdev);
1706 
1707 	lockdep_assert_held(&ptdev->scheduler->lock);
1708 
1709 	/* Acknowledge the idle event and schedule a tick. */
1710 	panthor_fw_update_reqs(glb_iface, req, glb_iface->output->ack, GLB_IDLE);
1711 	sched_queue_delayed_work(ptdev->scheduler, tick, 0);
1712 }
1713 
1714 /**
1715  * sched_process_global_irq_locked() - Process the scheduling part of a global IRQ
1716  * @ptdev: Device.
1717  */
1718 static void sched_process_global_irq_locked(struct panthor_device *ptdev)
1719 {
1720 	struct panthor_fw_global_iface *glb_iface = panthor_fw_get_glb_iface(ptdev);
1721 	u32 req, ack, evts;
1722 
1723 	lockdep_assert_held(&ptdev->scheduler->lock);
1724 
1725 	req = READ_ONCE(glb_iface->input->req);
1726 	ack = READ_ONCE(glb_iface->output->ack);
1727 	evts = (req ^ ack) & GLB_EVT_MASK;
1728 
1729 	if (evts & GLB_IDLE)
1730 		sched_process_idle_event_locked(ptdev);
1731 }
1732 
1733 static void process_fw_events_work(struct work_struct *work)
1734 {
1735 	struct panthor_scheduler *sched = container_of(work, struct panthor_scheduler,
1736 						      fw_events_work);
1737 	u32 events = atomic_xchg(&sched->fw_events, 0);
1738 	struct panthor_device *ptdev = sched->ptdev;
1739 
1740 	mutex_lock(&sched->lock);
1741 
1742 	if (events & JOB_INT_GLOBAL_IF) {
1743 		sched_process_global_irq_locked(ptdev);
1744 		events &= ~JOB_INT_GLOBAL_IF;
1745 	}
1746 
1747 	while (events) {
1748 		u32 csg_id = ffs(events) - 1;
1749 
1750 		sched_process_csg_irq_locked(ptdev, csg_id);
1751 		events &= ~BIT(csg_id);
1752 	}
1753 
1754 	mutex_unlock(&sched->lock);
1755 }
1756 
1757 /**
1758  * panthor_sched_report_fw_events() - Report FW events to the scheduler.
1759  */
1760 void panthor_sched_report_fw_events(struct panthor_device *ptdev, u32 events)
1761 {
1762 	if (!ptdev->scheduler)
1763 		return;
1764 
1765 	atomic_or(events, &ptdev->scheduler->fw_events);
1766 	sched_queue_work(ptdev->scheduler, fw_events);
1767 }
1768 
1769 static const char *fence_get_driver_name(struct dma_fence *fence)
1770 {
1771 	return "panthor";
1772 }
1773 
1774 static const char *queue_fence_get_timeline_name(struct dma_fence *fence)
1775 {
1776 	return "queue-fence";
1777 }
1778 
1779 static const struct dma_fence_ops panthor_queue_fence_ops = {
1780 	.get_driver_name = fence_get_driver_name,
1781 	.get_timeline_name = queue_fence_get_timeline_name,
1782 };
1783 
1784 struct panthor_csg_slots_upd_ctx {
1785 	u32 update_mask;
1786 	u32 timedout_mask;
1787 	struct {
1788 		u32 value;
1789 		u32 mask;
1790 	} requests[MAX_CSGS];
1791 };
1792 
1793 static void csgs_upd_ctx_init(struct panthor_csg_slots_upd_ctx *ctx)
1794 {
1795 	memset(ctx, 0, sizeof(*ctx));
1796 }
1797 
1798 static void csgs_upd_ctx_queue_reqs(struct panthor_device *ptdev,
1799 				    struct panthor_csg_slots_upd_ctx *ctx,
1800 				    u32 csg_id, u32 value, u32 mask)
1801 {
1802 	if (drm_WARN_ON(&ptdev->base, !mask) ||
1803 	    drm_WARN_ON(&ptdev->base, csg_id >= ptdev->scheduler->csg_slot_count))
1804 		return;
1805 
1806 	ctx->requests[csg_id].value = (ctx->requests[csg_id].value & ~mask) | (value & mask);
1807 	ctx->requests[csg_id].mask |= mask;
1808 	ctx->update_mask |= BIT(csg_id);
1809 }
1810 
1811 static int csgs_upd_ctx_apply_locked(struct panthor_device *ptdev,
1812 				     struct panthor_csg_slots_upd_ctx *ctx)
1813 {
1814 	struct panthor_scheduler *sched = ptdev->scheduler;
1815 	u32 update_slots = ctx->update_mask;
1816 
1817 	lockdep_assert_held(&sched->lock);
1818 
1819 	if (!ctx->update_mask)
1820 		return 0;
1821 
1822 	while (update_slots) {
1823 		struct panthor_fw_csg_iface *csg_iface;
1824 		u32 csg_id = ffs(update_slots) - 1;
1825 
1826 		update_slots &= ~BIT(csg_id);
1827 		csg_iface = panthor_fw_get_csg_iface(ptdev, csg_id);
1828 		panthor_fw_update_reqs(csg_iface, req,
1829 				       ctx->requests[csg_id].value,
1830 				       ctx->requests[csg_id].mask);
1831 	}
1832 
1833 	panthor_fw_ring_csg_doorbells(ptdev, ctx->update_mask);
1834 
1835 	update_slots = ctx->update_mask;
1836 	while (update_slots) {
1837 		struct panthor_fw_csg_iface *csg_iface;
1838 		u32 csg_id = ffs(update_slots) - 1;
1839 		u32 req_mask = ctx->requests[csg_id].mask, acked;
1840 		int ret;
1841 
1842 		update_slots &= ~BIT(csg_id);
1843 		csg_iface = panthor_fw_get_csg_iface(ptdev, csg_id);
1844 
1845 		ret = panthor_fw_csg_wait_acks(ptdev, csg_id, req_mask, &acked, 100);
1846 
1847 		if (acked & CSG_ENDPOINT_CONFIG)
1848 			csg_slot_sync_priority_locked(ptdev, csg_id);
1849 
1850 		if (acked & CSG_STATE_MASK)
1851 			csg_slot_sync_state_locked(ptdev, csg_id);
1852 
1853 		if (acked & CSG_STATUS_UPDATE) {
1854 			csg_slot_sync_queues_state_locked(ptdev, csg_id);
1855 			csg_slot_sync_idle_state_locked(ptdev, csg_id);
1856 		}
1857 
1858 		if (ret && acked != req_mask &&
1859 		    ((csg_iface->input->req ^ csg_iface->output->ack) & req_mask) != 0) {
1860 			drm_err(&ptdev->base, "CSG %d update request timedout", csg_id);
1861 			ctx->timedout_mask |= BIT(csg_id);
1862 		}
1863 	}
1864 
1865 	if (ctx->timedout_mask)
1866 		return -ETIMEDOUT;
1867 
1868 	return 0;
1869 }
1870 
1871 struct panthor_sched_tick_ctx {
1872 	struct list_head old_groups[PANTHOR_CSG_PRIORITY_COUNT];
1873 	struct list_head groups[PANTHOR_CSG_PRIORITY_COUNT];
1874 	u32 idle_group_count;
1875 	u32 group_count;
1876 	enum panthor_csg_priority min_priority;
1877 	struct panthor_vm *vms[MAX_CS_PER_CSG];
1878 	u32 as_count;
1879 	bool immediate_tick;
1880 	u32 csg_upd_failed_mask;
1881 };
1882 
1883 static bool
1884 tick_ctx_is_full(const struct panthor_scheduler *sched,
1885 		 const struct panthor_sched_tick_ctx *ctx)
1886 {
1887 	return ctx->group_count == sched->csg_slot_count;
1888 }
1889 
1890 static bool
1891 group_is_idle(struct panthor_group *group)
1892 {
1893 	struct panthor_device *ptdev = group->ptdev;
1894 	u32 inactive_queues;
1895 
1896 	if (group->csg_id >= 0)
1897 		return ptdev->scheduler->csg_slots[group->csg_id].idle;
1898 
1899 	inactive_queues = group->idle_queues | group->blocked_queues;
1900 	return hweight32(inactive_queues) == group->queue_count;
1901 }
1902 
1903 static bool
1904 group_can_run(struct panthor_group *group)
1905 {
1906 	return group->state != PANTHOR_CS_GROUP_TERMINATED &&
1907 	       group->state != PANTHOR_CS_GROUP_UNKNOWN_STATE &&
1908 	       !group->destroyed && group->fatal_queues == 0 &&
1909 	       !group->timedout;
1910 }
1911 
1912 static void
1913 tick_ctx_pick_groups_from_list(const struct panthor_scheduler *sched,
1914 			       struct panthor_sched_tick_ctx *ctx,
1915 			       struct list_head *queue,
1916 			       bool skip_idle_groups,
1917 			       bool owned_by_tick_ctx)
1918 {
1919 	struct panthor_group *group, *tmp;
1920 
1921 	if (tick_ctx_is_full(sched, ctx))
1922 		return;
1923 
1924 	list_for_each_entry_safe(group, tmp, queue, run_node) {
1925 		u32 i;
1926 
1927 		if (!group_can_run(group))
1928 			continue;
1929 
1930 		if (skip_idle_groups && group_is_idle(group))
1931 			continue;
1932 
1933 		for (i = 0; i < ctx->as_count; i++) {
1934 			if (ctx->vms[i] == group->vm)
1935 				break;
1936 		}
1937 
1938 		if (i == ctx->as_count && ctx->as_count == sched->as_slot_count)
1939 			continue;
1940 
1941 		if (!owned_by_tick_ctx)
1942 			group_get(group);
1943 
1944 		list_move_tail(&group->run_node, &ctx->groups[group->priority]);
1945 		ctx->group_count++;
1946 		if (group_is_idle(group))
1947 			ctx->idle_group_count++;
1948 
1949 		if (i == ctx->as_count)
1950 			ctx->vms[ctx->as_count++] = group->vm;
1951 
1952 		if (ctx->min_priority > group->priority)
1953 			ctx->min_priority = group->priority;
1954 
1955 		if (tick_ctx_is_full(sched, ctx))
1956 			return;
1957 	}
1958 }
1959 
1960 static void
1961 tick_ctx_insert_old_group(struct panthor_scheduler *sched,
1962 			  struct panthor_sched_tick_ctx *ctx,
1963 			  struct panthor_group *group,
1964 			  bool full_tick)
1965 {
1966 	struct panthor_csg_slot *csg_slot = &sched->csg_slots[group->csg_id];
1967 	struct panthor_group *other_group;
1968 
1969 	if (!full_tick) {
1970 		list_add_tail(&group->run_node, &ctx->old_groups[group->priority]);
1971 		return;
1972 	}
1973 
1974 	/* Rotate to make sure groups with lower CSG slot
1975 	 * priorities have a chance to get a higher CSG slot
1976 	 * priority next time they get picked. This priority
1977 	 * has an impact on resource request ordering, so it's
1978 	 * important to make sure we don't let one group starve
1979 	 * all other groups with the same group priority.
1980 	 */
1981 	list_for_each_entry(other_group,
1982 			    &ctx->old_groups[csg_slot->group->priority],
1983 			    run_node) {
1984 		struct panthor_csg_slot *other_csg_slot = &sched->csg_slots[other_group->csg_id];
1985 
1986 		if (other_csg_slot->priority > csg_slot->priority) {
1987 			list_add_tail(&csg_slot->group->run_node, &other_group->run_node);
1988 			return;
1989 		}
1990 	}
1991 
1992 	list_add_tail(&group->run_node, &ctx->old_groups[group->priority]);
1993 }
1994 
1995 static void
1996 tick_ctx_init(struct panthor_scheduler *sched,
1997 	      struct panthor_sched_tick_ctx *ctx,
1998 	      bool full_tick)
1999 {
2000 	struct panthor_device *ptdev = sched->ptdev;
2001 	struct panthor_csg_slots_upd_ctx upd_ctx;
2002 	int ret;
2003 	u32 i;
2004 
2005 	memset(ctx, 0, sizeof(*ctx));
2006 	csgs_upd_ctx_init(&upd_ctx);
2007 
2008 	ctx->min_priority = PANTHOR_CSG_PRIORITY_COUNT;
2009 	for (i = 0; i < ARRAY_SIZE(ctx->groups); i++) {
2010 		INIT_LIST_HEAD(&ctx->groups[i]);
2011 		INIT_LIST_HEAD(&ctx->old_groups[i]);
2012 	}
2013 
2014 	for (i = 0; i < sched->csg_slot_count; i++) {
2015 		struct panthor_csg_slot *csg_slot = &sched->csg_slots[i];
2016 		struct panthor_group *group = csg_slot->group;
2017 		struct panthor_fw_csg_iface *csg_iface;
2018 
2019 		if (!group)
2020 			continue;
2021 
2022 		csg_iface = panthor_fw_get_csg_iface(ptdev, i);
2023 		group_get(group);
2024 
2025 		/* If there was unhandled faults on the VM, force processing of
2026 		 * CSG IRQs, so we can flag the faulty queue.
2027 		 */
2028 		if (panthor_vm_has_unhandled_faults(group->vm)) {
2029 			sched_process_csg_irq_locked(ptdev, i);
2030 
2031 			/* No fatal fault reported, flag all queues as faulty. */
2032 			if (!group->fatal_queues)
2033 				group->fatal_queues |= GENMASK(group->queue_count - 1, 0);
2034 		}
2035 
2036 		tick_ctx_insert_old_group(sched, ctx, group, full_tick);
2037 		csgs_upd_ctx_queue_reqs(ptdev, &upd_ctx, i,
2038 					csg_iface->output->ack ^ CSG_STATUS_UPDATE,
2039 					CSG_STATUS_UPDATE);
2040 	}
2041 
2042 	ret = csgs_upd_ctx_apply_locked(ptdev, &upd_ctx);
2043 	if (ret) {
2044 		panthor_device_schedule_reset(ptdev);
2045 		ctx->csg_upd_failed_mask |= upd_ctx.timedout_mask;
2046 	}
2047 }
2048 
2049 static void
2050 group_term_post_processing(struct panthor_group *group)
2051 {
2052 	struct panthor_job *job, *tmp;
2053 	LIST_HEAD(faulty_jobs);
2054 	bool cookie;
2055 	u32 i = 0;
2056 
2057 	if (drm_WARN_ON(&group->ptdev->base, group_can_run(group)))
2058 		return;
2059 
2060 	cookie = dma_fence_begin_signalling();
2061 	for (i = 0; i < group->queue_count; i++) {
2062 		struct panthor_queue *queue = group->queues[i];
2063 		struct panthor_syncobj_64b *syncobj;
2064 		int err;
2065 
2066 		if (group->fatal_queues & BIT(i))
2067 			err = -EINVAL;
2068 		else if (group->timedout)
2069 			err = -ETIMEDOUT;
2070 		else
2071 			err = -ECANCELED;
2072 
2073 		if (!queue)
2074 			continue;
2075 
2076 		spin_lock(&queue->fence_ctx.lock);
2077 		list_for_each_entry_safe(job, tmp, &queue->fence_ctx.in_flight_jobs, node) {
2078 			list_move_tail(&job->node, &faulty_jobs);
2079 			dma_fence_set_error(job->done_fence, err);
2080 			dma_fence_signal_locked(job->done_fence);
2081 		}
2082 		spin_unlock(&queue->fence_ctx.lock);
2083 
2084 		/* Manually update the syncobj seqno to unblock waiters. */
2085 		syncobj = group->syncobjs->kmap + (i * sizeof(*syncobj));
2086 		syncobj->status = ~0;
2087 		syncobj->seqno = atomic64_read(&queue->fence_ctx.seqno);
2088 		sched_queue_work(group->ptdev->scheduler, sync_upd);
2089 	}
2090 	dma_fence_end_signalling(cookie);
2091 
2092 	list_for_each_entry_safe(job, tmp, &faulty_jobs, node) {
2093 		list_del_init(&job->node);
2094 		panthor_job_put(&job->base);
2095 	}
2096 }
2097 
2098 static void group_term_work(struct work_struct *work)
2099 {
2100 	struct panthor_group *group =
2101 		container_of(work, struct panthor_group, term_work);
2102 
2103 	group_term_post_processing(group);
2104 	group_put(group);
2105 }
2106 
2107 static void
2108 tick_ctx_cleanup(struct panthor_scheduler *sched,
2109 		 struct panthor_sched_tick_ctx *ctx)
2110 {
2111 	struct panthor_device *ptdev = sched->ptdev;
2112 	struct panthor_group *group, *tmp;
2113 	u32 i;
2114 
2115 	for (i = 0; i < ARRAY_SIZE(ctx->old_groups); i++) {
2116 		list_for_each_entry_safe(group, tmp, &ctx->old_groups[i], run_node) {
2117 			/* If everything went fine, we should only have groups
2118 			 * to be terminated in the old_groups lists.
2119 			 */
2120 			drm_WARN_ON(&ptdev->base, !ctx->csg_upd_failed_mask &&
2121 				    group_can_run(group));
2122 
2123 			if (!group_can_run(group)) {
2124 				list_del_init(&group->run_node);
2125 				list_del_init(&group->wait_node);
2126 				group_queue_work(group, term);
2127 			} else if (group->csg_id >= 0) {
2128 				list_del_init(&group->run_node);
2129 			} else {
2130 				list_move(&group->run_node,
2131 					  group_is_idle(group) ?
2132 					  &sched->groups.idle[group->priority] :
2133 					  &sched->groups.runnable[group->priority]);
2134 			}
2135 			group_put(group);
2136 		}
2137 	}
2138 
2139 	for (i = 0; i < ARRAY_SIZE(ctx->groups); i++) {
2140 		/* If everything went fine, the groups to schedule lists should
2141 		 * be empty.
2142 		 */
2143 		drm_WARN_ON(&ptdev->base,
2144 			    !ctx->csg_upd_failed_mask && !list_empty(&ctx->groups[i]));
2145 
2146 		list_for_each_entry_safe(group, tmp, &ctx->groups[i], run_node) {
2147 			if (group->csg_id >= 0) {
2148 				list_del_init(&group->run_node);
2149 			} else {
2150 				list_move(&group->run_node,
2151 					  group_is_idle(group) ?
2152 					  &sched->groups.idle[group->priority] :
2153 					  &sched->groups.runnable[group->priority]);
2154 			}
2155 			group_put(group);
2156 		}
2157 	}
2158 }
2159 
2160 static void
2161 tick_ctx_apply(struct panthor_scheduler *sched, struct panthor_sched_tick_ctx *ctx)
2162 {
2163 	struct panthor_group *group, *tmp;
2164 	struct panthor_device *ptdev = sched->ptdev;
2165 	struct panthor_csg_slot *csg_slot;
2166 	int prio, new_csg_prio = MAX_CSG_PRIO, i;
2167 	u32 free_csg_slots = 0;
2168 	struct panthor_csg_slots_upd_ctx upd_ctx;
2169 	int ret;
2170 
2171 	csgs_upd_ctx_init(&upd_ctx);
2172 
2173 	for (prio = PANTHOR_CSG_PRIORITY_COUNT - 1; prio >= 0; prio--) {
2174 		/* Suspend or terminate evicted groups. */
2175 		list_for_each_entry(group, &ctx->old_groups[prio], run_node) {
2176 			bool term = !group_can_run(group);
2177 			int csg_id = group->csg_id;
2178 
2179 			if (drm_WARN_ON(&ptdev->base, csg_id < 0))
2180 				continue;
2181 
2182 			csg_slot = &sched->csg_slots[csg_id];
2183 			csgs_upd_ctx_queue_reqs(ptdev, &upd_ctx, csg_id,
2184 						term ? CSG_STATE_TERMINATE : CSG_STATE_SUSPEND,
2185 						CSG_STATE_MASK);
2186 		}
2187 
2188 		/* Update priorities on already running groups. */
2189 		list_for_each_entry(group, &ctx->groups[prio], run_node) {
2190 			struct panthor_fw_csg_iface *csg_iface;
2191 			int csg_id = group->csg_id;
2192 
2193 			if (csg_id < 0) {
2194 				new_csg_prio--;
2195 				continue;
2196 			}
2197 
2198 			csg_slot = &sched->csg_slots[csg_id];
2199 			csg_iface = panthor_fw_get_csg_iface(ptdev, csg_id);
2200 			if (csg_slot->priority == new_csg_prio) {
2201 				new_csg_prio--;
2202 				continue;
2203 			}
2204 
2205 			panthor_fw_update_reqs(csg_iface, endpoint_req,
2206 					       CSG_EP_REQ_PRIORITY(new_csg_prio),
2207 					       CSG_EP_REQ_PRIORITY_MASK);
2208 			csgs_upd_ctx_queue_reqs(ptdev, &upd_ctx, csg_id,
2209 						csg_iface->output->ack ^ CSG_ENDPOINT_CONFIG,
2210 						CSG_ENDPOINT_CONFIG);
2211 			new_csg_prio--;
2212 		}
2213 	}
2214 
2215 	ret = csgs_upd_ctx_apply_locked(ptdev, &upd_ctx);
2216 	if (ret) {
2217 		panthor_device_schedule_reset(ptdev);
2218 		ctx->csg_upd_failed_mask |= upd_ctx.timedout_mask;
2219 		return;
2220 	}
2221 
2222 	/* Unbind evicted groups. */
2223 	for (prio = PANTHOR_CSG_PRIORITY_COUNT - 1; prio >= 0; prio--) {
2224 		list_for_each_entry(group, &ctx->old_groups[prio], run_node) {
2225 			/* This group is gone. Process interrupts to clear
2226 			 * any pending interrupts before we start the new
2227 			 * group.
2228 			 */
2229 			if (group->csg_id >= 0)
2230 				sched_process_csg_irq_locked(ptdev, group->csg_id);
2231 
2232 			group_unbind_locked(group);
2233 		}
2234 	}
2235 
2236 	for (i = 0; i < sched->csg_slot_count; i++) {
2237 		if (!sched->csg_slots[i].group)
2238 			free_csg_slots |= BIT(i);
2239 	}
2240 
2241 	csgs_upd_ctx_init(&upd_ctx);
2242 	new_csg_prio = MAX_CSG_PRIO;
2243 
2244 	/* Start new groups. */
2245 	for (prio = PANTHOR_CSG_PRIORITY_COUNT - 1; prio >= 0; prio--) {
2246 		list_for_each_entry(group, &ctx->groups[prio], run_node) {
2247 			int csg_id = group->csg_id;
2248 			struct panthor_fw_csg_iface *csg_iface;
2249 
2250 			if (csg_id >= 0) {
2251 				new_csg_prio--;
2252 				continue;
2253 			}
2254 
2255 			csg_id = ffs(free_csg_slots) - 1;
2256 			if (drm_WARN_ON(&ptdev->base, csg_id < 0))
2257 				break;
2258 
2259 			csg_iface = panthor_fw_get_csg_iface(ptdev, csg_id);
2260 			csg_slot = &sched->csg_slots[csg_id];
2261 			group_bind_locked(group, csg_id);
2262 			csg_slot_prog_locked(ptdev, csg_id, new_csg_prio--);
2263 			csgs_upd_ctx_queue_reqs(ptdev, &upd_ctx, csg_id,
2264 						group->state == PANTHOR_CS_GROUP_SUSPENDED ?
2265 						CSG_STATE_RESUME : CSG_STATE_START,
2266 						CSG_STATE_MASK);
2267 			csgs_upd_ctx_queue_reqs(ptdev, &upd_ctx, csg_id,
2268 						csg_iface->output->ack ^ CSG_ENDPOINT_CONFIG,
2269 						CSG_ENDPOINT_CONFIG);
2270 			free_csg_slots &= ~BIT(csg_id);
2271 		}
2272 	}
2273 
2274 	ret = csgs_upd_ctx_apply_locked(ptdev, &upd_ctx);
2275 	if (ret) {
2276 		panthor_device_schedule_reset(ptdev);
2277 		ctx->csg_upd_failed_mask |= upd_ctx.timedout_mask;
2278 		return;
2279 	}
2280 
2281 	for (prio = PANTHOR_CSG_PRIORITY_COUNT - 1; prio >= 0; prio--) {
2282 		list_for_each_entry_safe(group, tmp, &ctx->groups[prio], run_node) {
2283 			list_del_init(&group->run_node);
2284 
2285 			/* If the group has been destroyed while we were
2286 			 * scheduling, ask for an immediate tick to
2287 			 * re-evaluate as soon as possible and get rid of
2288 			 * this dangling group.
2289 			 */
2290 			if (group->destroyed)
2291 				ctx->immediate_tick = true;
2292 			group_put(group);
2293 		}
2294 
2295 		/* Return evicted groups to the idle or run queues. Groups
2296 		 * that can no longer be run (because they've been destroyed
2297 		 * or experienced an unrecoverable error) will be scheduled
2298 		 * for destruction in tick_ctx_cleanup().
2299 		 */
2300 		list_for_each_entry_safe(group, tmp, &ctx->old_groups[prio], run_node) {
2301 			if (!group_can_run(group))
2302 				continue;
2303 
2304 			if (group_is_idle(group))
2305 				list_move_tail(&group->run_node, &sched->groups.idle[prio]);
2306 			else
2307 				list_move_tail(&group->run_node, &sched->groups.runnable[prio]);
2308 			group_put(group);
2309 		}
2310 	}
2311 
2312 	sched->used_csg_slot_count = ctx->group_count;
2313 	sched->might_have_idle_groups = ctx->idle_group_count > 0;
2314 }
2315 
2316 static u64
2317 tick_ctx_update_resched_target(struct panthor_scheduler *sched,
2318 			       const struct panthor_sched_tick_ctx *ctx)
2319 {
2320 	/* We had space left, no need to reschedule until some external event happens. */
2321 	if (!tick_ctx_is_full(sched, ctx))
2322 		goto no_tick;
2323 
2324 	/* If idle groups were scheduled, no need to wake up until some external
2325 	 * event happens (group unblocked, new job submitted, ...).
2326 	 */
2327 	if (ctx->idle_group_count)
2328 		goto no_tick;
2329 
2330 	if (drm_WARN_ON(&sched->ptdev->base, ctx->min_priority >= PANTHOR_CSG_PRIORITY_COUNT))
2331 		goto no_tick;
2332 
2333 	/* If there are groups of the same priority waiting, we need to
2334 	 * keep the scheduler ticking, otherwise, we'll just wait for
2335 	 * new groups with higher priority to be queued.
2336 	 */
2337 	if (!list_empty(&sched->groups.runnable[ctx->min_priority])) {
2338 		u64 resched_target = sched->last_tick + sched->tick_period;
2339 
2340 		if (time_before64(sched->resched_target, sched->last_tick) ||
2341 		    time_before64(resched_target, sched->resched_target))
2342 			sched->resched_target = resched_target;
2343 
2344 		return sched->resched_target - sched->last_tick;
2345 	}
2346 
2347 no_tick:
2348 	sched->resched_target = U64_MAX;
2349 	return U64_MAX;
2350 }
2351 
2352 static void tick_work(struct work_struct *work)
2353 {
2354 	struct panthor_scheduler *sched = container_of(work, struct panthor_scheduler,
2355 						      tick_work.work);
2356 	struct panthor_device *ptdev = sched->ptdev;
2357 	struct panthor_sched_tick_ctx ctx;
2358 	u64 remaining_jiffies = 0, resched_delay;
2359 	u64 now = get_jiffies_64();
2360 	int prio, ret, cookie;
2361 
2362 	if (!drm_dev_enter(&ptdev->base, &cookie))
2363 		return;
2364 
2365 	ret = panthor_device_resume_and_get(ptdev);
2366 	if (drm_WARN_ON(&ptdev->base, ret))
2367 		goto out_dev_exit;
2368 
2369 	if (time_before64(now, sched->resched_target))
2370 		remaining_jiffies = sched->resched_target - now;
2371 
2372 	mutex_lock(&sched->lock);
2373 	if (panthor_device_reset_is_pending(sched->ptdev))
2374 		goto out_unlock;
2375 
2376 	tick_ctx_init(sched, &ctx, remaining_jiffies != 0);
2377 	if (ctx.csg_upd_failed_mask)
2378 		goto out_cleanup_ctx;
2379 
2380 	if (remaining_jiffies) {
2381 		/* Scheduling forced in the middle of a tick. Only RT groups
2382 		 * can preempt non-RT ones. Currently running RT groups can't be
2383 		 * preempted.
2384 		 */
2385 		for (prio = PANTHOR_CSG_PRIORITY_COUNT - 1;
2386 		     prio >= 0 && !tick_ctx_is_full(sched, &ctx);
2387 		     prio--) {
2388 			tick_ctx_pick_groups_from_list(sched, &ctx, &ctx.old_groups[prio],
2389 						       true, true);
2390 			if (prio == PANTHOR_CSG_PRIORITY_RT) {
2391 				tick_ctx_pick_groups_from_list(sched, &ctx,
2392 							       &sched->groups.runnable[prio],
2393 							       true, false);
2394 			}
2395 		}
2396 	}
2397 
2398 	/* First pick non-idle groups */
2399 	for (prio = PANTHOR_CSG_PRIORITY_COUNT - 1;
2400 	     prio >= 0 && !tick_ctx_is_full(sched, &ctx);
2401 	     prio--) {
2402 		tick_ctx_pick_groups_from_list(sched, &ctx, &sched->groups.runnable[prio],
2403 					       true, false);
2404 		tick_ctx_pick_groups_from_list(sched, &ctx, &ctx.old_groups[prio], true, true);
2405 	}
2406 
2407 	/* If we have free CSG slots left, pick idle groups */
2408 	for (prio = PANTHOR_CSG_PRIORITY_COUNT - 1;
2409 	     prio >= 0 && !tick_ctx_is_full(sched, &ctx);
2410 	     prio--) {
2411 		/* Check the old_group queue first to avoid reprogramming the slots */
2412 		tick_ctx_pick_groups_from_list(sched, &ctx, &ctx.old_groups[prio], false, true);
2413 		tick_ctx_pick_groups_from_list(sched, &ctx, &sched->groups.idle[prio],
2414 					       false, false);
2415 	}
2416 
2417 	tick_ctx_apply(sched, &ctx);
2418 	if (ctx.csg_upd_failed_mask)
2419 		goto out_cleanup_ctx;
2420 
2421 	if (ctx.idle_group_count == ctx.group_count) {
2422 		panthor_devfreq_record_idle(sched->ptdev);
2423 		if (sched->pm.has_ref) {
2424 			pm_runtime_put_autosuspend(ptdev->base.dev);
2425 			sched->pm.has_ref = false;
2426 		}
2427 	} else {
2428 		panthor_devfreq_record_busy(sched->ptdev);
2429 		if (!sched->pm.has_ref) {
2430 			pm_runtime_get(ptdev->base.dev);
2431 			sched->pm.has_ref = true;
2432 		}
2433 	}
2434 
2435 	sched->last_tick = now;
2436 	resched_delay = tick_ctx_update_resched_target(sched, &ctx);
2437 	if (ctx.immediate_tick)
2438 		resched_delay = 0;
2439 
2440 	if (resched_delay != U64_MAX)
2441 		sched_queue_delayed_work(sched, tick, resched_delay);
2442 
2443 out_cleanup_ctx:
2444 	tick_ctx_cleanup(sched, &ctx);
2445 
2446 out_unlock:
2447 	mutex_unlock(&sched->lock);
2448 	pm_runtime_mark_last_busy(ptdev->base.dev);
2449 	pm_runtime_put_autosuspend(ptdev->base.dev);
2450 
2451 out_dev_exit:
2452 	drm_dev_exit(cookie);
2453 }
2454 
2455 static int panthor_queue_eval_syncwait(struct panthor_group *group, u8 queue_idx)
2456 {
2457 	struct panthor_queue *queue = group->queues[queue_idx];
2458 	union {
2459 		struct panthor_syncobj_64b sync64;
2460 		struct panthor_syncobj_32b sync32;
2461 	} *syncobj;
2462 	bool result;
2463 	u64 value;
2464 
2465 	syncobj = panthor_queue_get_syncwait_obj(group, queue);
2466 	if (!syncobj)
2467 		return -EINVAL;
2468 
2469 	value = queue->syncwait.sync64 ?
2470 		syncobj->sync64.seqno :
2471 		syncobj->sync32.seqno;
2472 
2473 	if (queue->syncwait.gt)
2474 		result = value > queue->syncwait.ref;
2475 	else
2476 		result = value <= queue->syncwait.ref;
2477 
2478 	if (result)
2479 		panthor_queue_put_syncwait_obj(queue);
2480 
2481 	return result;
2482 }
2483 
2484 static void sync_upd_work(struct work_struct *work)
2485 {
2486 	struct panthor_scheduler *sched = container_of(work,
2487 						      struct panthor_scheduler,
2488 						      sync_upd_work);
2489 	struct panthor_group *group, *tmp;
2490 	bool immediate_tick = false;
2491 
2492 	mutex_lock(&sched->lock);
2493 	list_for_each_entry_safe(group, tmp, &sched->groups.waiting, wait_node) {
2494 		u32 tested_queues = group->blocked_queues;
2495 		u32 unblocked_queues = 0;
2496 
2497 		while (tested_queues) {
2498 			u32 cs_id = ffs(tested_queues) - 1;
2499 			int ret;
2500 
2501 			ret = panthor_queue_eval_syncwait(group, cs_id);
2502 			drm_WARN_ON(&group->ptdev->base, ret < 0);
2503 			if (ret)
2504 				unblocked_queues |= BIT(cs_id);
2505 
2506 			tested_queues &= ~BIT(cs_id);
2507 		}
2508 
2509 		if (unblocked_queues) {
2510 			group->blocked_queues &= ~unblocked_queues;
2511 
2512 			if (group->csg_id < 0) {
2513 				list_move(&group->run_node,
2514 					  &sched->groups.runnable[group->priority]);
2515 				if (group->priority == PANTHOR_CSG_PRIORITY_RT)
2516 					immediate_tick = true;
2517 			}
2518 		}
2519 
2520 		if (!group->blocked_queues)
2521 			list_del_init(&group->wait_node);
2522 	}
2523 	mutex_unlock(&sched->lock);
2524 
2525 	if (immediate_tick)
2526 		sched_queue_delayed_work(sched, tick, 0);
2527 }
2528 
2529 static void group_schedule_locked(struct panthor_group *group, u32 queue_mask)
2530 {
2531 	struct panthor_device *ptdev = group->ptdev;
2532 	struct panthor_scheduler *sched = ptdev->scheduler;
2533 	struct list_head *queue = &sched->groups.runnable[group->priority];
2534 	u64 delay_jiffies = 0;
2535 	bool was_idle;
2536 	u64 now;
2537 
2538 	if (!group_can_run(group))
2539 		return;
2540 
2541 	/* All updated queues are blocked, no need to wake up the scheduler. */
2542 	if ((queue_mask & group->blocked_queues) == queue_mask)
2543 		return;
2544 
2545 	was_idle = group_is_idle(group);
2546 	group->idle_queues &= ~queue_mask;
2547 
2548 	/* Don't mess up with the lists if we're in a middle of a reset. */
2549 	if (atomic_read(&sched->reset.in_progress))
2550 		return;
2551 
2552 	if (was_idle && !group_is_idle(group))
2553 		list_move_tail(&group->run_node, queue);
2554 
2555 	/* RT groups are preemptive. */
2556 	if (group->priority == PANTHOR_CSG_PRIORITY_RT) {
2557 		sched_queue_delayed_work(sched, tick, 0);
2558 		return;
2559 	}
2560 
2561 	/* Some groups might be idle, force an immediate tick to
2562 	 * re-evaluate.
2563 	 */
2564 	if (sched->might_have_idle_groups) {
2565 		sched_queue_delayed_work(sched, tick, 0);
2566 		return;
2567 	}
2568 
2569 	/* Scheduler is ticking, nothing to do. */
2570 	if (sched->resched_target != U64_MAX) {
2571 		/* If there are free slots, force immediating ticking. */
2572 		if (sched->used_csg_slot_count < sched->csg_slot_count)
2573 			sched_queue_delayed_work(sched, tick, 0);
2574 
2575 		return;
2576 	}
2577 
2578 	/* Scheduler tick was off, recalculate the resched_target based on the
2579 	 * last tick event, and queue the scheduler work.
2580 	 */
2581 	now = get_jiffies_64();
2582 	sched->resched_target = sched->last_tick + sched->tick_period;
2583 	if (sched->used_csg_slot_count == sched->csg_slot_count &&
2584 	    time_before64(now, sched->resched_target))
2585 		delay_jiffies = min_t(unsigned long, sched->resched_target - now, ULONG_MAX);
2586 
2587 	sched_queue_delayed_work(sched, tick, delay_jiffies);
2588 }
2589 
2590 static void queue_stop(struct panthor_queue *queue,
2591 		       struct panthor_job *bad_job)
2592 {
2593 	drm_sched_stop(&queue->scheduler, bad_job ? &bad_job->base : NULL);
2594 }
2595 
2596 static void queue_start(struct panthor_queue *queue)
2597 {
2598 	struct panthor_job *job;
2599 
2600 	/* Re-assign the parent fences. */
2601 	list_for_each_entry(job, &queue->scheduler.pending_list, base.list)
2602 		job->base.s_fence->parent = dma_fence_get(job->done_fence);
2603 
2604 	drm_sched_start(&queue->scheduler, 0);
2605 }
2606 
2607 static void panthor_group_stop(struct panthor_group *group)
2608 {
2609 	struct panthor_scheduler *sched = group->ptdev->scheduler;
2610 
2611 	lockdep_assert_held(&sched->reset.lock);
2612 
2613 	for (u32 i = 0; i < group->queue_count; i++)
2614 		queue_stop(group->queues[i], NULL);
2615 
2616 	group_get(group);
2617 	list_move_tail(&group->run_node, &sched->reset.stopped_groups);
2618 }
2619 
2620 static void panthor_group_start(struct panthor_group *group)
2621 {
2622 	struct panthor_scheduler *sched = group->ptdev->scheduler;
2623 
2624 	lockdep_assert_held(&group->ptdev->scheduler->reset.lock);
2625 
2626 	for (u32 i = 0; i < group->queue_count; i++)
2627 		queue_start(group->queues[i]);
2628 
2629 	if (group_can_run(group)) {
2630 		list_move_tail(&group->run_node,
2631 			       group_is_idle(group) ?
2632 			       &sched->groups.idle[group->priority] :
2633 			       &sched->groups.runnable[group->priority]);
2634 	} else {
2635 		list_del_init(&group->run_node);
2636 		list_del_init(&group->wait_node);
2637 		group_queue_work(group, term);
2638 	}
2639 
2640 	group_put(group);
2641 }
2642 
2643 static void panthor_sched_immediate_tick(struct panthor_device *ptdev)
2644 {
2645 	struct panthor_scheduler *sched = ptdev->scheduler;
2646 
2647 	sched_queue_delayed_work(sched, tick, 0);
2648 }
2649 
2650 /**
2651  * panthor_sched_report_mmu_fault() - Report MMU faults to the scheduler.
2652  */
2653 void panthor_sched_report_mmu_fault(struct panthor_device *ptdev)
2654 {
2655 	/* Force a tick to immediately kill faulty groups. */
2656 	if (ptdev->scheduler)
2657 		panthor_sched_immediate_tick(ptdev);
2658 }
2659 
2660 void panthor_sched_resume(struct panthor_device *ptdev)
2661 {
2662 	/* Force a tick to re-evaluate after a resume. */
2663 	panthor_sched_immediate_tick(ptdev);
2664 }
2665 
2666 void panthor_sched_suspend(struct panthor_device *ptdev)
2667 {
2668 	struct panthor_scheduler *sched = ptdev->scheduler;
2669 	struct panthor_csg_slots_upd_ctx upd_ctx;
2670 	struct panthor_group *group;
2671 	u32 suspended_slots;
2672 	u32 i;
2673 
2674 	mutex_lock(&sched->lock);
2675 	csgs_upd_ctx_init(&upd_ctx);
2676 	for (i = 0; i < sched->csg_slot_count; i++) {
2677 		struct panthor_csg_slot *csg_slot = &sched->csg_slots[i];
2678 
2679 		if (csg_slot->group) {
2680 			csgs_upd_ctx_queue_reqs(ptdev, &upd_ctx, i,
2681 						group_can_run(csg_slot->group) ?
2682 						CSG_STATE_SUSPEND : CSG_STATE_TERMINATE,
2683 						CSG_STATE_MASK);
2684 		}
2685 	}
2686 
2687 	suspended_slots = upd_ctx.update_mask;
2688 
2689 	csgs_upd_ctx_apply_locked(ptdev, &upd_ctx);
2690 	suspended_slots &= ~upd_ctx.timedout_mask;
2691 
2692 	if (upd_ctx.timedout_mask) {
2693 		u32 slot_mask = upd_ctx.timedout_mask;
2694 
2695 		drm_err(&ptdev->base, "CSG suspend failed, escalating to termination");
2696 		csgs_upd_ctx_init(&upd_ctx);
2697 		while (slot_mask) {
2698 			u32 csg_id = ffs(slot_mask) - 1;
2699 			struct panthor_csg_slot *csg_slot = &sched->csg_slots[csg_id];
2700 
2701 			/* If the group was still usable before that point, we consider
2702 			 * it innocent.
2703 			 */
2704 			if (group_can_run(csg_slot->group))
2705 				csg_slot->group->innocent = true;
2706 
2707 			/* We consider group suspension failures as fatal and flag the
2708 			 * group as unusable by setting timedout=true.
2709 			 */
2710 			csg_slot->group->timedout = true;
2711 
2712 			csgs_upd_ctx_queue_reqs(ptdev, &upd_ctx, csg_id,
2713 						CSG_STATE_TERMINATE,
2714 						CSG_STATE_MASK);
2715 			slot_mask &= ~BIT(csg_id);
2716 		}
2717 
2718 		csgs_upd_ctx_apply_locked(ptdev, &upd_ctx);
2719 
2720 		slot_mask = upd_ctx.timedout_mask;
2721 		while (slot_mask) {
2722 			u32 csg_id = ffs(slot_mask) - 1;
2723 			struct panthor_csg_slot *csg_slot = &sched->csg_slots[csg_id];
2724 
2725 			/* Terminate command timedout, but the soft-reset will
2726 			 * automatically terminate all active groups, so let's
2727 			 * force the state to halted here.
2728 			 */
2729 			if (csg_slot->group->state != PANTHOR_CS_GROUP_TERMINATED)
2730 				csg_slot->group->state = PANTHOR_CS_GROUP_TERMINATED;
2731 			slot_mask &= ~BIT(csg_id);
2732 		}
2733 	}
2734 
2735 	/* Flush L2 and LSC caches to make sure suspend state is up-to-date.
2736 	 * If the flush fails, flag all queues for termination.
2737 	 */
2738 	if (suspended_slots) {
2739 		bool flush_caches_failed = false;
2740 		u32 slot_mask = suspended_slots;
2741 
2742 		if (panthor_gpu_flush_caches(ptdev, CACHE_CLEAN, CACHE_CLEAN, 0))
2743 			flush_caches_failed = true;
2744 
2745 		while (slot_mask) {
2746 			u32 csg_id = ffs(slot_mask) - 1;
2747 			struct panthor_csg_slot *csg_slot = &sched->csg_slots[csg_id];
2748 
2749 			if (flush_caches_failed)
2750 				csg_slot->group->state = PANTHOR_CS_GROUP_TERMINATED;
2751 			else
2752 				csg_slot_sync_update_locked(ptdev, csg_id);
2753 
2754 			slot_mask &= ~BIT(csg_id);
2755 		}
2756 	}
2757 
2758 	for (i = 0; i < sched->csg_slot_count; i++) {
2759 		struct panthor_csg_slot *csg_slot = &sched->csg_slots[i];
2760 
2761 		group = csg_slot->group;
2762 		if (!group)
2763 			continue;
2764 
2765 		group_get(group);
2766 
2767 		if (group->csg_id >= 0)
2768 			sched_process_csg_irq_locked(ptdev, group->csg_id);
2769 
2770 		group_unbind_locked(group);
2771 
2772 		drm_WARN_ON(&group->ptdev->base, !list_empty(&group->run_node));
2773 
2774 		if (group_can_run(group)) {
2775 			list_add(&group->run_node,
2776 				 &sched->groups.idle[group->priority]);
2777 		} else {
2778 			/* We don't bother stopping the scheduler if the group is
2779 			 * faulty, the group termination work will finish the job.
2780 			 */
2781 			list_del_init(&group->wait_node);
2782 			group_queue_work(group, term);
2783 		}
2784 		group_put(group);
2785 	}
2786 	mutex_unlock(&sched->lock);
2787 }
2788 
2789 void panthor_sched_pre_reset(struct panthor_device *ptdev)
2790 {
2791 	struct panthor_scheduler *sched = ptdev->scheduler;
2792 	struct panthor_group *group, *group_tmp;
2793 	u32 i;
2794 
2795 	mutex_lock(&sched->reset.lock);
2796 	atomic_set(&sched->reset.in_progress, true);
2797 
2798 	/* Cancel all scheduler works. Once this is done, these works can't be
2799 	 * scheduled again until the reset operation is complete.
2800 	 */
2801 	cancel_work_sync(&sched->sync_upd_work);
2802 	cancel_delayed_work_sync(&sched->tick_work);
2803 
2804 	panthor_sched_suspend(ptdev);
2805 
2806 	/* Stop all groups that might still accept jobs, so we don't get passed
2807 	 * new jobs while we're resetting.
2808 	 */
2809 	for (i = 0; i < ARRAY_SIZE(sched->groups.runnable); i++) {
2810 		/* All groups should be in the idle lists. */
2811 		drm_WARN_ON(&ptdev->base, !list_empty(&sched->groups.runnable[i]));
2812 		list_for_each_entry_safe(group, group_tmp, &sched->groups.runnable[i], run_node)
2813 			panthor_group_stop(group);
2814 	}
2815 
2816 	for (i = 0; i < ARRAY_SIZE(sched->groups.idle); i++) {
2817 		list_for_each_entry_safe(group, group_tmp, &sched->groups.idle[i], run_node)
2818 			panthor_group_stop(group);
2819 	}
2820 
2821 	mutex_unlock(&sched->reset.lock);
2822 }
2823 
2824 void panthor_sched_post_reset(struct panthor_device *ptdev, bool reset_failed)
2825 {
2826 	struct panthor_scheduler *sched = ptdev->scheduler;
2827 	struct panthor_group *group, *group_tmp;
2828 
2829 	mutex_lock(&sched->reset.lock);
2830 
2831 	list_for_each_entry_safe(group, group_tmp, &sched->reset.stopped_groups, run_node) {
2832 		/* Consider all previously running group as terminated if the
2833 		 * reset failed.
2834 		 */
2835 		if (reset_failed)
2836 			group->state = PANTHOR_CS_GROUP_TERMINATED;
2837 
2838 		panthor_group_start(group);
2839 	}
2840 
2841 	/* We're done resetting the GPU, clear the reset.in_progress bit so we can
2842 	 * kick the scheduler.
2843 	 */
2844 	atomic_set(&sched->reset.in_progress, false);
2845 	mutex_unlock(&sched->reset.lock);
2846 
2847 	/* No need to queue a tick and update syncs if the reset failed. */
2848 	if (!reset_failed) {
2849 		sched_queue_delayed_work(sched, tick, 0);
2850 		sched_queue_work(sched, sync_upd);
2851 	}
2852 }
2853 
2854 static void update_fdinfo_stats(struct panthor_job *job)
2855 {
2856 	struct panthor_group *group = job->group;
2857 	struct panthor_queue *queue = group->queues[job->queue_idx];
2858 	struct panthor_gpu_usage *fdinfo = &group->fdinfo.data;
2859 	struct panthor_job_profiling_data *slots = queue->profiling.slots->kmap;
2860 	struct panthor_job_profiling_data *data = &slots[job->profiling.slot];
2861 
2862 	scoped_guard(spinlock, &group->fdinfo.lock) {
2863 		if (job->profiling.mask & PANTHOR_DEVICE_PROFILING_CYCLES)
2864 			fdinfo->cycles += data->cycles.after - data->cycles.before;
2865 		if (job->profiling.mask & PANTHOR_DEVICE_PROFILING_TIMESTAMP)
2866 			fdinfo->time += data->time.after - data->time.before;
2867 	}
2868 }
2869 
2870 void panthor_fdinfo_gather_group_samples(struct panthor_file *pfile)
2871 {
2872 	struct panthor_group_pool *gpool = pfile->groups;
2873 	struct panthor_group *group;
2874 	unsigned long i;
2875 
2876 	if (IS_ERR_OR_NULL(gpool))
2877 		return;
2878 
2879 	xa_lock(&gpool->xa);
2880 	xa_for_each(&gpool->xa, i, group) {
2881 		guard(spinlock)(&group->fdinfo.lock);
2882 		pfile->stats.cycles += group->fdinfo.data.cycles;
2883 		pfile->stats.time += group->fdinfo.data.time;
2884 		group->fdinfo.data.cycles = 0;
2885 		group->fdinfo.data.time = 0;
2886 	}
2887 	xa_unlock(&gpool->xa);
2888 }
2889 
2890 static void group_sync_upd_work(struct work_struct *work)
2891 {
2892 	struct panthor_group *group =
2893 		container_of(work, struct panthor_group, sync_upd_work);
2894 	struct panthor_job *job, *job_tmp;
2895 	LIST_HEAD(done_jobs);
2896 	u32 queue_idx;
2897 	bool cookie;
2898 
2899 	cookie = dma_fence_begin_signalling();
2900 	for (queue_idx = 0; queue_idx < group->queue_count; queue_idx++) {
2901 		struct panthor_queue *queue = group->queues[queue_idx];
2902 		struct panthor_syncobj_64b *syncobj;
2903 
2904 		if (!queue)
2905 			continue;
2906 
2907 		syncobj = group->syncobjs->kmap + (queue_idx * sizeof(*syncobj));
2908 
2909 		spin_lock(&queue->fence_ctx.lock);
2910 		list_for_each_entry_safe(job, job_tmp, &queue->fence_ctx.in_flight_jobs, node) {
2911 			if (syncobj->seqno < job->done_fence->seqno)
2912 				break;
2913 
2914 			list_move_tail(&job->node, &done_jobs);
2915 			dma_fence_signal_locked(job->done_fence);
2916 		}
2917 		spin_unlock(&queue->fence_ctx.lock);
2918 	}
2919 	dma_fence_end_signalling(cookie);
2920 
2921 	list_for_each_entry_safe(job, job_tmp, &done_jobs, node) {
2922 		if (job->profiling.mask)
2923 			update_fdinfo_stats(job);
2924 		list_del_init(&job->node);
2925 		panthor_job_put(&job->base);
2926 	}
2927 
2928 	group_put(group);
2929 }
2930 
2931 struct panthor_job_ringbuf_instrs {
2932 	u64 buffer[MAX_INSTRS_PER_JOB];
2933 	u32 count;
2934 };
2935 
2936 struct panthor_job_instr {
2937 	u32 profile_mask;
2938 	u64 instr;
2939 };
2940 
2941 #define JOB_INSTR(__prof, __instr) \
2942 	{ \
2943 		.profile_mask = __prof, \
2944 		.instr = __instr, \
2945 	}
2946 
2947 static void
2948 copy_instrs_to_ringbuf(struct panthor_queue *queue,
2949 		       struct panthor_job *job,
2950 		       struct panthor_job_ringbuf_instrs *instrs)
2951 {
2952 	u64 ringbuf_size = panthor_kernel_bo_size(queue->ringbuf);
2953 	u64 start = job->ringbuf.start & (ringbuf_size - 1);
2954 	u64 size, written;
2955 
2956 	/*
2957 	 * We need to write a whole slot, including any trailing zeroes
2958 	 * that may come at the end of it. Also, because instrs.buffer has
2959 	 * been zero-initialised, there's no need to pad it with 0's
2960 	 */
2961 	instrs->count = ALIGN(instrs->count, NUM_INSTRS_PER_CACHE_LINE);
2962 	size = instrs->count * sizeof(u64);
2963 	WARN_ON(size > ringbuf_size);
2964 	written = min(ringbuf_size - start, size);
2965 
2966 	memcpy(queue->ringbuf->kmap + start, instrs->buffer, written);
2967 
2968 	if (written < size)
2969 		memcpy(queue->ringbuf->kmap,
2970 		       &instrs->buffer[written / sizeof(u64)],
2971 		       size - written);
2972 }
2973 
2974 struct panthor_job_cs_params {
2975 	u32 profile_mask;
2976 	u64 addr_reg; u64 val_reg;
2977 	u64 cycle_reg; u64 time_reg;
2978 	u64 sync_addr; u64 times_addr;
2979 	u64 cs_start; u64 cs_size;
2980 	u32 last_flush; u32 waitall_mask;
2981 };
2982 
2983 static void
2984 get_job_cs_params(struct panthor_job *job, struct panthor_job_cs_params *params)
2985 {
2986 	struct panthor_group *group = job->group;
2987 	struct panthor_queue *queue = group->queues[job->queue_idx];
2988 	struct panthor_device *ptdev = group->ptdev;
2989 	struct panthor_scheduler *sched = ptdev->scheduler;
2990 
2991 	params->addr_reg = ptdev->csif_info.cs_reg_count -
2992 			   ptdev->csif_info.unpreserved_cs_reg_count;
2993 	params->val_reg = params->addr_reg + 2;
2994 	params->cycle_reg = params->addr_reg;
2995 	params->time_reg = params->val_reg;
2996 
2997 	params->sync_addr = panthor_kernel_bo_gpuva(group->syncobjs) +
2998 			    job->queue_idx * sizeof(struct panthor_syncobj_64b);
2999 	params->times_addr = panthor_kernel_bo_gpuva(queue->profiling.slots) +
3000 			     (job->profiling.slot * sizeof(struct panthor_job_profiling_data));
3001 	params->waitall_mask = GENMASK(sched->sb_slot_count - 1, 0);
3002 
3003 	params->cs_start = job->call_info.start;
3004 	params->cs_size = job->call_info.size;
3005 	params->last_flush = job->call_info.latest_flush;
3006 
3007 	params->profile_mask = job->profiling.mask;
3008 }
3009 
3010 #define JOB_INSTR_ALWAYS(instr) \
3011 	JOB_INSTR(PANTHOR_DEVICE_PROFILING_DISABLED, (instr))
3012 #define JOB_INSTR_TIMESTAMP(instr) \
3013 	JOB_INSTR(PANTHOR_DEVICE_PROFILING_TIMESTAMP, (instr))
3014 #define JOB_INSTR_CYCLES(instr) \
3015 	JOB_INSTR(PANTHOR_DEVICE_PROFILING_CYCLES, (instr))
3016 
3017 static void
3018 prepare_job_instrs(const struct panthor_job_cs_params *params,
3019 		   struct panthor_job_ringbuf_instrs *instrs)
3020 {
3021 	const struct panthor_job_instr instr_seq[] = {
3022 		/* MOV32 rX+2, cs.latest_flush */
3023 		JOB_INSTR_ALWAYS((2ull << 56) | (params->val_reg << 48) | params->last_flush),
3024 		/* FLUSH_CACHE2.clean_inv_all.no_wait.signal(0) rX+2 */
3025 		JOB_INSTR_ALWAYS((36ull << 56) | (0ull << 48) | (params->val_reg << 40) |
3026 				 (0 << 16) | 0x233),
3027 		/* MOV48 rX:rX+1, cycles_offset */
3028 		JOB_INSTR_CYCLES((1ull << 56) | (params->cycle_reg << 48) |
3029 				 (params->times_addr +
3030 				  offsetof(struct panthor_job_profiling_data, cycles.before))),
3031 		/* STORE_STATE cycles */
3032 		JOB_INSTR_CYCLES((40ull << 56) | (params->cycle_reg << 40) | (1ll << 32)),
3033 		/* MOV48 rX:rX+1, time_offset */
3034 		JOB_INSTR_TIMESTAMP((1ull << 56) | (params->time_reg << 48) |
3035 				    (params->times_addr +
3036 				     offsetof(struct panthor_job_profiling_data, time.before))),
3037 		/* STORE_STATE timer */
3038 		JOB_INSTR_TIMESTAMP((40ull << 56) | (params->time_reg << 40) | (0ll << 32)),
3039 		/* MOV48 rX:rX+1, cs.start */
3040 		JOB_INSTR_ALWAYS((1ull << 56) | (params->addr_reg << 48) | params->cs_start),
3041 		/* MOV32 rX+2, cs.size */
3042 		JOB_INSTR_ALWAYS((2ull << 56) | (params->val_reg << 48) | params->cs_size),
3043 		/* WAIT(0) => waits for FLUSH_CACHE2 instruction */
3044 		JOB_INSTR_ALWAYS((3ull << 56) | (1 << 16)),
3045 		/* CALL rX:rX+1, rX+2 */
3046 		JOB_INSTR_ALWAYS((32ull << 56) | (params->addr_reg << 40) |
3047 				 (params->val_reg << 32)),
3048 		/* MOV48 rX:rX+1, cycles_offset */
3049 		JOB_INSTR_CYCLES((1ull << 56) | (params->cycle_reg << 48) |
3050 				 (params->times_addr +
3051 				  offsetof(struct panthor_job_profiling_data, cycles.after))),
3052 		/* STORE_STATE cycles */
3053 		JOB_INSTR_CYCLES((40ull << 56) | (params->cycle_reg << 40) | (1ll << 32)),
3054 		/* MOV48 rX:rX+1, time_offset */
3055 		JOB_INSTR_TIMESTAMP((1ull << 56) | (params->time_reg << 48) |
3056 			  (params->times_addr +
3057 			   offsetof(struct panthor_job_profiling_data, time.after))),
3058 		/* STORE_STATE timer */
3059 		JOB_INSTR_TIMESTAMP((40ull << 56) | (params->time_reg << 40) | (0ll << 32)),
3060 		/* MOV48 rX:rX+1, sync_addr */
3061 		JOB_INSTR_ALWAYS((1ull << 56) | (params->addr_reg << 48) | params->sync_addr),
3062 		/* MOV48 rX+2, #1 */
3063 		JOB_INSTR_ALWAYS((1ull << 56) | (params->val_reg << 48) | 1),
3064 		/* WAIT(all) */
3065 		JOB_INSTR_ALWAYS((3ull << 56) | (params->waitall_mask << 16)),
3066 		/* SYNC_ADD64.system_scope.propage_err.nowait rX:rX+1, rX+2*/
3067 		JOB_INSTR_ALWAYS((51ull << 56) | (0ull << 48) | (params->addr_reg << 40) |
3068 				 (params->val_reg << 32) | (0 << 16) | 1),
3069 		/* ERROR_BARRIER, so we can recover from faults at job boundaries. */
3070 		JOB_INSTR_ALWAYS((47ull << 56)),
3071 	};
3072 	u32 pad;
3073 
3074 	instrs->count = 0;
3075 
3076 	/* NEED to be cacheline aligned to please the prefetcher. */
3077 	static_assert(sizeof(instrs->buffer) % 64 == 0,
3078 		      "panthor_job_ringbuf_instrs::buffer is not aligned on a cacheline");
3079 
3080 	/* Make sure we have enough storage to store the whole sequence. */
3081 	static_assert(ALIGN(ARRAY_SIZE(instr_seq), NUM_INSTRS_PER_CACHE_LINE) ==
3082 		      ARRAY_SIZE(instrs->buffer),
3083 		      "instr_seq vs panthor_job_ringbuf_instrs::buffer size mismatch");
3084 
3085 	for (u32 i = 0; i < ARRAY_SIZE(instr_seq); i++) {
3086 		/* If the profile mask of this instruction is not enabled, skip it. */
3087 		if (instr_seq[i].profile_mask &&
3088 		    !(instr_seq[i].profile_mask & params->profile_mask))
3089 			continue;
3090 
3091 		instrs->buffer[instrs->count++] = instr_seq[i].instr;
3092 	}
3093 
3094 	pad = ALIGN(instrs->count, NUM_INSTRS_PER_CACHE_LINE);
3095 	memset(&instrs->buffer[instrs->count], 0,
3096 	       (pad - instrs->count) * sizeof(instrs->buffer[0]));
3097 	instrs->count = pad;
3098 }
3099 
3100 static u32 calc_job_credits(u32 profile_mask)
3101 {
3102 	struct panthor_job_ringbuf_instrs instrs;
3103 	struct panthor_job_cs_params params = {
3104 		.profile_mask = profile_mask,
3105 	};
3106 
3107 	prepare_job_instrs(&params, &instrs);
3108 	return instrs.count;
3109 }
3110 
3111 static struct dma_fence *
3112 queue_run_job(struct drm_sched_job *sched_job)
3113 {
3114 	struct panthor_job *job = container_of(sched_job, struct panthor_job, base);
3115 	struct panthor_group *group = job->group;
3116 	struct panthor_queue *queue = group->queues[job->queue_idx];
3117 	struct panthor_device *ptdev = group->ptdev;
3118 	struct panthor_scheduler *sched = ptdev->scheduler;
3119 	struct panthor_job_ringbuf_instrs instrs;
3120 	struct panthor_job_cs_params cs_params;
3121 	struct dma_fence *done_fence;
3122 	int ret;
3123 
3124 	/* Stream size is zero, nothing to do except making sure all previously
3125 	 * submitted jobs are done before we signal the
3126 	 * drm_sched_job::s_fence::finished fence.
3127 	 */
3128 	if (!job->call_info.size) {
3129 		job->done_fence = dma_fence_get(queue->fence_ctx.last_fence);
3130 		return dma_fence_get(job->done_fence);
3131 	}
3132 
3133 	ret = panthor_device_resume_and_get(ptdev);
3134 	if (drm_WARN_ON(&ptdev->base, ret))
3135 		return ERR_PTR(ret);
3136 
3137 	mutex_lock(&sched->lock);
3138 	if (!group_can_run(group)) {
3139 		done_fence = ERR_PTR(-ECANCELED);
3140 		goto out_unlock;
3141 	}
3142 
3143 	dma_fence_init(job->done_fence,
3144 		       &panthor_queue_fence_ops,
3145 		       &queue->fence_ctx.lock,
3146 		       queue->fence_ctx.id,
3147 		       atomic64_inc_return(&queue->fence_ctx.seqno));
3148 
3149 	job->profiling.slot = queue->profiling.seqno++;
3150 	if (queue->profiling.seqno == queue->profiling.slot_count)
3151 		queue->profiling.seqno = 0;
3152 
3153 	job->ringbuf.start = queue->iface.input->insert;
3154 
3155 	get_job_cs_params(job, &cs_params);
3156 	prepare_job_instrs(&cs_params, &instrs);
3157 	copy_instrs_to_ringbuf(queue, job, &instrs);
3158 
3159 	job->ringbuf.end = job->ringbuf.start + (instrs.count * sizeof(u64));
3160 
3161 	panthor_job_get(&job->base);
3162 	spin_lock(&queue->fence_ctx.lock);
3163 	list_add_tail(&job->node, &queue->fence_ctx.in_flight_jobs);
3164 	spin_unlock(&queue->fence_ctx.lock);
3165 
3166 	/* Make sure the ring buffer is updated before the INSERT
3167 	 * register.
3168 	 */
3169 	wmb();
3170 
3171 	queue->iface.input->extract = queue->iface.output->extract;
3172 	queue->iface.input->insert = job->ringbuf.end;
3173 
3174 	if (group->csg_id < 0) {
3175 		/* If the queue is blocked, we want to keep the timeout running, so we
3176 		 * can detect unbounded waits and kill the group when that happens.
3177 		 * Otherwise, we suspend the timeout so the time we spend waiting for
3178 		 * a CSG slot is not counted.
3179 		 */
3180 		if (!(group->blocked_queues & BIT(job->queue_idx)) &&
3181 		    !queue->timeout_suspended) {
3182 			queue->remaining_time = drm_sched_suspend_timeout(&queue->scheduler);
3183 			queue->timeout_suspended = true;
3184 		}
3185 
3186 		group_schedule_locked(group, BIT(job->queue_idx));
3187 	} else {
3188 		gpu_write(ptdev, CSF_DOORBELL(queue->doorbell_id), 1);
3189 		if (!sched->pm.has_ref &&
3190 		    !(group->blocked_queues & BIT(job->queue_idx))) {
3191 			pm_runtime_get(ptdev->base.dev);
3192 			sched->pm.has_ref = true;
3193 		}
3194 		panthor_devfreq_record_busy(sched->ptdev);
3195 	}
3196 
3197 	/* Update the last fence. */
3198 	dma_fence_put(queue->fence_ctx.last_fence);
3199 	queue->fence_ctx.last_fence = dma_fence_get(job->done_fence);
3200 
3201 	done_fence = dma_fence_get(job->done_fence);
3202 
3203 out_unlock:
3204 	mutex_unlock(&sched->lock);
3205 	pm_runtime_mark_last_busy(ptdev->base.dev);
3206 	pm_runtime_put_autosuspend(ptdev->base.dev);
3207 
3208 	return done_fence;
3209 }
3210 
3211 static enum drm_gpu_sched_stat
3212 queue_timedout_job(struct drm_sched_job *sched_job)
3213 {
3214 	struct panthor_job *job = container_of(sched_job, struct panthor_job, base);
3215 	struct panthor_group *group = job->group;
3216 	struct panthor_device *ptdev = group->ptdev;
3217 	struct panthor_scheduler *sched = ptdev->scheduler;
3218 	struct panthor_queue *queue = group->queues[job->queue_idx];
3219 
3220 	drm_warn(&ptdev->base, "job timeout\n");
3221 
3222 	drm_WARN_ON(&ptdev->base, atomic_read(&sched->reset.in_progress));
3223 
3224 	queue_stop(queue, job);
3225 
3226 	mutex_lock(&sched->lock);
3227 	group->timedout = true;
3228 	if (group->csg_id >= 0) {
3229 		sched_queue_delayed_work(ptdev->scheduler, tick, 0);
3230 	} else {
3231 		/* Remove from the run queues, so the scheduler can't
3232 		 * pick the group on the next tick.
3233 		 */
3234 		list_del_init(&group->run_node);
3235 		list_del_init(&group->wait_node);
3236 
3237 		group_queue_work(group, term);
3238 	}
3239 	mutex_unlock(&sched->lock);
3240 
3241 	queue_start(queue);
3242 
3243 	return DRM_GPU_SCHED_STAT_RESET;
3244 }
3245 
3246 static void queue_free_job(struct drm_sched_job *sched_job)
3247 {
3248 	drm_sched_job_cleanup(sched_job);
3249 	panthor_job_put(sched_job);
3250 }
3251 
3252 static const struct drm_sched_backend_ops panthor_queue_sched_ops = {
3253 	.run_job = queue_run_job,
3254 	.timedout_job = queue_timedout_job,
3255 	.free_job = queue_free_job,
3256 };
3257 
3258 static u32 calc_profiling_ringbuf_num_slots(struct panthor_device *ptdev,
3259 					    u32 cs_ringbuf_size)
3260 {
3261 	u32 min_profiled_job_instrs = U32_MAX;
3262 	u32 last_flag = fls(PANTHOR_DEVICE_PROFILING_ALL);
3263 
3264 	/*
3265 	 * We want to calculate the minimum size of a profiled job's CS,
3266 	 * because since they need additional instructions for the sampling
3267 	 * of performance metrics, they might take up further slots in
3268 	 * the queue's ringbuffer. This means we might not need as many job
3269 	 * slots for keeping track of their profiling information. What we
3270 	 * need is the maximum number of slots we should allocate to this end,
3271 	 * which matches the maximum number of profiled jobs we can place
3272 	 * simultaneously in the queue's ring buffer.
3273 	 * That has to be calculated separately for every single job profiling
3274 	 * flag, but not in the case job profiling is disabled, since unprofiled
3275 	 * jobs don't need to keep track of this at all.
3276 	 */
3277 	for (u32 i = 0; i < last_flag; i++) {
3278 		min_profiled_job_instrs =
3279 			min(min_profiled_job_instrs, calc_job_credits(BIT(i)));
3280 	}
3281 
3282 	return DIV_ROUND_UP(cs_ringbuf_size, min_profiled_job_instrs * sizeof(u64));
3283 }
3284 
3285 static struct panthor_queue *
3286 group_create_queue(struct panthor_group *group,
3287 		   const struct drm_panthor_queue_create *args)
3288 {
3289 	const struct drm_sched_init_args sched_args = {
3290 		.ops = &panthor_queue_sched_ops,
3291 		.submit_wq = group->ptdev->scheduler->wq,
3292 		.num_rqs = 1,
3293 		/*
3294 		 * The credit limit argument tells us the total number of
3295 		 * instructions across all CS slots in the ringbuffer, with
3296 		 * some jobs requiring twice as many as others, depending on
3297 		 * their profiling status.
3298 		 */
3299 		.credit_limit = args->ringbuf_size / sizeof(u64),
3300 		.timeout = msecs_to_jiffies(JOB_TIMEOUT_MS),
3301 		.timeout_wq = group->ptdev->reset.wq,
3302 		.name = "panthor-queue",
3303 		.dev = group->ptdev->base.dev,
3304 	};
3305 	struct drm_gpu_scheduler *drm_sched;
3306 	struct panthor_queue *queue;
3307 	int ret;
3308 
3309 	if (args->pad[0] || args->pad[1] || args->pad[2])
3310 		return ERR_PTR(-EINVAL);
3311 
3312 	if (args->ringbuf_size < SZ_4K || args->ringbuf_size > SZ_64K ||
3313 	    !is_power_of_2(args->ringbuf_size))
3314 		return ERR_PTR(-EINVAL);
3315 
3316 	if (args->priority > CSF_MAX_QUEUE_PRIO)
3317 		return ERR_PTR(-EINVAL);
3318 
3319 	queue = kzalloc(sizeof(*queue), GFP_KERNEL);
3320 	if (!queue)
3321 		return ERR_PTR(-ENOMEM);
3322 
3323 	queue->fence_ctx.id = dma_fence_context_alloc(1);
3324 	spin_lock_init(&queue->fence_ctx.lock);
3325 	INIT_LIST_HEAD(&queue->fence_ctx.in_flight_jobs);
3326 
3327 	queue->priority = args->priority;
3328 
3329 	queue->ringbuf = panthor_kernel_bo_create(group->ptdev, group->vm,
3330 						  args->ringbuf_size,
3331 						  DRM_PANTHOR_BO_NO_MMAP,
3332 						  DRM_PANTHOR_VM_BIND_OP_MAP_NOEXEC |
3333 						  DRM_PANTHOR_VM_BIND_OP_MAP_UNCACHED,
3334 						  PANTHOR_VM_KERNEL_AUTO_VA,
3335 						  "CS ring buffer");
3336 	if (IS_ERR(queue->ringbuf)) {
3337 		ret = PTR_ERR(queue->ringbuf);
3338 		goto err_free_queue;
3339 	}
3340 
3341 	ret = panthor_kernel_bo_vmap(queue->ringbuf);
3342 	if (ret)
3343 		goto err_free_queue;
3344 
3345 	queue->iface.mem = panthor_fw_alloc_queue_iface_mem(group->ptdev,
3346 							    &queue->iface.input,
3347 							    &queue->iface.output,
3348 							    &queue->iface.input_fw_va,
3349 							    &queue->iface.output_fw_va);
3350 	if (IS_ERR(queue->iface.mem)) {
3351 		ret = PTR_ERR(queue->iface.mem);
3352 		goto err_free_queue;
3353 	}
3354 
3355 	queue->profiling.slot_count =
3356 		calc_profiling_ringbuf_num_slots(group->ptdev, args->ringbuf_size);
3357 
3358 	queue->profiling.slots =
3359 		panthor_kernel_bo_create(group->ptdev, group->vm,
3360 					 queue->profiling.slot_count *
3361 					 sizeof(struct panthor_job_profiling_data),
3362 					 DRM_PANTHOR_BO_NO_MMAP,
3363 					 DRM_PANTHOR_VM_BIND_OP_MAP_NOEXEC |
3364 					 DRM_PANTHOR_VM_BIND_OP_MAP_UNCACHED,
3365 					 PANTHOR_VM_KERNEL_AUTO_VA,
3366 					 "Group job stats");
3367 
3368 	if (IS_ERR(queue->profiling.slots)) {
3369 		ret = PTR_ERR(queue->profiling.slots);
3370 		goto err_free_queue;
3371 	}
3372 
3373 	ret = panthor_kernel_bo_vmap(queue->profiling.slots);
3374 	if (ret)
3375 		goto err_free_queue;
3376 
3377 	ret = drm_sched_init(&queue->scheduler, &sched_args);
3378 	if (ret)
3379 		goto err_free_queue;
3380 
3381 	drm_sched = &queue->scheduler;
3382 	ret = drm_sched_entity_init(&queue->entity, 0, &drm_sched, 1, NULL);
3383 
3384 	return queue;
3385 
3386 err_free_queue:
3387 	group_free_queue(group, queue);
3388 	return ERR_PTR(ret);
3389 }
3390 
3391 static void add_group_kbo_sizes(struct panthor_device *ptdev,
3392 				struct panthor_group *group)
3393 {
3394 	struct panthor_queue *queue;
3395 	int i;
3396 
3397 	if (drm_WARN_ON(&ptdev->base, IS_ERR_OR_NULL(group)))
3398 		return;
3399 	if (drm_WARN_ON(&ptdev->base, ptdev != group->ptdev))
3400 		return;
3401 
3402 	group->fdinfo.kbo_sizes += group->suspend_buf->obj->size;
3403 	group->fdinfo.kbo_sizes += group->protm_suspend_buf->obj->size;
3404 	group->fdinfo.kbo_sizes += group->syncobjs->obj->size;
3405 
3406 	for (i = 0; i < group->queue_count; i++) {
3407 		queue =	group->queues[i];
3408 		group->fdinfo.kbo_sizes += queue->ringbuf->obj->size;
3409 		group->fdinfo.kbo_sizes += queue->iface.mem->obj->size;
3410 		group->fdinfo.kbo_sizes += queue->profiling.slots->obj->size;
3411 	}
3412 }
3413 
3414 #define MAX_GROUPS_PER_POOL		128
3415 
3416 int panthor_group_create(struct panthor_file *pfile,
3417 			 const struct drm_panthor_group_create *group_args,
3418 			 const struct drm_panthor_queue_create *queue_args)
3419 {
3420 	struct panthor_device *ptdev = pfile->ptdev;
3421 	struct panthor_group_pool *gpool = pfile->groups;
3422 	struct panthor_scheduler *sched = ptdev->scheduler;
3423 	struct panthor_fw_csg_iface *csg_iface = panthor_fw_get_csg_iface(ptdev, 0);
3424 	struct panthor_group *group = NULL;
3425 	u32 gid, i, suspend_size;
3426 	int ret;
3427 
3428 	if (group_args->pad)
3429 		return -EINVAL;
3430 
3431 	if (group_args->priority >= PANTHOR_CSG_PRIORITY_COUNT)
3432 		return -EINVAL;
3433 
3434 	if ((group_args->compute_core_mask & ~ptdev->gpu_info.shader_present) ||
3435 	    (group_args->fragment_core_mask & ~ptdev->gpu_info.shader_present) ||
3436 	    (group_args->tiler_core_mask & ~ptdev->gpu_info.tiler_present))
3437 		return -EINVAL;
3438 
3439 	if (hweight64(group_args->compute_core_mask) < group_args->max_compute_cores ||
3440 	    hweight64(group_args->fragment_core_mask) < group_args->max_fragment_cores ||
3441 	    hweight64(group_args->tiler_core_mask) < group_args->max_tiler_cores)
3442 		return -EINVAL;
3443 
3444 	group = kzalloc(sizeof(*group), GFP_KERNEL);
3445 	if (!group)
3446 		return -ENOMEM;
3447 
3448 	spin_lock_init(&group->fatal_lock);
3449 	kref_init(&group->refcount);
3450 	group->state = PANTHOR_CS_GROUP_CREATED;
3451 	group->csg_id = -1;
3452 
3453 	group->ptdev = ptdev;
3454 	group->max_compute_cores = group_args->max_compute_cores;
3455 	group->compute_core_mask = group_args->compute_core_mask;
3456 	group->max_fragment_cores = group_args->max_fragment_cores;
3457 	group->fragment_core_mask = group_args->fragment_core_mask;
3458 	group->max_tiler_cores = group_args->max_tiler_cores;
3459 	group->tiler_core_mask = group_args->tiler_core_mask;
3460 	group->priority = group_args->priority;
3461 
3462 	INIT_LIST_HEAD(&group->wait_node);
3463 	INIT_LIST_HEAD(&group->run_node);
3464 	INIT_WORK(&group->term_work, group_term_work);
3465 	INIT_WORK(&group->sync_upd_work, group_sync_upd_work);
3466 	INIT_WORK(&group->tiler_oom_work, group_tiler_oom_work);
3467 	INIT_WORK(&group->release_work, group_release_work);
3468 
3469 	group->vm = panthor_vm_pool_get_vm(pfile->vms, group_args->vm_id);
3470 	if (!group->vm) {
3471 		ret = -EINVAL;
3472 		goto err_put_group;
3473 	}
3474 
3475 	suspend_size = csg_iface->control->suspend_size;
3476 	group->suspend_buf = panthor_fw_alloc_suspend_buf_mem(ptdev, suspend_size);
3477 	if (IS_ERR(group->suspend_buf)) {
3478 		ret = PTR_ERR(group->suspend_buf);
3479 		group->suspend_buf = NULL;
3480 		goto err_put_group;
3481 	}
3482 
3483 	suspend_size = csg_iface->control->protm_suspend_size;
3484 	group->protm_suspend_buf = panthor_fw_alloc_suspend_buf_mem(ptdev, suspend_size);
3485 	if (IS_ERR(group->protm_suspend_buf)) {
3486 		ret = PTR_ERR(group->protm_suspend_buf);
3487 		group->protm_suspend_buf = NULL;
3488 		goto err_put_group;
3489 	}
3490 
3491 	group->syncobjs = panthor_kernel_bo_create(ptdev, group->vm,
3492 						   group_args->queues.count *
3493 						   sizeof(struct panthor_syncobj_64b),
3494 						   DRM_PANTHOR_BO_NO_MMAP,
3495 						   DRM_PANTHOR_VM_BIND_OP_MAP_NOEXEC |
3496 						   DRM_PANTHOR_VM_BIND_OP_MAP_UNCACHED,
3497 						   PANTHOR_VM_KERNEL_AUTO_VA,
3498 						   "Group sync objects");
3499 	if (IS_ERR(group->syncobjs)) {
3500 		ret = PTR_ERR(group->syncobjs);
3501 		goto err_put_group;
3502 	}
3503 
3504 	ret = panthor_kernel_bo_vmap(group->syncobjs);
3505 	if (ret)
3506 		goto err_put_group;
3507 
3508 	memset(group->syncobjs->kmap, 0,
3509 	       group_args->queues.count * sizeof(struct panthor_syncobj_64b));
3510 
3511 	for (i = 0; i < group_args->queues.count; i++) {
3512 		group->queues[i] = group_create_queue(group, &queue_args[i]);
3513 		if (IS_ERR(group->queues[i])) {
3514 			ret = PTR_ERR(group->queues[i]);
3515 			group->queues[i] = NULL;
3516 			goto err_put_group;
3517 		}
3518 
3519 		group->queue_count++;
3520 	}
3521 
3522 	group->idle_queues = GENMASK(group->queue_count - 1, 0);
3523 
3524 	ret = xa_alloc(&gpool->xa, &gid, group, XA_LIMIT(1, MAX_GROUPS_PER_POOL), GFP_KERNEL);
3525 	if (ret)
3526 		goto err_put_group;
3527 
3528 	mutex_lock(&sched->reset.lock);
3529 	if (atomic_read(&sched->reset.in_progress)) {
3530 		panthor_group_stop(group);
3531 	} else {
3532 		mutex_lock(&sched->lock);
3533 		list_add_tail(&group->run_node,
3534 			      &sched->groups.idle[group->priority]);
3535 		mutex_unlock(&sched->lock);
3536 	}
3537 	mutex_unlock(&sched->reset.lock);
3538 
3539 	add_group_kbo_sizes(group->ptdev, group);
3540 	spin_lock_init(&group->fdinfo.lock);
3541 
3542 	return gid;
3543 
3544 err_put_group:
3545 	group_put(group);
3546 	return ret;
3547 }
3548 
3549 int panthor_group_destroy(struct panthor_file *pfile, u32 group_handle)
3550 {
3551 	struct panthor_group_pool *gpool = pfile->groups;
3552 	struct panthor_device *ptdev = pfile->ptdev;
3553 	struct panthor_scheduler *sched = ptdev->scheduler;
3554 	struct panthor_group *group;
3555 
3556 	group = xa_erase(&gpool->xa, group_handle);
3557 	if (!group)
3558 		return -EINVAL;
3559 
3560 	mutex_lock(&sched->reset.lock);
3561 	mutex_lock(&sched->lock);
3562 	group->destroyed = true;
3563 	if (group->csg_id >= 0) {
3564 		sched_queue_delayed_work(sched, tick, 0);
3565 	} else if (!atomic_read(&sched->reset.in_progress)) {
3566 		/* Remove from the run queues, so the scheduler can't
3567 		 * pick the group on the next tick.
3568 		 */
3569 		list_del_init(&group->run_node);
3570 		list_del_init(&group->wait_node);
3571 		group_queue_work(group, term);
3572 	}
3573 	mutex_unlock(&sched->lock);
3574 	mutex_unlock(&sched->reset.lock);
3575 
3576 	group_put(group);
3577 	return 0;
3578 }
3579 
3580 static struct panthor_group *group_from_handle(struct panthor_group_pool *pool,
3581 					       u32 group_handle)
3582 {
3583 	struct panthor_group *group;
3584 
3585 	xa_lock(&pool->xa);
3586 	group = group_get(xa_load(&pool->xa, group_handle));
3587 	xa_unlock(&pool->xa);
3588 
3589 	return group;
3590 }
3591 
3592 int panthor_group_get_state(struct panthor_file *pfile,
3593 			    struct drm_panthor_group_get_state *get_state)
3594 {
3595 	struct panthor_group_pool *gpool = pfile->groups;
3596 	struct panthor_device *ptdev = pfile->ptdev;
3597 	struct panthor_scheduler *sched = ptdev->scheduler;
3598 	struct panthor_group *group;
3599 
3600 	if (get_state->pad)
3601 		return -EINVAL;
3602 
3603 	group = group_from_handle(gpool, get_state->group_handle);
3604 	if (!group)
3605 		return -EINVAL;
3606 
3607 	memset(get_state, 0, sizeof(*get_state));
3608 
3609 	mutex_lock(&sched->lock);
3610 	if (group->timedout)
3611 		get_state->state |= DRM_PANTHOR_GROUP_STATE_TIMEDOUT;
3612 	if (group->fatal_queues) {
3613 		get_state->state |= DRM_PANTHOR_GROUP_STATE_FATAL_FAULT;
3614 		get_state->fatal_queues = group->fatal_queues;
3615 	}
3616 	if (group->innocent)
3617 		get_state->state |= DRM_PANTHOR_GROUP_STATE_INNOCENT;
3618 	mutex_unlock(&sched->lock);
3619 
3620 	group_put(group);
3621 	return 0;
3622 }
3623 
3624 int panthor_group_pool_create(struct panthor_file *pfile)
3625 {
3626 	struct panthor_group_pool *gpool;
3627 
3628 	gpool = kzalloc(sizeof(*gpool), GFP_KERNEL);
3629 	if (!gpool)
3630 		return -ENOMEM;
3631 
3632 	xa_init_flags(&gpool->xa, XA_FLAGS_ALLOC1);
3633 	pfile->groups = gpool;
3634 	return 0;
3635 }
3636 
3637 void panthor_group_pool_destroy(struct panthor_file *pfile)
3638 {
3639 	struct panthor_group_pool *gpool = pfile->groups;
3640 	struct panthor_group *group;
3641 	unsigned long i;
3642 
3643 	if (IS_ERR_OR_NULL(gpool))
3644 		return;
3645 
3646 	xa_for_each(&gpool->xa, i, group)
3647 		panthor_group_destroy(pfile, i);
3648 
3649 	xa_destroy(&gpool->xa);
3650 	kfree(gpool);
3651 	pfile->groups = NULL;
3652 }
3653 
3654 /**
3655  * panthor_fdinfo_gather_group_mem_info() - Retrieve aggregate size of all private kernel BO's
3656  * belonging to all the groups owned by an open Panthor file
3657  * @pfile: File.
3658  * @stats: Memory statistics to be updated.
3659  *
3660  */
3661 void
3662 panthor_fdinfo_gather_group_mem_info(struct panthor_file *pfile,
3663 				     struct drm_memory_stats *stats)
3664 {
3665 	struct panthor_group_pool *gpool = pfile->groups;
3666 	struct panthor_group *group;
3667 	unsigned long i;
3668 
3669 	if (IS_ERR_OR_NULL(gpool))
3670 		return;
3671 
3672 	xa_lock(&gpool->xa);
3673 	xa_for_each(&gpool->xa, i, group) {
3674 		stats->resident += group->fdinfo.kbo_sizes;
3675 		if (group->csg_id >= 0)
3676 			stats->active += group->fdinfo.kbo_sizes;
3677 	}
3678 	xa_unlock(&gpool->xa);
3679 }
3680 
3681 static void job_release(struct kref *ref)
3682 {
3683 	struct panthor_job *job = container_of(ref, struct panthor_job, refcount);
3684 
3685 	drm_WARN_ON(&job->group->ptdev->base, !list_empty(&job->node));
3686 
3687 	if (job->base.s_fence)
3688 		drm_sched_job_cleanup(&job->base);
3689 
3690 	if (job->done_fence && job->done_fence->ops)
3691 		dma_fence_put(job->done_fence);
3692 	else
3693 		dma_fence_free(job->done_fence);
3694 
3695 	group_put(job->group);
3696 
3697 	kfree(job);
3698 }
3699 
3700 struct drm_sched_job *panthor_job_get(struct drm_sched_job *sched_job)
3701 {
3702 	if (sched_job) {
3703 		struct panthor_job *job = container_of(sched_job, struct panthor_job, base);
3704 
3705 		kref_get(&job->refcount);
3706 	}
3707 
3708 	return sched_job;
3709 }
3710 
3711 void panthor_job_put(struct drm_sched_job *sched_job)
3712 {
3713 	struct panthor_job *job = container_of(sched_job, struct panthor_job, base);
3714 
3715 	if (sched_job)
3716 		kref_put(&job->refcount, job_release);
3717 }
3718 
3719 struct panthor_vm *panthor_job_vm(struct drm_sched_job *sched_job)
3720 {
3721 	struct panthor_job *job = container_of(sched_job, struct panthor_job, base);
3722 
3723 	return job->group->vm;
3724 }
3725 
3726 struct drm_sched_job *
3727 panthor_job_create(struct panthor_file *pfile,
3728 		   u16 group_handle,
3729 		   const struct drm_panthor_queue_submit *qsubmit,
3730 		   u64 drm_client_id)
3731 {
3732 	struct panthor_group_pool *gpool = pfile->groups;
3733 	struct panthor_job *job;
3734 	u32 credits;
3735 	int ret;
3736 
3737 	if (qsubmit->pad)
3738 		return ERR_PTR(-EINVAL);
3739 
3740 	/* If stream_addr is zero, so stream_size should be. */
3741 	if ((qsubmit->stream_size == 0) != (qsubmit->stream_addr == 0))
3742 		return ERR_PTR(-EINVAL);
3743 
3744 	/* Make sure the address is aligned on 64-byte (cacheline) and the size is
3745 	 * aligned on 8-byte (instruction size).
3746 	 */
3747 	if ((qsubmit->stream_addr & 63) || (qsubmit->stream_size & 7))
3748 		return ERR_PTR(-EINVAL);
3749 
3750 	/* bits 24:30 must be zero. */
3751 	if (qsubmit->latest_flush & GENMASK(30, 24))
3752 		return ERR_PTR(-EINVAL);
3753 
3754 	job = kzalloc(sizeof(*job), GFP_KERNEL);
3755 	if (!job)
3756 		return ERR_PTR(-ENOMEM);
3757 
3758 	kref_init(&job->refcount);
3759 	job->queue_idx = qsubmit->queue_index;
3760 	job->call_info.size = qsubmit->stream_size;
3761 	job->call_info.start = qsubmit->stream_addr;
3762 	job->call_info.latest_flush = qsubmit->latest_flush;
3763 	INIT_LIST_HEAD(&job->node);
3764 
3765 	job->group = group_from_handle(gpool, group_handle);
3766 	if (!job->group) {
3767 		ret = -EINVAL;
3768 		goto err_put_job;
3769 	}
3770 
3771 	if (!group_can_run(job->group)) {
3772 		ret = -EINVAL;
3773 		goto err_put_job;
3774 	}
3775 
3776 	if (job->queue_idx >= job->group->queue_count ||
3777 	    !job->group->queues[job->queue_idx]) {
3778 		ret = -EINVAL;
3779 		goto err_put_job;
3780 	}
3781 
3782 	/* Empty command streams don't need a fence, they'll pick the one from
3783 	 * the previously submitted job.
3784 	 */
3785 	if (job->call_info.size) {
3786 		job->done_fence = kzalloc(sizeof(*job->done_fence), GFP_KERNEL);
3787 		if (!job->done_fence) {
3788 			ret = -ENOMEM;
3789 			goto err_put_job;
3790 		}
3791 	}
3792 
3793 	job->profiling.mask = pfile->ptdev->profile_mask;
3794 	credits = calc_job_credits(job->profiling.mask);
3795 	if (credits == 0) {
3796 		ret = -EINVAL;
3797 		goto err_put_job;
3798 	}
3799 
3800 	ret = drm_sched_job_init(&job->base,
3801 				 &job->group->queues[job->queue_idx]->entity,
3802 				 credits, job->group, drm_client_id);
3803 	if (ret)
3804 		goto err_put_job;
3805 
3806 	return &job->base;
3807 
3808 err_put_job:
3809 	panthor_job_put(&job->base);
3810 	return ERR_PTR(ret);
3811 }
3812 
3813 void panthor_job_update_resvs(struct drm_exec *exec, struct drm_sched_job *sched_job)
3814 {
3815 	struct panthor_job *job = container_of(sched_job, struct panthor_job, base);
3816 
3817 	panthor_vm_update_resvs(job->group->vm, exec, &sched_job->s_fence->finished,
3818 				DMA_RESV_USAGE_BOOKKEEP, DMA_RESV_USAGE_BOOKKEEP);
3819 }
3820 
3821 void panthor_sched_unplug(struct panthor_device *ptdev)
3822 {
3823 	struct panthor_scheduler *sched = ptdev->scheduler;
3824 
3825 	cancel_delayed_work_sync(&sched->tick_work);
3826 
3827 	mutex_lock(&sched->lock);
3828 	if (sched->pm.has_ref) {
3829 		pm_runtime_put(ptdev->base.dev);
3830 		sched->pm.has_ref = false;
3831 	}
3832 	mutex_unlock(&sched->lock);
3833 }
3834 
3835 static void panthor_sched_fini(struct drm_device *ddev, void *res)
3836 {
3837 	struct panthor_scheduler *sched = res;
3838 	int prio;
3839 
3840 	if (!sched || !sched->csg_slot_count)
3841 		return;
3842 
3843 	cancel_delayed_work_sync(&sched->tick_work);
3844 
3845 	if (sched->wq)
3846 		destroy_workqueue(sched->wq);
3847 
3848 	if (sched->heap_alloc_wq)
3849 		destroy_workqueue(sched->heap_alloc_wq);
3850 
3851 	for (prio = PANTHOR_CSG_PRIORITY_COUNT - 1; prio >= 0; prio--) {
3852 		drm_WARN_ON(ddev, !list_empty(&sched->groups.runnable[prio]));
3853 		drm_WARN_ON(ddev, !list_empty(&sched->groups.idle[prio]));
3854 	}
3855 
3856 	drm_WARN_ON(ddev, !list_empty(&sched->groups.waiting));
3857 }
3858 
3859 int panthor_sched_init(struct panthor_device *ptdev)
3860 {
3861 	struct panthor_fw_global_iface *glb_iface = panthor_fw_get_glb_iface(ptdev);
3862 	struct panthor_fw_csg_iface *csg_iface = panthor_fw_get_csg_iface(ptdev, 0);
3863 	struct panthor_fw_cs_iface *cs_iface = panthor_fw_get_cs_iface(ptdev, 0, 0);
3864 	struct panthor_scheduler *sched;
3865 	u32 gpu_as_count, num_groups;
3866 	int prio, ret;
3867 
3868 	sched = drmm_kzalloc(&ptdev->base, sizeof(*sched), GFP_KERNEL);
3869 	if (!sched)
3870 		return -ENOMEM;
3871 
3872 	/* The highest bit in JOB_INT_* is reserved for globabl IRQs. That
3873 	 * leaves 31 bits for CSG IRQs, hence the MAX_CSGS clamp here.
3874 	 */
3875 	num_groups = min_t(u32, MAX_CSGS, glb_iface->control->group_num);
3876 
3877 	/* The FW-side scheduler might deadlock if two groups with the same
3878 	 * priority try to access a set of resources that overlaps, with part
3879 	 * of the resources being allocated to one group and the other part to
3880 	 * the other group, both groups waiting for the remaining resources to
3881 	 * be allocated. To avoid that, it is recommended to assign each CSG a
3882 	 * different priority. In theory we could allow several groups to have
3883 	 * the same CSG priority if they don't request the same resources, but
3884 	 * that makes the scheduling logic more complicated, so let's clamp
3885 	 * the number of CSG slots to MAX_CSG_PRIO + 1 for now.
3886 	 */
3887 	num_groups = min_t(u32, MAX_CSG_PRIO + 1, num_groups);
3888 
3889 	/* We need at least one AS for the MCU and one for the GPU contexts. */
3890 	gpu_as_count = hweight32(ptdev->gpu_info.as_present & GENMASK(31, 1));
3891 	if (!gpu_as_count) {
3892 		drm_err(&ptdev->base, "Not enough AS (%d, expected at least 2)",
3893 			gpu_as_count + 1);
3894 		return -EINVAL;
3895 	}
3896 
3897 	sched->ptdev = ptdev;
3898 	sched->sb_slot_count = CS_FEATURES_SCOREBOARDS(cs_iface->control->features);
3899 	sched->csg_slot_count = num_groups;
3900 	sched->cs_slot_count = csg_iface->control->stream_num;
3901 	sched->as_slot_count = gpu_as_count;
3902 	ptdev->csif_info.csg_slot_count = sched->csg_slot_count;
3903 	ptdev->csif_info.cs_slot_count = sched->cs_slot_count;
3904 	ptdev->csif_info.scoreboard_slot_count = sched->sb_slot_count;
3905 
3906 	sched->last_tick = 0;
3907 	sched->resched_target = U64_MAX;
3908 	sched->tick_period = msecs_to_jiffies(10);
3909 	INIT_DELAYED_WORK(&sched->tick_work, tick_work);
3910 	INIT_WORK(&sched->sync_upd_work, sync_upd_work);
3911 	INIT_WORK(&sched->fw_events_work, process_fw_events_work);
3912 
3913 	ret = drmm_mutex_init(&ptdev->base, &sched->lock);
3914 	if (ret)
3915 		return ret;
3916 
3917 	for (prio = PANTHOR_CSG_PRIORITY_COUNT - 1; prio >= 0; prio--) {
3918 		INIT_LIST_HEAD(&sched->groups.runnable[prio]);
3919 		INIT_LIST_HEAD(&sched->groups.idle[prio]);
3920 	}
3921 	INIT_LIST_HEAD(&sched->groups.waiting);
3922 
3923 	ret = drmm_mutex_init(&ptdev->base, &sched->reset.lock);
3924 	if (ret)
3925 		return ret;
3926 
3927 	INIT_LIST_HEAD(&sched->reset.stopped_groups);
3928 
3929 	/* sched->heap_alloc_wq will be used for heap chunk allocation on
3930 	 * tiler OOM events, which means we can't use the same workqueue for
3931 	 * the scheduler because works queued by the scheduler are in
3932 	 * the dma-signalling path. Allocate a dedicated heap_alloc_wq to
3933 	 * work around this limitation.
3934 	 *
3935 	 * FIXME: Ultimately, what we need is a failable/non-blocking GEM
3936 	 * allocation path that we can call when a heap OOM is reported. The
3937 	 * FW is smart enough to fall back on other methods if the kernel can't
3938 	 * allocate memory, and fail the tiling job if none of these
3939 	 * countermeasures worked.
3940 	 *
3941 	 * Set WQ_MEM_RECLAIM on sched->wq to unblock the situation when the
3942 	 * system is running out of memory.
3943 	 */
3944 	sched->heap_alloc_wq = alloc_workqueue("panthor-heap-alloc", WQ_UNBOUND, 0);
3945 	sched->wq = alloc_workqueue("panthor-csf-sched", WQ_MEM_RECLAIM | WQ_UNBOUND, 0);
3946 	if (!sched->wq || !sched->heap_alloc_wq) {
3947 		panthor_sched_fini(&ptdev->base, sched);
3948 		drm_err(&ptdev->base, "Failed to allocate the workqueues");
3949 		return -ENOMEM;
3950 	}
3951 
3952 	ret = drmm_add_action_or_reset(&ptdev->base, panthor_sched_fini, sched);
3953 	if (ret)
3954 		return ret;
3955 
3956 	ptdev->scheduler = sched;
3957 	return 0;
3958 }
3959