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